text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Compiler, makeGloballyAddressable } from '@cardstack/core/src/compiler';
import { CompiledCard, ModuleRef, RawCard, Unsaved } from '@cardstack/core/src/interfaces';
import { RawCardDeserializer, RawCardSerializer } from '@cardstack/core/src/serializers';
import { cardURL } from '@cardstack/core/src/utils';
import { JS_TYPE } from '@cardstack/core/src/utils/content';
import { CardstackError, NotFound, serializableError } from '@cardstack/core/src/utils/errors';
import { inject } from '@cardstack/di';
import { PoolClient } from 'pg';
import Cursor from 'pg-cursor';
import { BROWSER, NODE } from '../interfaces';
import { Expression, expressionToSql, param, PgPrimitive, upsert } from '../utils/expressions';
import CardBuilder from './card-builder';
import { transformSync } from '@babel/core';
import logger from '@cardstack/logger';
// @ts-ignore
import TransformModulesCommonJS from '@babel/plugin-transform-modules-commonjs';
// @ts-ignore
import ClassPropertiesPlugin from '@babel/plugin-proposal-class-properties';
const log = logger('hub/search-index');
export class SearchIndex {
private realmManager = inject('realm-manager', { as: 'realmManager' });
private builder = inject('card-builder', { as: 'builder' });
private database = inject('database-manager', { as: 'database' });
private fileCache = inject('file-cache', { as: 'fileCache' });
async indexAllRealms(): Promise<void> {
await Promise.all(
this.realmManager.realms.map((realm) => {
return this.runIndexing(realm.url, async (ops) => {
let meta = await ops.loadMeta();
let newMeta = await realm.reindex(ops, meta);
ops.setMeta(newMeta);
});
})
);
}
async getCard(cardURL: string): Promise<{ raw: RawCard; compiled: CompiledCard | undefined }> {
let db = await this.database.getPool();
let deserializer = new RawCardDeserializer();
try {
let {
rows: [result],
} = await db.query('SELECT compiled, "compileErrors" from cards where url = $1', [cardURL]);
if (!result) {
throw new NotFound(`Card ${cardURL} was not found`);
}
if (result.compileErrors) {
throw CardstackError.fromSerializableError(result.compileErrors);
}
return deserializer.deserialize(result.compiled.data, result.compiled);
} finally {
db.release();
}
}
async indexCard(
raw: RawCard,
compiled: CompiledCard<Unsaved, ModuleRef>,
compiler: Compiler<Unsaved>
): Promise<CompiledCard> {
return await this.runIndexing(raw.realm, async (ops) => {
return await ops.internalSave(raw, compiled, compiler);
});
}
private async runIndexing<Out>(realmURL: string, fn: (ops: IndexerRun) => Promise<Out>): Promise<Out> {
let db = await this.database.getPool();
try {
log.info(`starting to index realm`, realmURL);
let run = new IndexerRun(db, this.builder, realmURL, this.fileCache);
let result = await fn(run);
await run.finalize();
log.info(`finished indexing realm`, realmURL);
return result;
} finally {
db.release();
}
}
notify(_cardURL: string, _action: 'save' | 'delete'): void {
throw new Error('not implemented');
}
}
// this is the methods that we allow Realms to call
export interface IndexerHandle {
save(card: RawCard): Promise<void>;
delete(cardURL: string): Promise<void>;
beginReplaceAll(): Promise<void>;
finishReplaceAll(): Promise<void>;
}
class IndexerRun implements IndexerHandle {
private generation?: number;
private touchCounter = 0;
private touched = new Map<string, number>();
private newMeta: PgPrimitive = null;
constructor(
private db: PoolClient,
private builder: CardBuilder,
private realmURL: string,
private fileCache: SearchIndex['fileCache']
) {}
async loadMeta(): Promise<PgPrimitive> {
let metaResult = await this.db.query(
expressionToSql(['select meta from realm_metas where realm=', param(this.realmURL)])
);
return metaResult.rows[0]?.meta;
}
setMeta(meta: PgPrimitive) {
this.newMeta = meta;
}
private async storeMeta(): Promise<void> {
await this.db.query(
expressionToSql(
upsert('realm_metas', 'realm_metas_pkey', { realm: param(this.realmURL), meta: param(this.newMeta) })
)
);
}
async finalize() {
await this.possiblyInvalidatedCards(async (cardURL: string, deps: string[], raw: RawCard) => {
if (!this.isValid(cardURL, deps)) {
log.trace(`reindexing %s because %s`, cardURL, deps);
await this.save(raw);
}
});
await this.storeMeta();
}
// This doesn't need to recurse because we intend for the `deps` column to
// contain all deep references, not just immediate references
private async possiblyInvalidatedCards(fn: (cardURL: string, deps: string[], raw: RawCard) => Promise<void>) {
const queryBatchSize = 100;
let queue = [...this.touched.keys()];
for (let i = 0; i < queue.length; i += queryBatchSize) {
let queryRefs = queue.slice(i, i + queryBatchSize);
await this.iterateThroughRows(
['select url, deps, raw from cards where', param(queryRefs), '&&', 'deps'],
async (row) => {
let deserializer = new RawCardDeserializer();
let { raw } = deserializer.deserialize(row.raw.data, row.raw);
await fn(row.url, row.deps, raw);
}
);
}
}
private isValid(cardURL: string, deps: string[]): boolean {
let maybeTouchedAt = this.touched.get(cardURL);
if (maybeTouchedAt == null) {
// our card hasn't been updated at all, so it definitely needs to be redone
return false;
}
let cardTouchedAt = maybeTouchedAt;
return deps.every((dep) => {
let depTouchedAt = this.touched.get(dep);
depTouchedAt == null || depTouchedAt < cardTouchedAt;
});
}
private async iterateThroughRows(expression: Expression, fn: (row: Record<string, any>) => Promise<void>) {
const rowBatchSize = 100;
let { text, values } = expressionToSql(expression);
let cursor: Cursor = this.db.query(new Cursor(text, values) as any);
let rows;
do {
rows = await readCursor(cursor, rowBatchSize);
for (let row of rows) {
await fn(row);
}
} while (rows.length > 0);
}
// available to each realm's indexer
async save(card: RawCard): Promise<void> {
let compiler = await this.builder.compileCardFromRaw(card);
try {
let compiledCard = await compiler.compile();
await this.internalSave(card, compiledCard, compiler);
} catch (err: any) {
await this.saveErrorState(card, err, compiler);
}
}
// used directly by the hub when mutating cards
async internalSave(
rawCard: RawCard,
compiledCard: CompiledCard<Unsaved, ModuleRef>,
compiler: Compiler<Unsaved>
): Promise<CompiledCard> {
let definedCard = makeGloballyAddressable(cardURL(rawCard), compiledCard, (local, type, src) =>
this.define(cardURL(rawCard), local, type, src)
);
return await this.writeToIndex(rawCard, definedCard, compiler);
}
private define(cardURL: string, localPath: string, type: string, source: string): string {
switch (type) {
case JS_TYPE:
this.fileCache.setModule(BROWSER, cardURL, localPath, source);
return this.fileCache.setModule(NODE, cardURL, localPath, this.transformToCommonJS(localPath, source));
default:
return this.fileCache.writeAsset(cardURL, localPath, source);
}
}
private transformToCommonJS(moduleURL: string, source: string): string {
let out = transformSync(source, {
configFile: false,
babelrc: false,
filenameRelative: moduleURL,
plugins: [ClassPropertiesPlugin, TransformModulesCommonJS],
});
return out!.code!;
}
private async writeToIndex(
card: RawCard,
compiledCard: CompiledCard,
compiler: Compiler<Unsaved>
): Promise<CompiledCard> {
let url = cardURL(card);
let expression = upsert('cards', 'cards_pkey', {
url: param(url),
realm: param(this.realmURL),
generation: param(this.generation || null),
ancestors: param(ancestorsOf(compiledCard)),
data: param(card.data ?? null),
raw: param(new RawCardSerializer().serialize(card)),
compiled: param(new RawCardSerializer().serialize(card, compiledCard)),
searchData: param(card.data ? searchOptimizedData(card.data, compiledCard) : null),
compileErrors: param(null),
deps: param([...compiler.dependencies]),
});
await this.db.query(expressionToSql(expression));
this.touched.set(url, this.touchCounter++);
return compiledCard;
}
private async saveErrorState(card: RawCard, err: any, compiler: Compiler): Promise<void> {
let url = cardURL(card);
let expression = upsert('cards', 'cards_pkey', {
url: param(url),
realm: param(this.realmURL),
generation: param(this.generation || null),
ancestors: param(null),
data: param(card.data ?? null),
raw: param(new RawCardSerializer().serialize(card)),
compiled: param(null),
searchData: param(null),
compileErrors: param(serializableError(err)),
deps: param([...compiler.dependencies]),
});
this.touched.set(url, this.touchCounter++);
await this.db.query(expressionToSql(expression));
}
async delete(cardURL: string): Promise<void> {
await this.db.query(`DELETE from cards where url=$1`, [cardURL]);
}
async beginReplaceAll(): Promise<void> {
this.generation = Math.floor(Math.random() * 1000000000);
}
async finishReplaceAll(): Promise<void> {
await this.db.query('DELETE FROM cards where realm = $1 AND (generation != $2 OR generation IS NULL)', [
this.realmURL,
this.generation,
]);
}
}
function ancestorsOf(compiledCard: CompiledCard): string[] {
if (!compiledCard.adoptsFrom) {
return [];
}
return [compiledCard.adoptsFrom.url, ...ancestorsOf(compiledCard.adoptsFrom)];
}
function searchOptimizedData(data: Record<string, any>, compiled: CompiledCard): Record<string, any> {
let result: Record<string, any> = {};
for (let fieldName of Object.keys(compiled.fields)) {
let currentCard: CompiledCard | undefined = compiled;
do {
let entry = result[currentCard.url];
if (!entry) {
entry = result[currentCard.url] = {};
}
entry[fieldName] = data[fieldName];
currentCard = currentCard.adoptsFrom;
} while (currentCard && currentCard.fields[fieldName]);
}
return result;
}
declare module '@cardstack/di' {
interface KnownServices {
searchIndex: SearchIndex;
}
}
function readCursor(cursor: Cursor, rowCount: number): Promise<Record<string, any>[]> {
return new Promise((resolve, reject) => {
cursor.read(rowCount, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
} | the_stack |
import * as ts from "typescript";
import * as lua from "../../LuaAST";
import { assertNever } from "../../utils";
import { FunctionVisitor, TransformationContext, Visitors } from "../context";
import {
invalidMultiFunctionUse,
undefinedInArrayLiteral,
unsupportedAccessorInObjectLiteral,
} from "../utils/diagnostics";
import { createExportedIdentifier, getSymbolExportScope } from "../utils/export";
import { LuaLibFeature, transformLuaLibFunction } from "../utils/lualib";
import { createSafeName, hasUnsafeIdentifierName, hasUnsafeSymbolName } from "../utils/safe-names";
import { getSymbolIdOfSymbol, trackSymbolReference } from "../utils/symbols";
import { isArrayType } from "../utils/typescript";
import { transformFunctionLikeDeclaration } from "./function";
import { moveToPrecedingTemp, transformExpressionList } from "./expression-list";
import { findMultiAssignmentViolations } from "./language-extensions/multi";
// TODO: Move to object-literal.ts?
export function transformPropertyName(context: TransformationContext, node: ts.PropertyName): lua.Expression {
if (ts.isComputedPropertyName(node)) {
return context.transformExpression(node.expression);
} else if (ts.isIdentifier(node)) {
return lua.createStringLiteral(node.text);
} else if (ts.isPrivateIdentifier(node)) {
throw new Error("PrivateIdentifier is not supported");
} else {
return context.transformExpression(node);
}
}
export function createShorthandIdentifier(
context: TransformationContext,
valueSymbol: ts.Symbol | undefined,
propertyIdentifier: ts.Identifier
): lua.Expression {
const propertyName = propertyIdentifier.text;
const isUnsafeName = valueSymbol
? hasUnsafeSymbolName(context, valueSymbol, propertyIdentifier)
: hasUnsafeIdentifierName(context, propertyIdentifier, false);
const name = isUnsafeName ? createSafeName(propertyName) : propertyName;
let identifier = context.transformExpression(ts.factory.createIdentifier(name));
lua.setNodeOriginal(identifier, propertyIdentifier);
if (valueSymbol !== undefined && lua.isIdentifier(identifier)) {
identifier.symbolId = getSymbolIdOfSymbol(context, valueSymbol);
const exportScope = getSymbolExportScope(context, valueSymbol);
if (exportScope) {
identifier = createExportedIdentifier(context, identifier, exportScope);
}
}
return identifier;
}
const transformNumericLiteralExpression: FunctionVisitor<ts.NumericLiteral> = expression => {
if (expression.text === "Infinity") {
const math = lua.createIdentifier("math");
const huge = lua.createStringLiteral("huge");
return lua.createTableIndexExpression(math, huge, expression);
}
return lua.createNumericLiteral(Number(expression.text), expression);
};
const transformObjectLiteralExpression: FunctionVisitor<ts.ObjectLiteralExpression> = (expression, context) => {
const violations = findMultiAssignmentViolations(context, expression);
if (violations.length > 0) {
context.diagnostics.push(...violations.map(e => invalidMultiFunctionUse(e)));
return lua.createNilLiteral(expression);
}
const properties: lua.Expression[] = [];
const initializers: ts.Node[] = [];
const keyPrecedingStatements: lua.Statement[][] = [];
const valuePrecedingStatements: lua.Statement[][] = [];
let lastPrecedingStatementsIndex = -1;
for (let i = 0; i < expression.properties.length; ++i) {
const element = expression.properties[i];
// Transform key and cache preceding statements
context.pushPrecedingStatements();
const name = element.name ? transformPropertyName(context, element.name) : undefined;
let precedingStatements = context.popPrecedingStatements();
keyPrecedingStatements.push(precedingStatements);
if (precedingStatements.length > 0) {
lastPrecedingStatementsIndex = i;
}
// Transform value and cache preceding statements
context.pushPrecedingStatements();
if (ts.isPropertyAssignment(element)) {
const expression = context.transformExpression(element.initializer);
properties.push(lua.createTableFieldExpression(expression, name, element));
initializers.push(element.initializer);
} else if (ts.isShorthandPropertyAssignment(element)) {
const valueSymbol = context.checker.getShorthandAssignmentValueSymbol(element);
if (valueSymbol) {
trackSymbolReference(context, valueSymbol, element.name);
}
const identifier = createShorthandIdentifier(context, valueSymbol, element.name);
properties.push(lua.createTableFieldExpression(identifier, name, element));
initializers.push(element);
} else if (ts.isMethodDeclaration(element)) {
const expression = transformFunctionLikeDeclaration(element, context);
properties.push(lua.createTableFieldExpression(expression, name, element));
initializers.push(element);
} else if (ts.isSpreadAssignment(element)) {
const type = context.checker.getTypeAtLocation(element.expression);
let tableExpression: lua.Expression;
if (isArrayType(context, type)) {
tableExpression = transformLuaLibFunction(
context,
LuaLibFeature.ArrayToObject,
element.expression,
context.transformExpression(element.expression)
);
} else {
tableExpression = context.transformExpression(element.expression);
}
properties.push(tableExpression);
initializers.push(element.expression);
} else if (ts.isAccessor(element)) {
context.diagnostics.push(unsupportedAccessorInObjectLiteral(element));
} else {
assertNever(element);
}
precedingStatements = context.popPrecedingStatements();
valuePrecedingStatements.push(precedingStatements);
if (precedingStatements.length > 0) {
lastPrecedingStatementsIndex = i;
}
}
// Expressions referenced before others that produced preceding statements need to be cached in temps
if (lastPrecedingStatementsIndex >= 0) {
for (let i = 0; i < properties.length; ++i) {
const property = properties[i];
// Bubble up key's preceding statements
context.addPrecedingStatements(keyPrecedingStatements[i]);
// Cache computed property name in temp if before the last expression that generated preceding statements
if (i <= lastPrecedingStatementsIndex && lua.isTableFieldExpression(property) && property.key) {
property.key = moveToPrecedingTemp(context, property.key, expression.properties[i].name);
}
// Bubble up value's preceding statements
context.addPrecedingStatements(valuePrecedingStatements[i]);
// Cache property value in temp if before the last expression that generated preceding statements
if (i < lastPrecedingStatementsIndex) {
if (lua.isTableFieldExpression(property)) {
property.value = moveToPrecedingTemp(context, property.value, initializers[i]);
} else {
properties[i] = moveToPrecedingTemp(context, property, initializers[i]);
}
}
}
}
// Sort into field expressions and tables to pass into __TS__ObjectAssign
let fields: lua.TableFieldExpression[] = [];
const tableExpressions: lua.Expression[] = [];
for (const property of properties) {
if (lua.isTableFieldExpression(property)) {
fields.push(property);
} else {
if (fields.length > 0) {
tableExpressions.push(lua.createTableExpression(fields));
}
tableExpressions.push(property);
fields = [];
}
}
if (tableExpressions.length === 0) {
return lua.createTableExpression(fields, expression);
} else {
if (fields.length > 0) {
const tableExpression = lua.createTableExpression(fields, expression);
tableExpressions.push(tableExpression);
}
if (tableExpressions[0].kind !== lua.SyntaxKind.TableExpression) {
tableExpressions.unshift(lua.createTableExpression(undefined, expression));
}
return transformLuaLibFunction(context, LuaLibFeature.ObjectAssign, expression, ...tableExpressions);
}
};
const transformArrayLiteralExpression: FunctionVisitor<ts.ArrayLiteralExpression> = (expression, context) => {
// Disallow using undefined/null in array literals
checkForUndefinedOrNullInArrayLiteral(expression, context);
const filteredElements = expression.elements.map(e =>
ts.isOmittedExpression(e) ? ts.factory.createIdentifier("undefined") : e
);
const values = transformExpressionList(context, filteredElements).map(e => lua.createTableFieldExpression(e));
return lua.createTableExpression(values, expression);
};
function checkForUndefinedOrNullInArrayLiteral(array: ts.ArrayLiteralExpression, context: TransformationContext) {
// Look for last non-nil element in literal
let lastNonUndefinedIndex = array.elements.length - 1;
for (; lastNonUndefinedIndex >= 0; lastNonUndefinedIndex--) {
if (!isUndefinedOrNull(array.elements[lastNonUndefinedIndex])) {
break;
}
}
// Add diagnostics for non-trailing nil elements in array literal
for (let i = 0; i < array.elements.length; i++) {
if (i < lastNonUndefinedIndex && isUndefinedOrNull(array.elements[i])) {
context.diagnostics.push(undefinedInArrayLiteral(array.elements[i]));
}
}
}
function isUndefinedOrNull(node: ts.Node) {
return (
node.kind === ts.SyntaxKind.UndefinedKeyword ||
node.kind === ts.SyntaxKind.NullKeyword ||
(ts.isIdentifier(node) && node.text === "undefined")
);
}
export const literalVisitors: Visitors = {
[ts.SyntaxKind.NullKeyword]: node => lua.createNilLiteral(node),
[ts.SyntaxKind.TrueKeyword]: node => lua.createBooleanLiteral(true, node),
[ts.SyntaxKind.FalseKeyword]: node => lua.createBooleanLiteral(false, node),
[ts.SyntaxKind.NumericLiteral]: transformNumericLiteralExpression,
[ts.SyntaxKind.StringLiteral]: node => lua.createStringLiteral(node.text, node),
[ts.SyntaxKind.NoSubstitutionTemplateLiteral]: node => lua.createStringLiteral(node.text, node),
[ts.SyntaxKind.ObjectLiteralExpression]: transformObjectLiteralExpression,
[ts.SyntaxKind.ArrayLiteralExpression]: transformArrayLiteralExpression,
}; | the_stack |
import type { Cause } from "../Cause/cause"
import * as Tp from "../Collections/Immutable/Tuple"
import type { ExecutionStrategy } from "../Effect/ExecutionStrategy"
import { parallel, sequential } from "../Effect/ExecutionStrategy"
import { pipe } from "../Function"
import { makeRef } from "../Ref"
import * as T from "./deps-core"
import { fromEffect } from "./fromEffect"
import { makeExit_ } from "./makeExit"
import type { Managed } from "./managed"
import { managedApply } from "./managed"
import type { ReleaseMap } from "./ReleaseMap"
import * as add from "./ReleaseMap/add"
import * as addIfOpen from "./ReleaseMap/addIfOpen"
import type { Finalizer } from "./ReleaseMap/finalizer"
import * as makeReleaseMap from "./ReleaseMap/makeReleaseMap"
import * as release from "./ReleaseMap/release"
import * as releaseAll from "./ReleaseMap/releaseAll"
import { use_ } from "./use"
/**
* Returns a managed that models the execution of this managed, followed by
* the passing of its value to the specified continuation function `f`,
* followed by the managed that it returns.
*
* @ets_data_first chain_
*/
export function chain<A, R2, E2, A2>(
f: (a: A) => Managed<R2, E2, A2>,
__trace?: string
) {
return <R, E>(self: Managed<R, E, A>) => chain_(self, f, __trace)
}
/**
* Returns a managed that models the execution of this managed, followed by
* the passing of its value to the specified continuation function `f`,
* followed by the managed that it returns.
*/
export function chain_<R, E, A, R2, E2, A2>(
self: Managed<R, E, A>,
f: (a: A) => Managed<R2, E2, A2>,
__trace?: string
) {
return managedApply<R & R2, E | E2, A2>(
T.chain_(self.effect, ({ tuple: [releaseSelf, a] }) =>
T.map_(
f(a).effect,
({ tuple: [releaseThat, b] }) =>
Tp.tuple(
(e) =>
T.chain_(T.result(releaseThat(e)), (e1) =>
T.chain_(T.result(releaseSelf(e)), (e2) =>
T.done(T.exitZipRight_(e1, e2), __trace)
)
),
b
),
__trace
)
)
)
}
/**
* Imports a synchronous side-effect into a pure value
*/
export function succeedWith<A>(effect: () => A, __trace?: string) {
return fromEffect(T.succeedWith(effect, __trace))
}
/**
* Ensures that `f` is executed when this Managed is finalized, after
* the existing finalizer.
*
* For usecases that need access to the Managed's result, see `onExit`.
*/
export function ensuring_<R, E, A, R2, X>(
self: Managed<R, E, A>,
f: T.Effect<R2, never, X>,
__trace?: string
) {
return onExit_(self, () => f, __trace)
}
/**
* Ensures that `f` is executed when this Managed is finalized, after
* the existing finalizer.
*
* For usecases that need access to the Managed's result, see `onExit`.
*
* @ets_data_first ensuring_
*/
export function ensuring<R2, X>(f: T.Effect<R2, never, X>, __trace?: string) {
return <R, E, A>(self: Managed<R, E, A>) => ensuring_(self, f, __trace)
}
/**
* Returns an effect that models failure with the specified error. The moral equivalent of throw for pure code.
*/
export function fail<E>(e: E, __trace?: string) {
return fromEffect(T.fail(e, __trace))
}
/**
* Returns an effect that models failure with the specified error. The moral equivalent of throw for pure code.
*/
export function failWith<E>(e: () => E, __trace?: string) {
return fromEffect(T.failWith(e, __trace))
}
/**
* Creates an effect that executes a finalizer stored in a `Ref`.
* The `Ref` is yielded as the result of the effect, allowing for
* control flows that require mutating finalizers.
*/
export function finalizerRef(initial: Finalizer, __trace?: string) {
return makeExit_(
makeRef(initial),
(ref, exit) => T.chain_(ref.get, (f) => f(exit)),
__trace
)
}
/**
* A more powerful version of `foldM` that allows recovering from any kind of failure except interruptions.
*
* @ets_data_first foldCauseM_
*/
export function foldCauseM<E, A, R1, E1, A1, R2, E2, A2>(
f: (cause: Cause<E>) => Managed<R1, E1, A1>,
g: (a: A) => Managed<R2, E2, A2>,
__trace?: string
) {
return <R>(self: Managed<R, E, A>) => foldCauseM_(self, f, g, __trace)
}
/**
* A more powerful version of `foldM` that allows recovering from any kind of failure except interruptions.
*/
export function foldCauseM_<R, E, A, R1, E1, A1, R2, E2, A2>(
self: Managed<R, E, A>,
f: (cause: Cause<E>) => Managed<R1, E1, A1>,
g: (a: A) => Managed<R2, E2, A2>,
__trace?: string
) {
return managedApply<R & R1 & R2, E1 | E2, A1 | A2>(
pipe(
self.effect,
T.foldCauseM(
(c) => f(c).effect,
({ tuple: [_, a] }) => g(a).effect,
__trace
)
)
)
}
/**
* Lifts a `Effect< R, E, A>` into `Managed< R, E, A>` with a release action.
* The acquire and release actions will be performed uninterruptibly.
*
* @ets_data_first make_
*/
export function make<R1, A>(
release: (a: A) => T.Effect<R1, never, unknown>,
__trace?: string
): <R, E>(acquire: T.Effect<R, E, A>) => Managed<R & R1, E, A> {
return (acquire) => make_(acquire, release, __trace)
}
/**
* Lifts a `Effect< R, E, A>` into `Managed< R, E, A>` with a release action.
* The acquire and release actions will be performed uninterruptibly.
*/
export function make_<R, E, A, R1>(
acquire: T.Effect<R, E, A>,
release: (a: A) => T.Effect<R1, never, unknown>,
__trace?: string
): Managed<R & R1, E, A> {
return makeExit_(acquire, release, __trace)
}
/**
* Lifts a `Effect< R, E, A>` into `Managed< R, E, A>` with a release action.
* The acquire action will be performed interruptibly, while release
* will be performed uninterruptibly.
*
* @ets_data_first makeInterruptible_
*/
export function makeInterruptible<A, R1>(
release: (a: A) => T.Effect<R1, never, unknown>,
__trace?: string
) {
return <R, E>(acquire: T.Effect<R, E, A>) =>
makeInterruptible_(acquire, release, __trace)
}
/**
* Lifts a `Effect< R, E, A>` into `Managed< R, E, A>` with a release action.
* The acquire action will be performed interruptibly, while release
* will be performed uninterruptibly.
*/
export function makeInterruptible_<R, E, A, R1>(
acquire: T.Effect<R, E, A>,
release: (a: A) => T.Effect<R1, never, unknown>,
__trace?: string
) {
return onExitFirst_(fromEffect(acquire, __trace), T.exitForeach(release), __trace)
}
/**
* Construct a `ReleaseMap` wrapped in a `Managed`. The `ReleaseMap` will
* be released with the specified `ExecutionStrategy` as the release action
* for the resulting `Managed`.
*/
export function makeManagedReleaseMap(
es: ExecutionStrategy,
__trace?: string
): Managed<unknown, never, ReleaseMap> {
return makeExit_(
makeReleaseMap.makeReleaseMap,
(rm, e) => releaseAll.releaseAll(e, es)(rm),
__trace
)
}
/**
* Creates a `Managed` from a `Reservation` produced by an effect. Evaluating
* the effect that produces the reservation will be performed *uninterruptibly*,
* while the acquisition step of the reservation will be performed *interruptibly*.
* The release step will be performed uninterruptibly as usual.
*
* This two-phase acquisition allows for resource acquisition flows that can be
* safely interrupted and released.
*/
export function makeReserve<R, E, R2, E2, A>(
reservation: T.Effect<R, E, Reservation<R2, E2, A>>,
__trace?: string
) {
return managedApply<R & R2, E | E2, A>(
T.uninterruptibleMask(({ restore }) =>
pipe(
T.do,
T.bind("tp", () => T.environment<Tp.Tuple<[R & R2, ReleaseMap]>>()),
T.let("r", (s) => s.tp.get(0)),
T.let("releaseMap", (s) => s.tp.get(1)),
T.bind("reserved", (s) => T.provideAll_(reservation, s.r)),
T.bind("releaseKey", (s) =>
addIfOpen.addIfOpen((x) =>
T.provideAll_(s.reserved.release(x), s.r, __trace)
)(s.releaseMap)
),
T.bind("finalizerAndA", (s) => {
const k = s.releaseKey
switch (k._tag) {
case "None": {
return T.interrupt
}
case "Some": {
return T.map_(
restore(
T.provideSome_(
s.reserved.acquire,
({ tuple: [r] }: Tp.Tuple<[R & R2, ReleaseMap]>) => r,
__trace
)
),
(a): Tp.Tuple<[Finalizer, A]> =>
Tp.tuple((e) => release.release(k.value, e)(s.releaseMap), a)
)
}
}
}),
T.map((s) => s.finalizerAndA)
)
)
)
}
/**
* Returns a managed whose success is mapped by the specified `f` function.
*
* @ets_data_first map_
*/
export function map<A, B>(f: (a: A) => B, __trace?: string) {
return <R, E>(self: Managed<R, E, A>) => map_(self, f, __trace)
}
/**
* Returns a managed whose success is mapped by the specified `f` function.
*/
export function map_<R, E, A, B>(
self: Managed<R, E, A>,
f: (a: A) => B,
__trace?: string
) {
return managedApply<R, E, B>(
T.map_(self.effect, ({ tuple: [fin, a] }) => Tp.tuple(fin, f(a)), __trace)
)
}
/**
* Returns a managed whose success is mapped by the specified `f` function.
*/
export function mapM_<R, E, A, R2, E2, B>(
self: Managed<R, E, A>,
f: (a: A) => T.Effect<R2, E2, B>,
__trace?: string
) {
return managedApply<R & R2, E | E2, B>(
T.chain_(self.effect, ({ tuple: [fin, a] }) =>
T.provideSome_(
T.map_(f(a), (b) => Tp.tuple(fin, b), __trace),
({ tuple: [r] }: Tp.Tuple<[R & R2, ReleaseMap]>) => r
)
)
)
}
/**
* Returns a managed whose success is mapped by the specified `f` function.
*/
export function mapM<A, R2, E2, B>(f: (a: A) => T.Effect<R2, E2, B>, __trace?: string) {
return <R, E>(self: Managed<R, E, A>) => mapM_(self, f, __trace)
}
/**
* Ensures that a cleanup function runs when this Managed is finalized, after
* the existing finalizers.
*/
export function onExit_<R, E, A, R2, X>(
self: Managed<R, E, A>,
cleanup: (exit: T.Exit<E, A>) => T.Effect<R2, never, X>,
__trace?: string
) {
return managedApply<R & R2, E, A>(
T.uninterruptibleMask(({ restore }) =>
pipe(
T.do,
T.bind("tp", () => T.environment<Tp.Tuple<[R & R2, ReleaseMap]>>()),
T.let("r", (s) => s.tp.get(0)),
T.let("outerReleaseMap", (s) => s.tp.get(1)),
T.bind("innerReleaseMap", () => makeReleaseMap.makeReleaseMap),
T.bind("exitEA", (s) =>
T.provideAll_(
T.result(restore(T.map_(self.effect, ({ tuple: [_, a] }) => a))),
Tp.tuple(s.r, s.innerReleaseMap)
)
),
T.bind("releaseMapEntry", (s) =>
add.add((e) =>
pipe(
releaseAll.releaseAll(e, sequential)(s.innerReleaseMap),
T.result,
T.zipWith(
pipe(cleanup(s.exitEA), T.provideAll(s.r), T.result),
(l, r) => T.done(T.exitZipRight_(l, r)),
__trace
),
T.flatten
)
)(s.outerReleaseMap)
),
T.bind("a", (s) => T.done(s.exitEA)),
T.map((s) => Tp.tuple(s.releaseMapEntry, s.a))
)
)
)
}
/**
* Ensures that a cleanup function runs when this Managed is finalized, after
* the existing finalizers.
*
* @ets_data_first onExit_
*/
export function onExit<E, A, R2, X>(
cleanup: (exit: T.Exit<E, A>) => T.Effect<R2, never, X>,
__trace?: string
) {
return <R>(self: Managed<R, E, A>) => onExit_(self, cleanup, __trace)
}
/**
* Ensures that a cleanup function runs when this Managed is finalized, before
* the existing finalizers.
*
* @ets_data_first onExitFirst_
*/
export function onExitFirst<E, A, R2, X>(
cleanup: (exit: T.Exit<E, A>) => T.Effect<R2, never, X>,
__trace?: string
) {
return <R>(self: Managed<R, E, A>) => onExitFirst_(self, cleanup, __trace)
}
/**
* Ensures that a cleanup function runs when this Managed is finalized, before
* the existing finalizers.
*/
export function onExitFirst_<R, E, A, R2, X>(
self: Managed<R, E, A>,
cleanup: (exit: T.Exit<E, A>) => T.Effect<R2, never, X>,
__trace?: string
) {
return managedApply<R & R2, E, A>(
T.uninterruptibleMask(({ restore }) =>
pipe(
T.do,
T.bind("tp", () => T.environment<Tp.Tuple<[R & R2, ReleaseMap]>>()),
T.let("r", (s) => s.tp.get(0)),
T.let("outerReleaseMap", (s) => s.tp.get(1)),
T.bind("innerReleaseMap", () => makeReleaseMap.makeReleaseMap),
T.bind("exitEA", (s) =>
T.provideAll_(
T.result(restore(T.map_(self.effect, ({ tuple: [_, a] }) => a))),
Tp.tuple(s.r, s.innerReleaseMap)
)
),
T.bind("releaseMapEntry", (s) =>
add.add((e) =>
T.flatten(
T.zipWith_(
T.result(T.provideAll_(cleanup(s.exitEA), s.r, __trace)),
T.result(releaseAll.releaseAll(e, sequential)(s.innerReleaseMap)),
(l, r) => T.done(T.exitZipRight_(l, r))
)
)
)(s.outerReleaseMap)
),
T.bind("a", (s) => T.done(s.exitEA)),
T.map((s) => Tp.tuple(s.releaseMapEntry, s.a))
)
)
)
}
/**
* Like provideSome_ for effect but for Managed
*/
export function provideSome_<R, E, A, R0>(
self: Managed<R, E, A>,
f: (r0: R0) => R,
__trace?: string
): Managed<R0, E, A> {
return managedApply(
T.accessM(({ tuple: [r0, rm] }: Tp.Tuple<[R0, ReleaseMap]>) =>
T.provideAll_(self.effect, Tp.tuple(f(r0), rm), __trace)
)
)
}
/**
* Like provideSome for effect but for Managed
*
* @ets_data_first provideSome_
*/
export function provideSome<R, R0>(f: (r0: R0) => R, __trace?: string) {
return <E, A>(self: Managed<R, E, A>) => provideSome_(self, f, __trace)
}
/**
* Provides the `Managed` effect with its required environment, which eliminates
* its dependency on `R`.
*
* @ets_data_first provideAll_
*/
export function provideAll<R>(r: R, __trace?: string) {
return <E, A>(self: Managed<R, E, A>) => provideAll_(self, r)
}
/**
* Provides the `Managed` effect with its required environment, which eliminates
* its dependency on `R`.
*/
export function provideAll_<R, E, A>(self: Managed<R, E, A>, r: R, __trace?: string) {
return provideSome_(self, () => r, __trace)
}
/**
* A `Reservation<R, E, A>` encapsulates resource acquisition and disposal
* without specifying when or how that resource might be used.
*
* See `Managed#reserve` and `Effect#reserve` for details of usage.
*/
export class Reservation<R, E, A> {
static of = <R, E, A, R2>(
acquire: T.Effect<R, E, A>,
release: (exit: T.Exit<any, any>) => T.Effect<R2, never, unknown>
) => new Reservation<R & R2, E, A>(acquire, release)
private constructor(
readonly acquire: T.Effect<R, E, A>,
readonly release: (exit: T.Exit<any, any>) => T.Effect<R, never, unknown>
) {}
}
/**
* Make a new reservation
*/
export function makeReservation_<R, E, A, R2>(
acquire: T.Effect<R, E, A>,
release: (exit: T.Exit<any, any>) => T.Effect<R2, never, unknown>
) {
return Reservation.of(acquire, release)
}
/**
* Make a new reservation
*
* @ets_data_first makeReservation_
*/
export function makeReservation<R2>(
release: (exit: T.Exit<any, any>) => T.Effect<R2, never, unknown>
) {
return <R, E, A>(acquire: T.Effect<R, E, A>) => Reservation.of(acquire, release)
}
/**
* Lifts a pure `Reservation< R, E, A>` into `Managed< R, E, A>`. The acquisition step
* is performed interruptibly.
*/
export function reserve<R, E, A>(reservation: Reservation<R, E, A>, __trace?: string) {
return makeReserve(T.succeed(reservation), __trace)
}
/**
* Returns a managed that effectfully peeks at the acquired resource.
*/
export function tap_<A, R, R2, E, E2, X>(
self: Managed<R, E, A>,
f: (a: A) => Managed<R2, E2, X>,
__trace?: string
) {
return chain_(self, (a) => map_(f(a), () => a), __trace)
}
/**
* Returns a managed that effectfully peeks at the acquired resource.
*
* @ets_data_first tap_
*/
export function tap<A, R2, E2, X>(f: (a: A) => Managed<R2, E2, X>, __trace?: string) {
return <R, E>(self: Managed<R, E, A>) => tap_(self, f, __trace)
}
/**
* Runs the acquire and release actions and returns the result of this
* managed effect. Note that this is only safe if the result of this managed
* effect is valid outside its scope.
*/
export function useNow<R, E, A>(self: Managed<R, E, A>, __trace?: string) {
return use_(self, T.succeed, __trace)
}
/**
* Use the resource until interruption. Useful for resources that you want
* to acquire and use as long as the application is running, like a
* HTTP server.
*/
export function useForever<R, E, A>(self: Managed<R, E, A>, __trace?: string) {
return use_(self, () => T.never, __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in sequence, combining their results with the specified `f` function.
*/
export function zip_<R, E, A, R2, E2, A2>(
self: Managed<R, E, A>,
that: Managed<R2, E2, A2>,
__trace?: string
) {
return zipWith_(self, that, (a, a2) => [a, a2] as [A, A2], __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in sequence, combining their results with the specified `f` function.
*
* @ets_data_first zip_
*/
export function zip<R2, E2, A2>(that: Managed<R2, E2, A2>, __trace?: string) {
return <R, E, A>(self: Managed<R, E, A>) => zip_(self, that, __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in sequence, combining their results with the specified `f` function.
*
* @ets_data_first zipWith_
*/
export function zipWith<A, R2, E2, A2, B>(
that: Managed<R2, E2, A2>,
f: (a: A, a2: A2) => B,
__trace?: string
) {
return <R, E>(self: Managed<R, E, A>) => zipWith_(self, that, f, __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in sequence, combining their results with the specified `f` function.
*/
export function zipWith_<R, E, A, R2, E2, A2, B>(
self: Managed<R, E, A>,
that: Managed<R2, E2, A2>,
f: (a: A, a2: A2) => B,
__trace?: string
) {
return chain_(self, (a) => map_(that, (a2) => f(a, a2)), __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in parallel, combining their results with the specified `f` function.
*
* @ets_data_first zipWithPar_
*/
export function zipWithPar<A, R2, E2, A2, B>(
that: Managed<R2, E2, A2>,
f: (a: A, a2: A2) => B,
__trace?: string
) {
return <R, E>(self: Managed<R, E, A>): Managed<R & R2, E | E2, B> =>
zipWithPar_(self, that, f, __trace)
}
/**
* Returns a managed that executes both this managed and the specified managed,
* in parallel, combining their results with the specified `f` function.
*/
export function zipWithPar_<R, E, A, R2, E2, A2, B>(
self: Managed<R, E, A>,
that: Managed<R2, E2, A2>,
f: (a: A, a2: A2) => B,
__trace?: string
): Managed<R & R2, E | E2, B> {
return mapM_(makeManagedReleaseMap(parallel), (parallelReleaseMap) => {
const innerMap = T.provideSome_(
makeManagedReleaseMap(sequential).effect,
(r: R & R2) => Tp.tuple(r, parallelReleaseMap)
)
return T.chain_(
T.zip_(innerMap, innerMap, __trace),
({
tuple: [
{
tuple: [_, l]
},
{
tuple: [__, r]
}
]
}) =>
T.zipWithPar_(
T.provideSome_(self.effect, (_: R & R2) => Tp.tuple(_, l)),
T.provideSome_(that.effect, (_: R & R2) => Tp.tuple(_, r)),
({ tuple: [_, a] }, { tuple: [__, a2] }) => f(a, a2),
__trace
)
)
})
}
/**
* Returns a `Reservation` that allows separately accessing effects
* describing resource acquisition and release.
*/
export function managedReserve<R, E, A>(
self: Managed<R, E, A>
): T.UIO<Reservation<R, E, A>> {
return T.map_(makeReleaseMap.makeReleaseMap, (releaseMap) =>
Reservation.of(
T.map_(
T.provideSome_(self.effect, (_: R) => Tp.tuple(_, releaseMap)),
Tp.get(1)
),
(_) => releaseAll.releaseAll(_, T.sequential)(releaseMap)
)
)
} | the_stack |
import { Hooks } from '../Hooks'
import { Parser } from '../Parser'
import { help } from '../BaseCommands/Help'
import { InvalidCommandException } from '../Exceptions'
import { printHelp, printHelpFor } from '../utils/help'
import { validateCommand } from '../utils/validateCommand'
// Use the command contract from tensei instead.
import { CommandContract } from '@tensei/common'
import {
CommandFlag,
KernelContract,
TenseiContract,
RunHookCallback,
FindHookCallback,
GlobalFlagHandler,
CommandConstructorContract
} from '@tensei/common'
import { logger } from '@poppinss/cliui'
/**
* Ace kernel class is used to register, find and invoke commands by
* parsing `process.argv.splice(2)` value.
*/
export class Kernel implements KernelContract {
/**
* Reference to hooks class to execute lifecycle
* hooks
*/
private hooks = new Hooks()
/**
* The command that started the process
*/
private entryCommand?: CommandContract
/**
* The state of the kernel
*/
private state: 'idle' | 'running' | 'completed' = 'idle'
public constructor(public application: TenseiContract) {}
/**
* Exit handler for gracefully exiting the process
*/
private exitHandler: (callback: this) => void | Promise<void> = kernel => {
if (kernel.error && typeof kernel.error.handle === 'function') {
kernel.error.handle(kernel.error)
} else if (kernel.error) {
logger.fatal(kernel.error)
}
process.exit(kernel.exitCode === undefined ? 0 : kernel.exitCode)
}
/**
* The default command that will be invoked when no command is
* defined
*/
public defaultCommand: CommandConstructorContract = help
/**
* List of registered commands
*/
public commands: { [name: string]: CommandConstructorContract } = {}
public aliases: { [alias: string]: string } = {}
/**
* List of registered flags
*/
public flags: {
[name: string]: CommandFlag & { handler: GlobalFlagHandler }
} = {}
/**
* The exit code for the process
*/
public exitCode?: number
/**
* The error collected as part of the running commands or executing
* flags
*/
public error?: any
/**
* Executing global flag handlers. The global flag handlers are
* not async as of now, but later we can look into making them
* async.
*/
private executeGlobalFlagsHandlers(
argv: string[],
command?: CommandConstructorContract
) {
const globalFlags = Object.keys(this.flags)
const parsedOptions = new Parser(this.flags).parse(argv, command)
globalFlags.forEach(name => {
const value = parsedOptions[name]
/**
* Flag was not specified
*/
if (value === undefined) {
return
}
/**
* Calling the handler
*/
this.flags[name].handler(parsedOptions[name], parsedOptions, command)
})
}
/**
* Returns an array of all registered commands
*/
private getAllCommandsAndAliases() {
let commands: CommandConstructorContract[] = Object.keys(this.commands).map(
name => this.commands[name]
)
let aliases = {}
return {
commands,
aliases: Object.assign(aliases, this.aliases)
}
}
/**
* Processes the args and sets values on the command instance
*/
private async processCommandArgsAndFlags(
commandInstance: CommandContract,
args: string[]
) {
const parser = new Parser(this.flags)
const command = commandInstance
/**
* Parse the command arguments. The `parse` method will raise exception if flag
* or arg is not
*/
const parsedOptions = parser.parse(args, command)
/**
* We validate the command arguments after the global flags have been
* executed. It is required, since flags may have nothing to do
* with the validaty of command itself
*/
command.args.forEach((arg, index) => {
parser.validateArg(arg, index, parsedOptions, command)
})
/**
* Creating a new command instance and setting
* parsed options on it.
*/
commandInstance.parsed = parsedOptions
/**
* Setup command instance argument and flag
* properties.
*/
for (let i = 0; i < command.args.length; i++) {
const arg = command.args[i]
if (arg.type === 'spread') {
;(commandInstance as any)[arg.propertyName] = parsedOptions._.slice(i)
commandInstance.argValues[arg.propertyName] = parsedOptions._.slice(i)
break
} else {
;(commandInstance as any)[arg.propertyName] = parsedOptions._[i]
commandInstance.argValues[arg.propertyName] = parsedOptions._[i]
}
}
/**
* Set flag value on the command instance
*/
for (let flag of command.flags) {
const flagValue = parsedOptions[flag.name]
if (flagValue !== undefined) {
;(commandInstance as any)[flag.propertyName] = flagValue
commandInstance.flagValues[flag.propertyName] = flagValue
}
}
}
/**
* Execute the main command. For calling commands within commands,
* one must call "kernel.exec".
*/
private async execMain(commandName: string, args: string[]) {
const command = await this.find([commandName])
/**
* Command not found. So execute global flags handlers and
* raise an exception
*/
if (!command) {
this.executeGlobalFlagsHandlers(args)
throw InvalidCommandException.invoke(
commandName,
this.getSuggestions(commandName)
)
}
/**
* Make an instance of the command
*/
const commandInstance = command
/**
* Execute global flags
*/
this.executeGlobalFlagsHandlers(args, command)
/**
* Process the arguments and flags for the command
*/
await this.processCommandArgsAndFlags(commandInstance, args)
/**
* Keep a reference to the entry command. So that we know if we
* want to entertain `.exit` or not
*/
this.entryCommand = commandInstance
/**
* Execute before run hooks
*/
await this.hooks.execute('before', 'run', commandInstance)
/**
* Execute command
*/
return commandInstance.exec()
}
/**
* Handles exiting the process
*/
private async exitProcess(error?: any) {
/**
* Check for state to avoid exiting the process multiple times
*/
if (this.state === 'completed') {
return
}
this.state = 'completed'
/**
* Re-assign error if entry command exists and has error
*/
if (!error && this.entryCommand && this.entryCommand.error) {
error = this.entryCommand.error
}
/**
* Execute the after run hooks. Wrapping inside try/catch since this is the
* cleanup handler for the process and must handle all exceptions
*/
try {
if (this.entryCommand) {
await this.hooks.execute('after', 'run', this.entryCommand)
}
} catch (hookError) {
error = hookError
}
/**
* Assign error to the kernel instance
*/
if (error) {
this.error = error
}
/**
* Figure out the exit code for the process
*/
const exitCode = error ? 1 : 0
const commandExitCode = this.entryCommand && this.entryCommand.exitCode
this.exitCode = commandExitCode === undefined ? exitCode : commandExitCode
try {
await this.exitHandler(this)
} catch (exitHandlerError: any) {
logger.warning(
'Expected exit handler to exit the process. Instead it raised an exception'
)
logger.fatal(exitHandlerError)
}
}
/**
* Register a before hook
*/
public before(action: 'run', callback: RunHookCallback): this
public before(action: 'find', callback: FindHookCallback): this
public before(
action: 'run' | 'find',
callback: RunHookCallback | FindHookCallback
): this {
this.hooks.add('before', action, callback)
return this
}
/**
* Register an after hook
*/
public after(action: 'run', callback: RunHookCallback): this
public after(action: 'find', callback: FindHookCallback): this
public after(
action: 'run' | 'find',
callback: RunHookCallback | FindHookCallback
): this {
this.hooks.add('after', action, callback)
return this
}
/**
* Register an array of command constructors
*/
public register(commands: CommandConstructorContract[]): this {
commands.forEach(command => {
validateCommand(command)
// Set the kernel on all commands.
command.kernel = this
this.commands[command.commandName] = command
/**
* Registering command aliaes
*/
command.aliases.forEach(
alias => (this.aliases[alias] = command.commandName)
)
})
return this
}
/**
* Register a global flag. It can be defined in combination with
* any command.
*/
public flag(
name: string,
handler: GlobalFlagHandler,
options: Partial<Exclude<CommandFlag, 'name' | 'propertyName'>>
): this {
this.flags[name] = Object.assign(
{
name,
propertyName: name,
handler,
type: 'boolean'
},
options
)
return this
}
/**
* Register an exit handler
*/
public onExit(callback: (kernel: this) => void | Promise<void>): this {
this.exitHandler = callback
return this
}
/**
* Returns an array of command names suggestions for a given name.
*/
public getSuggestions(name: string, distance = 3): string[] {
const leven = require('leven')
const { commands, aliases } = this.getAllCommandsAndAliases()
const suggestions = commands
.filter(({ commandName }) => leven(name, commandName) <= distance)
.map(({ commandName }) => commandName)
return suggestions.concat(
Object.keys(aliases).filter(alias => leven(name, alias) <= distance)
)
}
/**
* Finds the command from the command line argv array. If command for
* the given name doesn't exists, then it will return `null`.
*
* Does executes the before and after hooks regardless of whether the
* command has been found or not
*/
public async find(
argv: string[]
): Promise<CommandConstructorContract | null> {
/**
* ----------------------------------------------------------------------------
* Even though in `Unix` the command name may appear in between or at last, with
* ace we always want the command name to be the first argument. However, the
* arguments to the command itself can appear in any sequence. For example:
*
* Works
* - node ace make:controller foo
* - node ace make:controller --http foo
*
* Doesn't work
* - node ace foo make:controller
* ----------------------------------------------------------------------------
*/
const [commandName] = argv
/**
* Command name from the registered aliases
*/
const aliasCommandName = this.aliases[commandName]
/**
* Try to find command inside manually registered command or fallback
* to null
*/
const command =
this.commands[commandName] || this.commands[aliasCommandName] || null
/**
* Executing before and after together to be compatible
* with the manifest find before and after hooks
*/
await this.hooks.execute('before', 'find', command)
await this.hooks.execute('after', 'find', command)
return command
}
/**
* Run the default command. The default command doesn't accept
* and args or flags.
*/
public async runDefaultCommand() {
validateCommand(this.defaultCommand)
// Set the kernel on defualt command.
this.defaultCommand.kernel = this
/**
* Execute before/after find hooks
*/
await this.hooks.execute('before', 'find', this.defaultCommand)
await this.hooks.execute('after', 'find', this.defaultCommand)
/**
* Make the command instance using the container
*/
const commandInstance = this.defaultCommand
/**
* Execute before run hook
*/
await this.hooks.execute('before', 'run', commandInstance)
/**
* Keep a reference to the entry command
*/
this.entryCommand = commandInstance
/**
* Execute the command
*/
return commandInstance.exec()
}
/**
* Execute a command as a sub-command. Do not call "handle" and
* always use this method to invoke command programatically
*/
public async exec(commandName: string, args: string[]) {
const command = await this.find([commandName])
/**
* Command not found. So execute global flags handlers and
* raise an exception
*/
if (!command) {
throw InvalidCommandException.invoke(
commandName,
this.getSuggestions(commandName)
)
}
/**
* Make an instance of command and keep a reference of it as `this.entryCommand`
*/
const commandInstance = command
/**
* Process args and flags for the command
*/
await this.processCommandArgsAndFlags(commandInstance, args)
let commandError: any
let commandResponse: any
/**
* Wrapping the command execution inside a try/catch, so that
* we can run the after hooks regardless of success or
* failure
*/
try {
await this.hooks.execute('before', 'run', commandInstance)
commandResponse = await commandInstance.exec()
} catch (error) {
commandError = error
}
/**
* Execute after hooks
*/
await this.hooks.execute('after', 'run', commandInstance)
/**
* Re-throw error (if any)
*/
if (commandError) {
throw commandError
}
return commandResponse
}
/**
* Makes instance of a given command by processing command line arguments
* and setting them on the command instance
*/
public async handle(argv: string[]) {
if (this.state !== 'idle') {
return
}
this.state = 'running'
try {
/**
* Branch 1
* Run default command and invoke the exit handler
*/
if (!argv.length) {
await this.runDefaultCommand()
await this.exitProcess()
return
}
/**
* Branch 2
* No command has been mentioned and hence execute all the global flags
* invoke the exit handler
*/
const hasMentionedCommand = !argv[0].startsWith('-')
if (!hasMentionedCommand) {
this.executeGlobalFlagsHandlers(argv)
await this.exitProcess()
return
}
/**
* Branch 3
* Execute the given command as the main command
*/
const [commandName, ...args] = argv
await this.execMain(commandName, args)
/**
* Exit the process if there isn't any entry command
*/
if (!this.entryCommand) {
await this.exitProcess()
return
}
const entryCommandConstructor = this.entryCommand
/**
* Exit the process if entry command isn't a stayalive command. Stayalive
* commands should call `this.exit` to exit the process.
*/
if (!entryCommandConstructor.settings.stayAlive) {
await this.exitProcess()
}
} catch (error) {
await this.exitProcess(error)
}
}
/**
* Print the help screen for a given command or all commands/flags
*/
public printHelp(
command?: CommandConstructorContract,
commandsToAppend?: CommandConstructorContract[],
aliasesToAppend?: Record<string, string>
) {
let { commands, aliases } = this.getAllCommandsAndAliases()
/**
* Append additional commands and aliases for help screen only
*/
if (commandsToAppend) {
commands = commands.concat(commandsToAppend)
}
if (aliasesToAppend) {
aliases = Object.assign({}, aliases, aliasesToAppend)
}
if (command) {
printHelpFor(command, aliases)
} else {
const flags = Object.keys(this.flags).map(name => this.flags[name])
printHelp(commands, flags, aliases)
}
}
/**
* Trigger kernel to exit the process. The call to this method
* is ignored when command is not same the `entryCommand`.
*
* In other words, subcommands cannot trigger exit
*/
public async exit(command: CommandContract, error?: any) {
if (command !== this.entryCommand) {
return
}
await this.exitProcess(error)
}
} | the_stack |
import { PdfPageBase } from './pdf-page-base';
import { PdfPage } from './pdf-page';
import { PdfDictionary } from './../primitives/pdf-dictionary';
import { PdfPageLayer } from './pdf-page-layer';
import { PdfCollection } from './../general/pdf-collection';
import { PdfReferenceHolder } from './../primitives/pdf-reference';
import { PdfArray } from './../primitives/pdf-array';
import { PdfCrossTable } from './../input-output/pdf-cross-table';
import { PdfStream } from './../primitives/pdf-stream';
import { IPdfPrimitive } from './../../interfaces/i-pdf-primitives';
/**
* The class provides methods and properties to handle the collections of `PdfPageLayer`.
*/
export class PdfPageLayerCollection extends PdfCollection {
// Fields
/**
* Parent `page`.
* @private
*/
private page : PdfPageBase;
/**
* Stores the `number of first level layers` in the document.
* @default 0
* @private
*/
private parentLayerCount : number = 0;
/**
* Indicates if `Sublayer` is present.
* @default false
* @private
*/
public sublayer : boolean = false;
/**
* Stores the `optional content dictionary`.
* @private
*/
public optionalContent : PdfDictionary = new PdfDictionary();
// Properties
/**
* Return the `PdfLayer` from the layer collection by index.
* @private
*/
public items(index : number) : PdfPageLayer
/**
* Stores the `layer` into layer collection with specified index.
* @private
*/
public items(index : number, value : PdfPageLayer) : void
public items(index : number, value ?: PdfPageLayer) : void|PdfPageLayer {
if (typeof index === 'number' && typeof value === 'undefined') {
let obj : Object = this.list[index];
return (obj as PdfPageLayer);
} else {
if (value == null) {
throw new Error('ArgumentNullException: layer');
}
if (value.page !== this.page) {
throw new Error('ArgumentException: The layer belongs to another page');
}
// // Add/remove the layer.
// let layer : PdfPageLayer = this.items(index);
// if (layer != null) {
// this.RemoveLayer(layer);
// }
// this.List[index] = value;
// this.InsertLayer(index, value);
}
}
// Constructors
/**
* Initializes a new instance of the `PdfPageLayerCollection` class
* @private
*/
public constructor()
/**
* Initializes a new instance of the `PdfPageLayerCollection` class
* @private
*/
public constructor(page : PdfPageBase)
public constructor(page? : PdfPageBase) {
super();
if (page instanceof PdfPageBase) {
// if (page == null) {
// throw new Error('ArgumentNullException:page');
// }
this.page = page;
let lPage : PdfPageBase = page;
// if (lPage != null) {
this.parseLayers(lPage);
// }
}
}
// Implementation
/**
* Creates a new `PdfPageLayer` and adds it to the end of the collection.
* @private
*/
public add() : PdfPageLayer
/**
* Creates a new `PdfPageLayer` and adds it to the end of the collection.
* @private
*/
public add(layerName : string, visible : boolean) : PdfPageLayer
/**
* Creates a new `PdfPageLayer` and adds it to the end of the collection.
* @private
*/
public add(layerName : string) : PdfPageLayer
/**
* Creates a new `PdfPageLayer` and adds it to the end of the collection.
* @private
*/
public add(layer : PdfPageLayer) : number
public add(firstArgument ?: PdfPageLayer|string, secondArgument ?: boolean) : PdfPageLayer|number {
if (typeof firstArgument === 'undefined') {
let layer : PdfPageLayer = new PdfPageLayer(this.page);
layer.name = '';
this.add(layer);
return layer;
} else if (firstArgument instanceof PdfPageLayer) {
// if (layer == null)
// throw new ArgumentNullException("layer");
// if (layer.Page != m_page)
// throw new ArgumentException("The layer belongs to another page");
let index : number = this.list.push(firstArgument);
// Register layer.
this.addLayer(index, firstArgument);
return index;
} else {
return 0;
}
}
/**
* Registers `layer` at the page.
* @private
*/
private addLayer(index : number, layer : PdfPageLayer) : void {
let reference : PdfReferenceHolder = new PdfReferenceHolder(layer);
this.page.contents.add(reference);
}
// private RemoveLayer(layer : PdfPageLayer) : void {
// if (layer == null) {
// throw new Error('ArgumentNullException:layer');
// }
// let reference : PdfReferenceHolder = new PdfReferenceHolder(layer);
// if (this.page != null) {
// this.page.Contents.Remove(reference);
// }
// }
/**
* Inserts `PdfPageLayer` into the collection at specified index.
* @private
*/
public insert(index : number, layer : PdfPageLayer) : void {
// if (index < 0)
// throw new ArgumentOutOfRangeException("index", "Value can not be less 0");
// if (layer == null)
// throw new ArgumentNullException("layer");
// if (layer.Page != m_page)
// throw new ArgumentException("The layer belongs to another page");
let list : Object[] = [];
let length : number = this.list.length;
for (let i : number = index; i < length; i++) {
list.push(this.list.pop());
}
this.list.push(layer);
for (let i : number = 0; i < list.length; i++) {
this.list.push(list[i]);
}
// Register layer.
this.insertLayer(index, layer);
}
/**
* Registers layer at the page.
* @private
*/
private insertLayer(index : number, layer : PdfPageLayer) : void {
if (layer == null) {
throw new Error('ArgumentNullException:layer');
}
let reference : PdfReferenceHolder = new PdfReferenceHolder(layer);
this.page.contents.insert(index, reference);
}
// tslint:disable
/**
* `Parses the layers`.
* @private
*/
private parseLayers(loadedPage : PdfPageBase) : void {// tslint:enable
// if (loadedPage == null) {
// throw new Error('ArgumentNullException:loadedPage');
// }
let contents : PdfArray = this.page.contents;
let resource : PdfDictionary = this.page.getResources();
let crossTable : PdfCrossTable = null;
let ocproperties : PdfDictionary = null;
let propertie : PdfDictionary = null;
let isLayerAdded : boolean = false;
// if (loadedPage instanceof PdfPage) {
crossTable = (loadedPage as PdfPage).crossTable;
// } else {
// crossTable = (loadedPage as PdfLoadedPage).CrossTable;
// Propertie = PdfCrossTable.Dereference(Resource[DictionaryProperties.Properties]) as PdfDictionary;
// ocproperties = PdfCrossTable.Dereference((loadedPage as PdfLoadedPage).
// Document.Catalog[DictionaryProperties.OCProperties]) as PdfDictionary;
// }
let saveStream : PdfStream = new PdfStream();
let restoreStream : PdfStream = new PdfStream();
let saveState : string = 'q';
let newLine : string = '\n';
let restoreState : string = 'Q';
// for (let index : number = 0; index < contents.Items.length; index++) {
// let obj : IPdfPrimitive = contents[index];
// let stream : PdfStream = crossTable.GetObject(obj) as PdfStream;
// if (stream == null)
// throw new PdfDocumentException("Invalid contents array.");
// // if (stream.Compress)
// {
// if (!loadedPage.Imported)
// stream.Decompress();
// }
// byte[] contentId = stream.Data;
// string str = PdfString.ByteToString(contentId);
// if (!loadedPage.Imported && (contents.Count == 1) && ((stream.Data[stream.Data.Length - 2] ==
// RestoreState) || (stream.Data[stream.Data.Length - 1] == RestoreState)))
// {
// byte[] content = stream.Data;
// byte[] data = new byte[content.Length + 4];
// data[0] = SaveState;
// data[1] = NewLine;
// content.CopyTo(data, 2);
// data[data.Length - 2] = NewLine;
// data[data.Length - 1] = RestoreState;
// stream.Data = data;
// }
// if (ocproperties != null)
// {
// if (Propertie != null)
// {
// foreach (KeyValuePair<PdfName, IPdfPrimitive> prop in Propertie.Items)
// {
// String Key = prop.Key.ToString();
// PdfReferenceHolder refh = prop.Value as PdfReferenceHolder;
// PdfDictionary Dict = null;
// if (refh != null)
// {
// Dict = refh.Object as PdfDictionary;
// }
// else
// {
// Dict = prop.Value as PdfDictionary;
// }
// PdfDictionary m_usage = PdfCrossTable.Dereference(Dict[DictionaryProperties.Usage]) as PdfDictionary;
// if (m_usage != null)
// {
// if (str.Contains(Key))
// {
// PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);
// PdfDictionary printoption = PdfCrossTable.Dereference(m_usage[DictionaryProperties.Print])
// as PdfDictionary;
// if (printoption != null)
// {
// layer.m_printOption = printoption;
// foreach (KeyValuePair<PdfName, IPdfPrimitive> value in printoption.Items)
// {
// if (value.Key.Value.Equals(DictionaryProperties.PrintState))
// {
// string printState = (value.Value as PdfName).Value;
// if (printState.Equals(DictionaryProperties.OCGON))
// {
// layer.PrintState = PdfPrintState.AlwaysPrint;
// break;
// }
// else
// {
// layer.PrintState = PdfPrintState.NeverPrint;
// break;
// }
// }
// }
// }
// PdfString layerName = PdfCrossTable.Dereference(Dict[DictionaryProperties.Name]) as PdfString;
// layer.Name = layerName.Value;
// List.add(layer);
// isLayerAdded = true;
// if(!str.Contains("EMC"))
// break;
// }
// }
// else
// {
// if (str.Contains(Key))
// {
// PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);
// List.add(layer);
// if(Dict.ContainsKey(DictionaryProperties.Name))
// {
// PdfString layerName = PdfCrossTable.Dereference(Dict[DictionaryProperties.Name]) as PdfString;
// layer.Name = layerName.Value;
// }
// isLayerAdded = true;
// break;
// }
// }
// }
// }
// }
// if (!isLayerAdded)
// {
// PdfPageLayer layer = new PdfPageLayer(loadedPage, stream);
// List.add(layer);
// }
// else
// isLayerAdded = false;
// }
let saveData : string[] = [];
saveData.push(saveState);
saveStream.data = saveData;
contents.insert(0, new PdfReferenceHolder(saveStream));
saveData = [];
saveData.push(restoreState);
restoreStream.data = saveData;
contents.insert(contents.count, new PdfReferenceHolder(restoreStream));
}
/**
* Returns `index of` the `PdfPageLayer` in the collection if exists, -1 otherwise.
* @private
*/
public indexOf(layer : PdfPageLayer) : number {
if (layer == null) {
throw new Error('ArgumentNullException: layer');
}
let index : number = this.list.indexOf(layer);
return index;
}
} | the_stack |
import { Stack } from "@aws-cdk/core";
import { Route53ToAlb, Route53ToAlbProps } from '../lib';
import * as r53 from '@aws-cdk/aws-route53';
import * as elb from '@aws-cdk/aws-elasticloadbalancingv2';
import '@aws-cdk/assert/jest';
import * as defaults from '@aws-solutions-constructs/core';
// Helper Functions
function getTestVpc(stack: Stack) {
return defaults.buildVpc(stack, {
defaultVpcProps: defaults.DefaultPublicPrivateVpcProps(),
constructVpcProps: {
enableDnsHostnames: true,
enableDnsSupport: true,
cidr: '172.168.0.0/16',
},
});
}
test('Test Public API, new VPC', () => {
// Initial Setup
const stack = new Stack(undefined, undefined, {
env: { account: "123456789012", region: 'us-east-1' },
});
const newZone = new r53.PublicHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com'
});
const props: Route53ToAlbProps = {
publicApi: true,
existingHostedZoneInterface: newZone,
};
new Route53ToAlb(stack, 'test-route53-alb', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internet-facing'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Test Private API, existing VPC', () => {
// Initial Setup
const stack = new Stack(undefined, undefined, {
env: { account: "123456789012", region: 'us-east-1' },
});
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
existingVpc: testExistingVpc
};
new Route53ToAlb(stack, 'test-route53-alb', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internal'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Test Private API, new VPC', () => {
// Initial Setup
const stack = new Stack(undefined, undefined, {
env: { account: "123456789012", region: 'us-east-1' },
});
const props: Route53ToAlbProps = {
publicApi: false,
privateHostedZoneProps: {
zoneName: 'www.example-test.com',
}
};
new Route53ToAlb(stack, 'test-route53-alb', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internal'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Check publicApi and zone props is an error', () => {
// Initial Setup
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const props: Route53ToAlbProps = {
publicApi: true,
existingVpc: testExistingVpc,
privateHostedZoneProps: {
zoneName: 'www.example-test.com',
}
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Check no Zone props and no existing zone interface is an error', () => {
// Initial Setup
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const props: Route53ToAlbProps = {
publicApi: false,
existingVpc: testExistingVpc,
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Check Zone props with VPC is an error', () => {
// Initial Setup
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const props: Route53ToAlbProps = {
publicApi: false,
existingVpc: testExistingVpc,
privateHostedZoneProps: {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
}
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Test with privateHostedZoneProps', () => {
// Initial Setup
const stack = new Stack(undefined, undefined, {
env: { account: "123456789012", region: 'us-east-1' },
});
const testExistingVpc = getTestVpc(stack);
const props: Route53ToAlbProps = {
publicApi: false,
existingVpc: testExistingVpc,
privateHostedZoneProps: {
zoneName: 'www.example-test.com',
}
};
new Route53ToAlb(stack, 'test-error', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internal'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Check that passing an existing hosted Zone without passing an existingVPC is an error', () => {
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Check that passing an existing Load Balancer without passing an existingVPC is an error', () => {
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const existingAlb = new elb.ApplicationLoadBalancer(stack, 'test-alb', {
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingLoadBalancerObj: existingAlb,
privateHostedZoneProps: {
zoneName: 'www.example-test.com',
}
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Check that passing an existing ALB without passing an existingVPC is an error', () => {
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Check that passing loadBalancerProps with a vpc is an error', () => {
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
loadBalancerProps: {
loadBalancerName: 'my-alb',
vpc: testExistingVpc,
}
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
});
test('Test providing loadBalancerProps', () => {
// Initial Setup
const stack = new Stack(undefined, undefined, {
env: { account: "123456789012", region: 'us-east-1' },
});
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
existingVpc: testExistingVpc,
loadBalancerProps: {
loadBalancerName: 'find-this-name'
},
};
new Route53ToAlb(stack, 'test-route53-alb', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internal',
Name: 'find-this-name'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Test providing an existingLoadBalancer', () => {
// Initial Setup
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const newZone = new r53.PrivateHostedZone(stack, 'test-zone', {
zoneName: 'www.example-test.com',
vpc: testExistingVpc
});
const existingAlb = new elb.ApplicationLoadBalancer(stack, 'test-alb', {
vpc: testExistingVpc,
loadBalancerName: 'find-this-name'
});
const props: Route53ToAlbProps = {
publicApi: false,
existingHostedZoneInterface: newZone,
existingVpc: testExistingVpc,
existingLoadBalancerObj: existingAlb,
};
new Route53ToAlb(stack, 'test-route53-alb', props);
expect(stack).toHaveResourceLike('AWS::ElasticLoadBalancingV2::LoadBalancer', {
Scheme: 'internal',
Name: 'find-this-name'
});
expect(stack).toHaveResourceLike('AWS::EC2::VPC', {
EnableDnsHostnames: true,
EnableDnsSupport: true,
InstanceTenancy: "default",
});
expect(stack).toHaveResourceLike('AWS::Route53::RecordSet', {
Name: 'www.example-test.com.',
Type: 'A'
});
});
test('Check publicApi and without an existing hosted zone is an error', () => {
// Initial Setup
const stack = new Stack();
const testExistingVpc = getTestVpc(stack);
const props: Route53ToAlbProps = {
publicApi: true,
existingVpc: testExistingVpc,
};
const app = () => {
new Route53ToAlb(stack, 'test-error', props);
};
// Assertion
expect(app).toThrowError();
}); | the_stack |
import { assert } from "chai";
import * as d3 from "d3";
import * as sinon from "sinon";
import * as Plottable from "../../src";
import { CanvasDrawer } from "../../src/drawers/canvasDrawer";
import { ProxyDrawer } from "../../src/drawers/drawer";
import * as TestMethods from "../testMethods";
describe("Plots", () => {
describe("Plot", () => {
it("adds a \"plot\" css class by default", () => {
const plot = new Plottable.Plot();
assert.isTrue(plot.hasClass("plot"), "plot class added by default");
});
it("turns _overflowHidden on", () => {
const plot = new Plottable.Plot();
assert.isTrue((<any> plot)._overflowHidden, "overflowHidden is enabled");
});
describe("managing entities", () => {
let plot: Plottable.Plot;
let div: d3.Selection<HTMLDivElement, any, any, any>;
beforeEach(() => {
plot = new Plottable.Plot();
div = TestMethods.generateDiv();
plot.renderTo(div);
});
afterEach(() => {
div.remove();
});
it("first call to entities builds a new store", () => {
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const lightweightPlotEntitySpy = sinon.spy(plot, "_buildLightweightPlotEntities");
const entities = plot.entities();
const entities1 = plot.entities();
assert.deepEqual(entities, entities1);
assert.isTrue(lightweightPlotEntitySpy.calledOnce);
});
it("new store is built each time entities is called with data", () => {
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const lightweightPlotEntitySpy = sinon.spy(plot, "_buildLightweightPlotEntities");
const entities = plot.entities([dataset]);
const entities1 = plot.entities([dataset]);
assert.deepEqual(entities, entities1);
assert.isTrue(lightweightPlotEntitySpy.calledTwice);
});
it("rebuilds the store when the datasets change", () => {
const dataset = new Plottable.Dataset([5, -5, 10]);
const dataset1 = new Plottable.Dataset([1, -2, 3]);
plot.addDataset(dataset);
const lightweightPlotEntitySpy = sinon.spy(plot, "_buildLightweightPlotEntities");
const entities = plot.entities();
assert.strictEqual(entities.length, 3);
plot.datasets([dataset1]);
const entities1 = plot.entities();
assert.isTrue(lightweightPlotEntitySpy.calledTwice);
assert.strictEqual(entities1.length, 3);
plot.addDataset(dataset);
const entities2 = plot.entities();
assert.isTrue(lightweightPlotEntitySpy.calledThrice);
assert.strictEqual(entities2.length, 6);
plot.removeDataset(dataset);
const entities3 = plot.entities();
assert.deepEqual(entities3, entities1);
assert.strictEqual(lightweightPlotEntitySpy.callCount, 4);
});
describe("adding entities", () => {
let addAllSpy: sinon.SinonSpy;
beforeEach(() => {
addAllSpy = sinon.spy(Plottable.Utils.EntityStore.prototype, "addAll");
});
afterEach(() => {
addAllSpy.restore();
});
it("supplies plot bounds from its own origin when adding entities to the store", () => {
const dataset = new Plottable.Dataset();
plot.addDataset(dataset);
const width = 200;
const height = 100;
const originX = 50;
const originY = 20;
plot.setBounds(width, height, originX, originY);
const parentSpaceBounds = plot.bounds();
plot.entities();
const plotLocalBounds = addAllSpy.args[0][2];
assert.notDeepEqual(parentSpaceBounds, plotLocalBounds);
assert.deepEqual(plotLocalBounds, {
topLeft: {x: 0, y: 0},
bottomRight: {x: width, y: height},
});
});
});
});
describe("entityNearest", () => {
let plot: Plottable.Plot;
let div: any;
beforeEach(() => {
plot = new Plottable.Plot();
div = TestMethods.generateDiv();
plot.renderTo(div);
});
afterEach(() => {
div.remove();
});
it("builds entityStore if entity store is undefined", () => {
const dataset = new Plottable.Dataset([5, -5, 10]);
plot.addDataset(dataset);
const lightweightPlotEntitySpy = sinon.spy(plot, "_buildLightweightPlotEntities");
plot.entityNearest({ x: 5, y: 0 });
assert.isTrue(lightweightPlotEntitySpy.calledOnce);
});
});
describe("managing datasets", () => {
let plot: Plottable.Plot;
beforeEach(() => {
plot = new Plottable.Plot();
});
it("can add a dataset", () => {
const dataset = new Plottable.Dataset();
assert.strictEqual(plot.addDataset(dataset), plot, "adding a dataset returns the plot");
assert.deepEqual(plot.datasets(), [dataset], "dataset has been added");
});
it("can remove a dataset", () => {
const dataset = new Plottable.Dataset();
plot.addDataset(dataset);
assert.strictEqual(plot.removeDataset(dataset), plot, "removing a dataset returns the plot");
assert.deepEqual(plot.datasets(), [], "dataset has been removed");
});
it("can set the datasets", () => {
const datasetCount = 5;
const datasets = Plottable.Utils.Math.range(0, datasetCount).map(() => new Plottable.Dataset());
assert.strictEqual(plot.datasets(datasets), plot, "setting the datasets returns the plot");
assert.deepEqual(plot.datasets(), datasets, "datasets have been set");
});
it("adds a g element for each dataset to the render area", () => {
const datasetCount = 5;
const datasets = Plottable.Utils.Math.range(0, datasetCount).map(() => new Plottable.Dataset());
plot.datasets(datasets);
const div = TestMethods.generateDiv();
plot.anchor(div);
assert.strictEqual(plot.content().select(".render-area").selectAll<Element, any>("g").size(), datasetCount, "g for each dataset");
div.remove();
});
it("updates the scales extents when the datasets get updated", () => {
const scale = new Plottable.Scales.Linear();
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.attr("foo", (d) => d, scale);
plot.addDataset(dataset);
const oldDomain = scale.domain();
const div = TestMethods.generateDiv();
plot.anchor(div);
assert.operator(scale.domainMin(), "<=", Math.min.apply(null, data), "domainMin extended to at least minimum");
assert.operator(scale.domainMax(), ">=", Math.max.apply(null, data), "domainMax extended to at least maximum");
plot.removeDataset(dataset);
assert.deepEqual(scale.domain(), oldDomain, "domain does not include dataset if removed");
const data2 = [7, -7, 8];
const dataset2 = new Plottable.Dataset(data2);
plot.datasets([dataset, dataset2]);
assert.operator(scale.domainMin(), "<=", Math.min.apply(null, data.concat(data2)), "domainMin includes new dataset");
assert.operator(scale.domainMax(), ">=", Math.max.apply(null, data.concat(data2)), "domainMax includes new dataset");
div.remove();
});
it("updates the scale extents in dataset order", () => {
const categoryScale = new Plottable.Scales.Category();
const data = ["A"];
const dataset = new Plottable.Dataset(data);
const data2 = ["B"];
const dataset2 = new Plottable.Dataset(data2);
plot.addDataset(dataset2);
plot.addDataset(dataset);
plot.attr("key", (d) => d, categoryScale);
const div = TestMethods.generateDiv();
plot.anchor(div);
assert.deepEqual(categoryScale.domain(), data2.concat(data), "extent in the right order");
div.remove();
});
});
it("can set if the plot will animate", () => {
const plot = new Plottable.Plot();
assert.strictEqual(plot.animated(), false, "by default the plot is not animated");
assert.strictEqual(plot.animated(true), plot, "toggling animation returns the plot");
assert.strictEqual(plot.animated(), true, "can set if plot does animate");
plot.animated(false);
assert.strictEqual(plot.animated(), false, "can set if plot does not animate");
});
describe("managing animators", () => {
let plot: Plottable.Plot;
beforeEach(() => {
plot = new Plottable.Plot();
});
it("correctly computes the total draw time", () => {
function makeFixedTimeAnimator(totalTime: number) {
return <Plottable.IAnimator> {
animate: () => null,
totalTime: () => totalTime,
};
}
const animationTimes = [10, 20];
const drawSteps = animationTimes.map((time) => {
return {
attrToProjector: <Plottable.AttributeToProjector> {},
animator: makeFixedTimeAnimator(time),
};
});
const totalTime = Plottable.Plot.getTotalDrawTime([], drawSteps);
const expectedTotalTime = d3.sum(animationTimes);
assert.strictEqual(totalTime, expectedTotalTime, "returned the total time taken by all Animators");
});
it("uses a null animator for the reset animator by default", () => {
assert.isTrue(plot.animator(Plottable.Plots.Animator.RESET) instanceof Plottable.Animators.Null, "null by default");
});
it("uses an easing animator for the main animator by default", () => {
assert.isTrue(plot.animator(Plottable.Plots.Animator.MAIN) instanceof Plottable.Animators.Easing, "easing by default");
});
it("can set the animator for a key", () => {
const animator = new Plottable.Animators.Easing();
const animatorKey = "foo";
assert.strictEqual(plot.animator(animatorKey, animator), plot, "setting an animator returns the plot");
assert.strictEqual(plot.animator(animatorKey), animator, "can set the animator for a given key");
});
});
it("disconnects the data extents from the scales when destroyed", () => {
const plot = new Plottable.Plot();
const scale = new Plottable.Scales.Linear();
plot.attr("attr", (d) => d, scale);
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const oldDomain = scale.domain();
const div = TestMethods.generateDiv();
plot.anchor(div);
plot.destroy();
assert.deepEqual(scale.domain(), oldDomain, "destroying the plot removes its extents from the scale");
div.remove();
});
it("disconnects the data extents from the scales when detached", () => {
const plot = new Plottable.Plot();
const scale = new Plottable.Scales.Linear();
plot.attr("attr", (d) => d, scale);
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const oldDomain = scale.domain();
const div = TestMethods.generateDiv();
plot.anchor(div);
plot.detach();
assert.deepEqual(scale.domain(), oldDomain, "detaching the plot removes its extents from the scale");
div.remove();
});
describe("setting attributes with attr()", () => {
let plot: Plottable.Plot;
beforeEach(() => {
plot = new Plottable.Plot();
});
it("can set the attribute to a constant value", () => {
const constantNumber = 10;
assert.strictEqual(plot.attr("foo", constantNumber), plot, "setting the attribute returns the calling plot");
assert.strictEqual(plot.attr("foo").accessor(null, 0, null), constantNumber, "can set the attribute to a constant number");
const constantString = "one";
plot.attr("foo", constantString);
assert.strictEqual(plot.attr("foo").accessor(null, 0, null), constantString, "can set the attribute to a constant string");
});
it("can set the attribute based on the input data", () => {
const data = [1, 2, 3, 4, 5];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const numberAccessor = (d: any, i: number) => d + i * 10;
assert.strictEqual(plot.attr("foo", numberAccessor), plot, "setting the attribute returns the calling plot");
let attrAccessor = plot.attr("foo").accessor;
/* tslint:disable no-shadowed-variable */
plot.datasets().forEach((dataset, datasetIndex) => {
dataset.data().forEach((datum, index) => {
assert.strictEqual(attrAccessor(datum, index, dataset), numberAccessor(datum, index),
`can set attribute for number datum ${index} in dataset ${datasetIndex}`);
});
});
/* tslint:enable no-shadowed-variable */
const stringAccessor = (d: any, i: number) => `${d + i * 10} foo`;
assert.strictEqual(plot.attr("foo", stringAccessor), plot, "setting the attribute returns the calling plot");
attrAccessor = plot.attr("foo").accessor;
/* tslint:disable no-shadowed-variable */
plot.datasets().forEach((dataset, datasetIndex) => {
dataset.data().forEach((datum, index) => {
assert.strictEqual(attrAccessor(datum, index, dataset), stringAccessor(datum, index),
`can set attribute for string datum ${index} in dataset ${datasetIndex}`);
});
});
/* tslint:enable no-shadowed-variable */
});
it("passes the correct index to the Accessor", () => {
const data = ["A", "B", "C"];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const indexCheckAccessor = (datum: any, index: number) => {
assert.strictEqual(index, data.indexOf(datum), "was passed correct index");
return datum;
};
const scale = new Plottable.Scales.Category();
plot.attr("foo", indexCheckAccessor, scale);
const div = TestMethods.generateDiv();
plot.anchor(div);
div.remove();
});
it("can apply a scale to the returned values", () => {
const data = [1, 2, 3, 4, 5];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
const numberAccessor = (d: any, i: number) => d;
const linearScale = new Plottable.Scales.Linear();
assert.strictEqual(plot.attr("foo", numberAccessor, linearScale), plot, "setting the attribute returns the calling plot");
let attrAccessor = plot.attr("foo").accessor;
let attrScale = plot.attr("foo").scale;
/* tslint:disable no-shadowed-variable */
plot.datasets().forEach((dataset, datasetIndex) => {
dataset.data().forEach((datum, index) => {
assert.strictEqual(attrScale.scale(attrAccessor(datum, index, dataset)), linearScale.scale(numberAccessor(datum, index)),
`can set based on scaled version of number datum ${index} in dataset ${datasetIndex}`);
});
});
/* tslint:enable no-shadowed-variable */
const stringAccessor = (d: any, i: number) => `${d} foo`;
const categoryScale = new Plottable.Scales.Category();
categoryScale.domain(data.map(stringAccessor));
assert.strictEqual(plot.attr("foo", stringAccessor, categoryScale), plot, "setting the attribute returns the calling plot");
attrAccessor = plot.attr("foo").accessor;
attrScale = plot.attr("foo").scale;
/* tslint:disable no-shadowed-variable */
plot.datasets().forEach((dataset, datasetIndex) => {
dataset.data().forEach((datum, index) => {
assert.strictEqual(attrScale.scale(attrAccessor(datum, index, dataset)), categoryScale.scale(stringAccessor(datum, index)),
`can set based on scaled version of string datum ${index} in dataset ${datasetIndex}`);
});
});
/* tslint:enable no-shadowed-variable */
});
it("updates the scales extents associated with an attribute when that attribute is set", () => {
const scale = new Plottable.Scales.Linear();
const data = [5, -5, 10];
const dataset = new Plottable.Dataset(data);
plot.addDataset(dataset);
plot.attr("foo", (d) => d, scale);
const div = TestMethods.generateDiv();
plot.anchor(div);
assert.operator(scale.domainMin(), "<=", Math.min.apply(null, data), "domainMin extended to at least minimum");
assert.operator(scale.domainMax(), ">=", Math.max.apply(null, data), "domainMax extended to at least maximum");
div.remove();
});
});
describe("canvas renderer", () => {
let plot: Plottable.Plot;
beforeEach(() => {
plot = new Plottable.Plot();
});
it("can get/set the .renderer", () => {
assert.strictEqual(plot.renderer(), "svg", "defaults to svg");
plot.renderer("canvas");
assert.strictEqual(plot.renderer(), "canvas", "can change to canvas");
});
it("adds a canvas element to the DOM when rendered", () => {
plot.renderer("canvas");
const div = TestMethods.generateDiv();
plot.renderTo(div);
assert.isDefined(div.select("canvas").node(), "canvas is in DOM");
div.remove();
});
it("removes renderArea from the DOM after anchoring", () => {
plot.addDataset(new Plottable.Dataset([]));
const div = TestMethods.generateDiv();
plot.anchor(div);
// set to canvas after anchor
plot.renderer("canvas");
assert.strictEqual(plot.content().select(".render-area").selectAll("g").size(), 0, "no g's in renderArea anymore");
plot.renderer("svg");
assert.strictEqual(plot.content().select(".render-area").selectAll("g").size(), 1, "g's come back");
div.remove();
});
it("sets Drawers' canvas when renderer is set", () => {
plot.addDataset(new Plottable.Dataset([]));
const div = TestMethods.generateDiv();
plot.anchor(div);
plot.renderer("canvas");
(<any> plot)._datasetToDrawer.forEach((drawer: ProxyDrawer) => {
assert.isTrue(drawer.getDrawer() instanceof CanvasDrawer, "ProxyDrawer is using a CanvasDrawer");
});
div.remove();
});
it("returns null on .selections()", () => {
plot.addDataset(new Plottable.Dataset([]));
plot.renderer("canvas");
const div = TestMethods.generateDiv();
plot.renderTo(div);
assert.isTrue(plot.selections().empty(), "no selections on canvas");
div.remove();
});
});
});
}); | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace baremetalsolution_v1alpha1 {
export interface Options extends GlobalOptions {
version: 'v1alpha1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: 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;
/**
* 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;
}
/**
* Bare Metal Solution API
*
* Provides ways to manage Bare Metal Solution hardware installed in a regional extension located near a Google Cloud data center.
*
* @example
* ```js
* const {google} = require('googleapis');
* const baremetalsolution = google.baremetalsolution('v1alpha1');
* ```
*/
export class Baremetalsolution {
context: APIRequestContext;
projects: Resource$Projects;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.projects = new Resource$Projects(this.context);
}
}
/**
* Configuration parameters for a new instance.
*/
export interface Schema$InstanceConfig {
/**
* Client network address.
*/
clientNetwork?: Schema$NetworkAddress;
/**
* Whether the instance should be provisioned with Hyperthreading enabled.
*/
hyperthreading?: boolean | null;
/**
* A transient unique identifier to idenfity an instance within an ProvisioningConfig request.
*/
id?: string | null;
/**
* Instance type.
*/
instanceType?: string | null;
/**
* Location where to deploy the instance.
*/
location?: string | null;
/**
* OS image to initialize the instance.
*/
osImage?: string | null;
/**
* Private network address, if any.
*/
privateNetwork?: Schema$NetworkAddress;
/**
* User note field, it can be used by customers to add additional information for the BMS Ops team (b/194021617).
*/
userNote?: string | null;
}
/**
* A resource budget.
*/
export interface Schema$InstanceQuota {
/**
* Number of machines than can be created for the given location and instance_type.
*/
availableMachineCount?: number | null;
/**
* Instance type.
*/
instanceType?: string | null;
/**
* Location where the quota applies.
*/
location?: string | null;
}
/**
* Response for ListProvisioningQuotas.
*/
export interface Schema$ListProvisioningQuotasResponse {
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
*/
nextPageToken?: string | null;
/**
* The provisioning quotas registered in this project.
*/
provisioningQuotas?: Schema$ProvisioningQuota[];
}
/**
* A LUN range.
*/
export interface Schema$LunRange {
/**
* Number of LUNs to create.
*/
quantity?: number | null;
/**
* The requested size of each LUN, in GB.
*/
sizeGb?: number | null;
}
/**
* A network.
*/
export interface Schema$NetworkAddress {
/**
* IP address to be assigned to the server.
*/
address?: string | null;
/**
* Name of the existing network to use. Will be of the format at--vlan for pre-intake UI networks like for eg, at-123456-vlan001 or any user-defined name like for eg, my-network-name for networks provisioned using intake UI. The field is exclusively filled only in case of an already existing network. Mutually exclusive with network_id.
*/
existingNetworkId?: string | null;
/**
* Name of the network to use, within the same ProvisioningConfig request. This represents a new network being provisioned in the same request. Can have any user-defined name like for eg, my-network-name. Mutually exclusive with existing_network_id.
*/
networkId?: string | null;
}
/**
* Configuration parameters for a new network.
*/
export interface Schema$NetworkConfig {
/**
* Interconnect bandwidth. Set only when type is CLIENT.
*/
bandwidth?: string | null;
/**
* CIDR range of the network.
*/
cidr?: string | null;
/**
* A transient unique identifier to identify a volume within an ProvisioningConfig request.
*/
id?: string | null;
/**
* Location where to deploy the network.
*/
location?: string | null;
/**
* Service CIDR, if any.
*/
serviceCidr?: string | null;
/**
* The type of this network.
*/
type?: string | null;
/**
* User note field, it can be used by customers to add additional information for the BMS Ops team (b/194021617).
*/
userNote?: string | null;
/**
* List of VLAN attachments. As of now there are always 2 attachments, but it is going to change in the future (multi vlan).
*/
vlanAttachments?: Schema$VlanAttachment[];
}
/**
* A NFS export entry.
*/
export interface Schema$NfsExport {
/**
* Allow dev.
*/
allowDev?: boolean | null;
/**
* Allow the setuid flag.
*/
allowSuid?: boolean | null;
/**
* A CIDR range.
*/
cidr?: string | null;
/**
* Either a single machine, identified by an ID, or a comma-separated list of machine IDs.
*/
machineId?: string | null;
/**
* Network to use to publish the export.
*/
networkId?: string | null;
/**
* Disable root squashing.
*/
noRootSquash?: boolean | null;
/**
* Export permissions.
*/
permissions?: string | null;
}
/**
* An provisioning configuration.
*/
export interface Schema$ProvisioningConfig {
/**
* Instances to be created.
*/
instances?: Schema$InstanceConfig[];
/**
* Networks to be created.
*/
networks?: Schema$NetworkConfig[];
/**
* A reference to track the request.
*/
ticketId?: string | null;
/**
* Volumes to be created.
*/
volumes?: Schema$VolumeConfig[];
}
/**
* A provisioning quota for a given project.
*/
export interface Schema$ProvisioningQuota {
/**
* Instance quota.
*/
instanceQuota?: Schema$InstanceQuota;
}
/**
* Request for SubmitProvisioningConfig.
*/
export interface Schema$SubmitProvisioningConfigRequest {
/**
* Optional. Email provided to send a confirmation with provisioning config to.
*/
email?: string | null;
/**
* Required. The ProvisioningConfig to submit.
*/
provisioningConfig?: Schema$ProvisioningConfig;
}
/**
* A GCP vlan attachment.
*/
export interface Schema$VlanAttachment {
/**
* Identifier of the VLAN attachment.
*/
id?: string | null;
/**
* Attachment pairing key.
*/
pairingKey?: string | null;
}
/**
* Configuration parameters for a new volume.
*/
export interface Schema$VolumeConfig {
/**
* A transient unique identifier to identify a volume within an ProvisioningConfig request.
*/
id?: string | null;
/**
* Location where to deploy the volume.
*/
location?: string | null;
/**
* LUN ranges to be configured. Set only when protocol is PROTOCOL_FC.
*/
lunRanges?: Schema$LunRange[];
/**
* Machine ids connected to this volume. Set only when protocol is PROTOCOL_FC.
*/
machineIds?: string[] | null;
/**
* NFS exports. Set only when protocol is PROTOCOL_NFS.
*/
nfsExports?: Schema$NfsExport[];
/**
* Volume protocol.
*/
protocol?: string | null;
/**
* The requested size of this volume, in GB. This will be updated in a later iteration with a generic size field.
*/
sizeGb?: number | null;
/**
* Whether snapshots should be enabled.
*/
snapshotsEnabled?: boolean | null;
/**
* The type of this Volume.
*/
type?: string | null;
/**
* User note field, it can be used by customers to add additional information for the BMS Ops team (b/194021617).
*/
userNote?: string | null;
}
export class Resource$Projects {
context: APIRequestContext;
locations: Resource$Projects$Locations;
provisioningQuotas: Resource$Projects$Provisioningquotas;
constructor(context: APIRequestContext) {
this.context = context;
this.locations = new Resource$Projects$Locations(this.context);
this.provisioningQuotas = new Resource$Projects$Provisioningquotas(
this.context
);
}
}
export class Resource$Projects$Locations {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Submit a provisiong configuration for a given project.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const baremetalsolution = google.baremetalsolution('v1alpha1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res =
* await baremetalsolution.projects.locations.submitProvisioningConfig({
* // Required. The target location of the provisioning request.
* location: 'locations/my-location',
* // Required. The target project of the provisioning request.
* project: 'projects/my-project',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "email": "my_email",
* // "provisioningConfig": {}
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "instances": [],
* // "networks": [],
* // "ticketId": "my_ticketId",
* // "volumes": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
submitProvisioningConfig(
params: Params$Resource$Projects$Locations$Submitprovisioningconfig,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
submitProvisioningConfig(
params?: Params$Resource$Projects$Locations$Submitprovisioningconfig,
options?: MethodOptions
): GaxiosPromise<Schema$ProvisioningConfig>;
submitProvisioningConfig(
params: Params$Resource$Projects$Locations$Submitprovisioningconfig,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
submitProvisioningConfig(
params: Params$Resource$Projects$Locations$Submitprovisioningconfig,
options: MethodOptions | BodyResponseCallback<Schema$ProvisioningConfig>,
callback: BodyResponseCallback<Schema$ProvisioningConfig>
): void;
submitProvisioningConfig(
params: Params$Resource$Projects$Locations$Submitprovisioningconfig,
callback: BodyResponseCallback<Schema$ProvisioningConfig>
): void;
submitProvisioningConfig(
callback: BodyResponseCallback<Schema$ProvisioningConfig>
): void;
submitProvisioningConfig(
paramsOrCallback?:
| Params$Resource$Projects$Locations$Submitprovisioningconfig
| BodyResponseCallback<Schema$ProvisioningConfig>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ProvisioningConfig>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ProvisioningConfig>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ProvisioningConfig>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Locations$Submitprovisioningconfig;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params =
{} as Params$Resource$Projects$Locations$Submitprovisioningconfig;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://baremetalsolution.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/v1alpha1/{+project}/{+location}:submitProvisioningConfig'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'POST',
},
options
),
params,
requiredParams: ['project', 'location'],
pathParams: ['location', 'project'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ProvisioningConfig>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ProvisioningConfig>(parameters);
}
}
}
export interface Params$Resource$Projects$Locations$Submitprovisioningconfig
extends StandardParameters {
/**
* Required. The target location of the provisioning request.
*/
location?: string;
/**
* Required. The target project of the provisioning request.
*/
project?: string;
/**
* Request body metadata
*/
requestBody?: Schema$SubmitProvisioningConfigRequest;
}
export class Resource$Projects$Provisioningquotas {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* List the budget details to provision resources on a given project.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const baremetalsolution = google.baremetalsolution('v1alpha1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await baremetalsolution.projects.provisioningQuotas.list({
* // The maximum number of items to return.
* pageSize: 'placeholder-value',
* // The next_page_token value returned from a previous List request, if any.
* pageToken: 'placeholder-value',
* // Required. The parent project containing the provisioning quotas.
* parent: 'projects/my-project',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "nextPageToken": "my_nextPageToken",
* // "provisioningQuotas": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
list(
params: Params$Resource$Projects$Provisioningquotas$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Projects$Provisioningquotas$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListProvisioningQuotasResponse>;
list(
params: Params$Resource$Projects$Provisioningquotas$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Projects$Provisioningquotas$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListProvisioningQuotasResponse>,
callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
): void;
list(
params: Params$Resource$Projects$Provisioningquotas$List,
callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
): void;
list(
callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Projects$Provisioningquotas$List
| BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListProvisioningQuotasResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListProvisioningQuotasResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Projects$Provisioningquotas$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Projects$Provisioningquotas$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://baremetalsolution.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1alpha1/{+parent}/provisioningQuotas').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListProvisioningQuotasResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListProvisioningQuotasResponse>(
parameters
);
}
}
}
export interface Params$Resource$Projects$Provisioningquotas$List
extends StandardParameters {
/**
* The maximum number of items to return.
*/
pageSize?: number;
/**
* The next_page_token value returned from a previous List request, if any.
*/
pageToken?: string;
/**
* Required. The parent project containing the provisioning quotas.
*/
parent?: string;
}
} | the_stack |
import fs from 'fs';
import tv4 from 'tv4';
import { JovoModelData, JovoModelDataV3 } from '@jovotech/model';
import { join as joinPaths, resolve } from 'path';
import { Config, deleteFolderRecursive, JovoCliError, JovoCliPlugin, Project } from '../src';
import { Plugin } from './__mocks__/plugins/Plugin';
jest.mock('fs', () => ({ ...Object.assign({}, jest.requireActual('fs')) }));
const testPath: string = resolve(joinPaths('test', 'tmpTestFolderProject'));
beforeEach(() => {
jest.spyOn(Config.prototype, 'getContent').mockReturnThis();
jest.spyOn(Config.prototype, 'get').mockReturnThis();
jest.spyOn(Config, 'getInstance').mockReturnValue(new Config(''));
});
afterEach(() => {
jest.restoreAllMocks();
});
describe('Project.getInstance()', () => {
beforeEach(() => {
delete Project['instance'];
});
test('should return instance of Project', () => {
expect(Project['instance']).toBeUndefined();
const project: Project = Project.getInstance('');
expect(project).toBeDefined();
expect(Project['instance']).toBeDefined();
expect(project === Project['instance']).toBeTruthy();
});
test('should not return instance of Project if one exists already', () => {
expect(Project['instance']).toBeUndefined();
const project1: Project = Project.getInstance('');
expect(Project['instance']).toBeDefined();
const project2: Project = Project.getInstance('');
expect(project1 === project2).toBeTruthy();
});
});
describe('new Project()', () => {
test('should instantiate project with project path, config and undefined stage', () => {
delete process.env.NODE_ENV;
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue(undefined);
const project: Project = new Project('testPath');
expect(project['projectPath']).toMatch('testPath');
expect(project.config).toBeDefined();
expect(project.stage).toBeUndefined();
});
test('should get the stage from command arguments', () => {
process.argv.push('--stage', 'dev');
const project: Project = new Project('');
expect(project.stage).toBeDefined();
expect(project.stage).toMatch('dev');
// Remove stage argument.
process.argv.splice(-2);
});
test('should get the stage from process.env.JOVO_STAGE', () => {
process.env.JOVO_STAGE = 'dev';
const project: Project = new Project('');
expect(project.stage).toBeDefined();
expect(project.stage).toMatch('dev');
delete process.env.JOVO_STAGE;
});
test('should get the stage from process.env.NODE_ENV', () => {
process.env.NODE_ENV = 'dev';
const project: Project = new Project('');
expect(project.stage).toBeDefined();
expect(project.stage).toMatch('dev');
delete process.env.NODE_ENV;
});
test('should get the stage from config', () => {
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue('dev');
const project: Project = new Project('');
expect(project.stage).toBeDefined();
expect(project.stage).toMatch('dev');
});
});
describe('getBuildDirectory()', () => {
test('should return default directory "build/"', () => {
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue(undefined);
const project: Project = new Project('');
expect(project.getBuildDirectory()).toMatch('build');
});
test('should return configured directory from project configuration', () => {
jest
.spyOn(Config.prototype, 'getParameter')
.mockReturnValueOnce(undefined)
.mockReturnValue('modifiedBuildDirectory');
const project: Project = new Project('');
expect(project.getBuildDirectory()).toMatch('modifiedBuildDirectory');
});
test('should return staged build directory', () => {
jest
.spyOn(Config.prototype, 'getParameter')
.mockReturnValueOnce('dev')
.mockReturnValue(undefined);
const project: Project = new Project('');
expect(project.getBuildDirectory()).toMatch(joinPaths('build', 'dev'));
});
});
describe('getBuildPath()', () => {
test('should return build path', () => {
jest.spyOn(Project.prototype, 'getBuildDirectory').mockReturnValue('build');
const project: Project = new Project('test');
expect(project.getBuildPath()).toMatch(joinPaths('test', 'build'));
});
});
describe('getModelsDirectory()', () => {
test('should return default directory "models/"', () => {
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue(undefined);
const project: Project = new Project('');
expect(project.getModelsDirectory()).toMatch('models');
});
test('should return configured directory from project configuration', () => {
jest
.spyOn(Config.prototype, 'getParameter')
.mockReturnValueOnce(undefined)
.mockReturnValue('modifiedModelsDirectory');
const project: Project = new Project('');
expect(project.getModelsDirectory()).toMatch('modifiedModelsDirectory');
});
});
describe('getModelsPath()', () => {
test('should return models path', () => {
jest.spyOn(Project.prototype, 'getModelsDirectory').mockReturnValue('models');
const project: Project = new Project('test');
expect(project.getModelsPath()).toMatch(joinPaths('test', 'models'));
});
});
describe('getModelPath()', () => {
test('should return model path for the provided locale', () => {
jest.spyOn(Project.prototype, 'getModelsPath').mockReturnValue('models');
const project: Project = new Project('');
expect(project.getModelPath('en')).toMatch(joinPaths('models', 'en'));
});
});
describe('getModel()', () => {
beforeEach(() => {
fs.mkdirSync(testPath, { recursive: true });
});
afterEach(() => {
deleteFolderRecursive(testPath);
});
test('should throw an error if module cannot be found', () => {
jest.spyOn(Project.prototype, 'getModelPath').mockReturnValue('invalid');
const project: Project = new Project('');
return expect(project.getModel('en')).rejects.toEqual(
new Error('Could not find model file for locale: en'),
);
});
test('should throw an error if something else went wrong', () => {
jest.spyOn(Project.prototype, 'getModelPath').mockReturnValue(joinPaths(testPath, 'en'));
fs.writeFileSync(joinPaths(testPath, 'en.json'), '{');
const project: Project = new Project('');
return expect(project.getModel('en')).rejects.toEqual(
new JovoCliError({ message: 'Unexpected end of JSON input' }),
);
});
test('should return model', async () => {
jest.spyOn(Project.prototype, 'getModelPath').mockReturnValue(joinPaths(testPath, 'de'));
const testModel: JovoModelData = {
version: '4.0',
invocation: 'test',
};
fs.writeFileSync(joinPaths(testPath, 'de.json'), JSON.stringify(testModel));
const project: Project = new Project('');
const projectModel: JovoModelData | JovoModelDataV3 = await project.getModel('de');
expect(projectModel).toBeDefined();
expect(projectModel).toHaveProperty('invocation');
expect(projectModel.invocation).toMatch('test');
});
});
describe('hasModelFiles()', () => {
test('should return false if no locales are provided', () => {
const project: Project = new Project('');
expect(project.hasModelFiles()).toBeFalsy();
});
test('should return false if requiring a model went wrong', () => {
jest.spyOn(Project.prototype, 'getModel').mockImplementation(() => {
throw new Error();
});
const project: Project = new Project('');
expect(project.hasModelFiles(['en'])).toBeFalsy();
});
test('should return true if all models could be loaded', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
const project: Project = new Project('');
expect(project.hasModelFiles(['en'])).toBeTruthy();
});
});
describe('validateModel()', () => {
test('should throw a ModelValidationError if model is not valid', async () => {
jest.spyOn(Project.prototype, 'getModel').mockReturnThis();
tv4.validate = jest.fn().mockReturnValueOnce(false);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
tv4.error = { message: 'Validation failed' };
const project: Project = new Project('');
try {
await project.validateModel('en', { invocation: '' }, {});
} catch (error) {
expect((error as Error).message).toMatch('Validation failed for locale "en"');
}
});
test('should do nothing if model is valid', async () => {
jest.spyOn(Project.prototype, 'getModel').mockReturnThis();
tv4.validate = jest.fn().mockReturnValueOnce(true);
const project: Project = new Project('');
await project.validateModel('en', { invocation: 'test' }, {});
});
});
describe('backupModel()', () => {
test('should throw an error if model file for the provided locale cannot be found', () => {
jest.spyOn(Project.prototype, 'hasModelFiles').mockReturnValue(false);
const project: Project = new Project('');
expect(project.backupModel.bind(project, 'en')).toThrow(
'Model file for locale en to backup could not be found.',
);
});
test('should copy the model for .js files', () => {
jest.spyOn(Project.prototype, 'hasModelFiles').mockReturnValue(true);
jest.spyOn(Project.prototype, 'getModelPath').mockReturnValue(joinPaths('models', 'en'));
jest.spyOn(fs, 'existsSync').mockReturnValueOnce(false).mockReturnValueOnce(true);
jest.spyOn(fs, 'copyFileSync').mockReturnThis();
const project: Project = new Project('');
project.backupModel('en');
const dateString: string = new Date().toISOString().substring(0, 10);
expect(fs.existsSync).toBeCalledTimes(2);
expect(fs.copyFileSync).toBeCalledTimes(1);
expect(fs.copyFileSync).toBeCalledWith(
joinPaths('models', 'en.js'),
joinPaths('models', `en.${dateString}.js`),
);
});
test('should copy the model for .json files', () => {
jest.spyOn(Project.prototype, 'hasModelFiles').mockReturnValue(true);
jest.spyOn(Project.prototype, 'getModelPath').mockReturnValue(joinPaths('models', 'en'));
jest.spyOn(fs, 'existsSync').mockReturnValueOnce(true);
jest.spyOn(fs, 'copyFileSync').mockReturnThis();
const project: Project = new Project('');
project.backupModel('en');
const dateString: string = new Date().toISOString().substring(0, 10);
expect(fs.existsSync).toBeCalledTimes(2);
expect(fs.copyFileSync).toBeCalledTimes(1);
expect(fs.copyFileSync).toBeCalledWith(
joinPaths('models', 'en.json'),
joinPaths('models', `en.${dateString}.json`),
);
});
});
describe('saveModel()', () => {
test('should create the models folder if it does not exist already', () => {
jest.spyOn(Project.prototype, 'getModelsPath').mockReturnValue('models');
jest.spyOn(fs, 'existsSync').mockReturnValueOnce(false);
jest.spyOn(fs, 'mkdirSync').mockReturnThis();
jest.spyOn(fs, 'writeFileSync').mockReturnThis();
const mockedGetModelPath: jest.SpyInstance = jest
.spyOn(Project.prototype, 'getModelPath')
.mockReturnValue(joinPaths('models', 'en'));
const project: Project = new Project('');
const model: JovoModelData = { version: '4.0', invocation: 'test' };
project.saveModel(model, 'en');
expect(fs.existsSync).toBeCalledWith('models');
expect(fs.mkdirSync).toBeCalledTimes(1);
expect(fs.mkdirSync).toBeCalledWith('models');
expect(mockedGetModelPath).toBeCalledWith('en');
expect(fs.writeFileSync).toBeCalledWith(
joinPaths('models', 'en.json'),
JSON.stringify(model, null, 2),
);
mockedGetModelPath.mockRestore();
});
});
describe('getLocales()', () => {
test('should return default locale if models directory does not exist', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(false);
const project: Project = new Project('');
const locales: string[] = project.getLocales();
expect(locales).toHaveLength(1);
expect(locales[0]).toMatch('en');
});
test('should return default locale if no files can be found', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest.spyOn(fs, 'readdirSync').mockReturnValue([]);
const project: Project = new Project('');
const locales: string[] = project.getLocales();
expect(locales).toHaveLength(1);
expect(locales[0]).toMatch('en');
});
test('should only return valid locales', () => {
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest
.spyOn(fs, 'readdirSync')
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
.mockReturnValue(['en.json', 'de.js', 'invalid_locale.json']);
const project: Project = new Project('');
const locales: string[] = project.getLocales();
expect(locales).toHaveLength(2);
expect(locales[1]).toMatch('de');
});
});
describe('getProjectName()', () => {
test('should return project name', () => {
const project: Project = new Project(joinPaths('test', 'projectName'));
expect(project.getProjectName()).toMatch('projectName');
});
});
describe('hasPlatform()', () => {
test('should return true if platform folder exists', () => {
fs.mkdirSync(joinPaths(testPath, 'build', 'platform.alexa'), { recursive: true });
jest.spyOn(Project.prototype, 'getBuildPath').mockReturnValue(joinPaths(testPath, 'build'));
const project: Project = new Project('');
expect(project.hasPlatform('platform.alexa')).toBeTruthy();
deleteFolderRecursive(testPath);
});
test('should return false if platform folder does not exist', () => {
jest.spyOn(Project.prototype, 'getBuildPath').mockReturnValue(joinPaths(testPath, 'build'));
const project: Project = new Project('');
expect(project.hasPlatform('platform.alexa')).toBeFalsy();
});
});
describe('isTypeScriptProject()', () => {
test('should return false if typescript is not a devDependency', () => {
jest.spyOn(fs, 'readFileSync').mockReturnValue('{"devDependencies": {} }');
const project: Project = new Project('');
expect(project.isTypeScriptProject()).toBeFalsy();
});
test('should return true if typescript is a devDependency', () => {
jest
.spyOn(fs, 'readFileSync')
.mockReturnValue('{"devDependencies": { "typescript": "^1.0.0" } }');
const project: Project = new Project('');
expect(project.isTypeScriptProject()).toBeTruthy();
});
});
describe('collectPlugins()', () => {
test('should return an empty array if no plugins could be found', () => {
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue([]);
const project: Project = new Project('');
const plugins: JovoCliPlugin[] = project.collectPlugins();
expect(plugins).toHaveLength(0);
});
test('should merge and return plugins', () => {
// Load mocked plugins.
const plugin: Plugin = new Plugin({ files: { foo: 'bar' } });
jest.spyOn(Config.prototype, 'getParameter').mockReturnValue([plugin]);
const project: Project = new Project('');
const plugins: JovoCliPlugin[] = project.collectPlugins();
expect(plugins).toHaveLength(1);
expect(plugins[0]).toHaveProperty('config');
expect(plugins[0].config).toHaveProperty('files');
expect(plugins[0].config.files).toHaveProperty('foo');
expect(plugins[0].config.files!.foo).toMatch('bar');
expect(plugins[0].id).toMatch('commandPlugin');
});
}); | the_stack |
// These imports are only used for testing. Run pretest and posttest scripts to automatically
// uncomment and re-comment these lines.
/*% import {Settings, AllDayValue} from './Settings'; %*/
/*% import {Util} from './Util'; %*/
/*% import {EventColor, GenericEvent, GenericEventKey} from './GenericEvent'; %*/
// Check that the user authorized permissions for the add-on. When the add-on is installed by somebody
// and used in a shared doc, for everybody else the add-on will be only "enabled" but not intalled.
// They must visit the auth URL to add the permissions.
function checkAuth(authMode: GoogleAppsScript.Script.AuthMode) {
const authInfo = ScriptApp.getAuthorizationInfo(authMode);
if (authInfo.getAuthorizationStatus() === ScriptApp.AuthorizationStatus.REQUIRED) {
const url = authInfo.getAuthorizationUrl();
Util.errorAlert(`Visit: ${url}\n to authorize the permissions needed for GCalendar Sync. Then reload this sheet.`)
return false;
}
return true;
}
// Create the add-on menu when a doc is opened.
function onOpen() {
if (!checkAuth(ScriptApp.AuthMode.LIMITED)) {
return;
}
SpreadsheetApp.getUi().createMenu('GCalendar Sync')
.addItem('Update from Calendar', 'syncFromCalendar')
.addItem('Update to Calendar', 'syncToCalendar')
.addItem('Settings', 'Settings.showSettingsDialog')
.addToUi();
}
// Create the menu when this add-on is installed.
function onInstall() {
onOpen();
}
// Synchronize from calendar to spreadsheet.
function syncFromCalendar() {
if (!checkAuth(ScriptApp.AuthMode.FULL)) {
return;
}
const userSettings = Settings.loadFromPropertyService();
//Logger.log('Starting sync from calendar');
// Loop through all sheets
const allSheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
let calendarIdsFound: string[] = [];
for (let sheet of allSheets) {
const sheetName = sheet.getName();
// Get sheet data and pull calendar ID from first row
let data = sheet.getDataRange().getValues();
if (data.length <= Util.CALENDAR_ID_ROW ||
!data[Util.CALENDAR_ID_ROW][0].replace(/\s/g, '').toLowerCase().startsWith('calendarid')) {
// Only sync sheets that start with "Calendar ID" in cell A1
continue;
}
// Get calendar events
const calendarId = data[Util.CALENDAR_ID_ROW][1];
if (calendarIdsFound.indexOf(calendarId) >= 0) {
if (Util.errorAlertHalt(`Calendar ID "${calendarId}" is in more than one sheet. This can have unpredictable results.`)) {
return;
}
}
calendarIdsFound.push(calendarId);
let calendar = CalendarApp.getCalendarById(calendarId);
if (!calendar) {
Util.errorAlert(`Could not find calendar with ID "${calendarId}" from sheet "${sheetName}".`);
continue;
}
const calEvents = calendar.getEvents(userSettings.begin_date, userSettings.end_date);
// Check if spreadsheet needs a title row added
if (data.length <= Util.TITLE_ROW ||
(data.length == Util.TITLE_ROW + 1 && data[Util.TITLE_ROW].length == 1 && data[Util.TITLE_ROW][0] === '')) {
Util.setUpSheet(sheet, calEvents.length);
// Refresh data from first two rows
data = sheet.getDataRange().getValues().slice(0, Util.FIRST_DATA_ROW);
}
// Map spreadsheet column titles to indices
const idxMap = Util.createIdxMap(data[Util.TITLE_ROW]);
// Verify title row has all required fields
const includeAllDay = userSettings.all_day_events === AllDayValue.use_column;
let missingFields = Util.missingRequiredFields(idxMap, includeAllDay);
if (missingFields.length > 0) {
Util.displayMissingFields(missingFields, sheetName);
continue;
}
// Get all of the event IDs from the sheet
const idIdx = idxMap.indexOf('id');
const sheetEventIds = data.map(row => row[idIdx]);
// Loop through calendar events and update or add to sheet data
let eventFound = new Array(data.length);
for (let calEvent of calEvents) {
const calEventId = calEvent.getId();
let rowIdx = sheetEventIds.indexOf(calEventId);
if (rowIdx < Util.FIRST_DATA_ROW) {
// Event not found, create it
rowIdx = data.length;
let newRow = Array(idxMap.length).fill('');
data.push(newRow);
} else {
eventFound[rowIdx] = true;
}
// Update event in spreadsheet data
GenericEvent.fromCalendarEvent(calEvent).toSpreadsheetRow(idxMap, data[rowIdx]);
}
// Remove any data rows not found in the calendar from the bottom up
let rowsDeleted = 0;
for (let idx = eventFound.length - 1; idx > Util.TITLE_ROW; idx--) {
if (!eventFound[idx] && sheetEventIds[idx]) {
data.splice(idx, 1);
rowsDeleted++;
}
}
// Save spreadsheet changes
let range = sheet.getRange(1, 1, data.length, data[Util.TITLE_ROW].length);
range.setValues(data);
if (rowsDeleted > 0) {
sheet.deleteRows(data.length + 1, rowsDeleted);
}
}
if (calendarIdsFound.length === 0) {
Util.errorAlert('Could not find any calendar IDs in sheets. See Help for setup instructions.');
}
}
// Synchronize from spreadsheet to calendar.
function syncToCalendar() {
if (!checkAuth(ScriptApp.AuthMode.FULL)) {
return;
}
const userSettings = Settings.loadFromPropertyService();
//Logger.log('Starting sync to calendar');
let scriptStart = Date.now();
// Loop through all sheets
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
const sheetTimeZone = spreadsheet.getSpreadsheetTimeZone();
const allSheets = spreadsheet.getSheets();
let calendarIdsFound: string[] = [];
for (let sheet of allSheets) {
const sheetName = sheet.getName();
// Get sheet data and pull calendar ID from first row
let range = sheet.getDataRange();
let data = range.getValues();
if (!data[Util.CALENDAR_ID_ROW][0].replace(/\s/g, '').toLowerCase().startsWith('calendarid')) {
// Only sync sheets that have a calendar ID
continue;
}
if (data.length < Util.FIRST_DATA_ROW + 1) {
Util.errorAlert(`Sheet "${sheetName}" must have a title row and at least one data row.`);
continue;
}
// Get calendar events
const calendarId = data[Util.CALENDAR_ID_ROW][1];
if (calendarIdsFound.indexOf(calendarId) >= 0) {
if (Util.errorAlertHalt(`Calendar ID "${calendarId}" is in more than one sheet. This can have unpredictable results.`)) {
return;
}
}
calendarIdsFound.push(calendarId);
let calendar = CalendarApp.getCalendarById(calendarId);
if (!calendar) {
Util.errorAlert(`Could not find calendar with ID "${calendarId}" from sheet "${sheetName}".`);
continue;
}
const calTimeZone = calendar.getTimeZone();
const calEvents = calendar.getEvents(userSettings.begin_date, userSettings.end_date);
let calEventIds = calEvents.map(val => val.getId());
// Map column headers to indices
let idxMap = Util.createIdxMap(data[Util.TITLE_ROW]);
// Verify title row has all required fields
const includeAllDay = userSettings.all_day_events === AllDayValue.use_column;
let missingFields = Util.missingRequiredFields(idxMap, includeAllDay);
if (missingFields.length > 0) {
Util.displayMissingFields(missingFields, sheetName);
continue;
}
let keysToAdd = Util.missingFields(idxMap);
// Get calendar IDs
let idIdx = idxMap.indexOf('id');
let idRange = range.offset(0, idIdx, data.length, 1);
let idData = idRange.getValues()
// Loop through sheet rows
let numAdded = 0;
let numUpdates = 0;
let eventsAdded = false;
for (let ridx = Util.FIRST_DATA_ROW; ridx < data.length; ridx++) {
let sheetEvent = GenericEvent.fromSpreadsheetRow(data[ridx], idxMap, keysToAdd,
userSettings.all_day_events, sheetTimeZone);
// If enabled, skip rows with blank/invalid start and end times
if (userSettings.skip_blank_rows && !(sheetEvent.starttime instanceof Date) &&
!(sheetEvent.endtime instanceof Date)) {
continue;
}
// Do some error checking first
if (!sheetEvent.title) {
Util.errorAlert('must have title', sheetEvent, ridx);
continue;
}
if (!(sheetEvent.starttime instanceof Date)) {
Util.errorAlert('start time must be a date/time', sheetEvent, ridx);
continue;
}
if (!(sheetEvent.endtime instanceof Date)) {
Util.errorAlert('end time must be a date/time', sheetEvent, ridx);
continue;
}
if (sheetEvent.endtime < sheetEvent.starttime) {
Util.errorAlert('end time must be after start time', sheetEvent, ridx);
continue;
}
// Ignore events outside of the begin/end range desired.
if (sheetEvent.starttime > userSettings.end_date) {
continue;
}
if (sheetEvent.endtime < userSettings.begin_date) {
continue;
}
// Determine if spreadsheet event is already in calendar and matches
let addEvent = true;
if (sheetEvent.id) {
let eventIdx = calEventIds.indexOf(sheetEvent.id);
if (eventIdx >= 0) {
calEventIds[eventIdx] = null; // Prevents removing event below
addEvent = false;
let calEvent = calEvents[eventIdx];
let calGenericEvent = GenericEvent.fromCalendarEvent(calEvent);
let eventDiffs = calGenericEvent.eventDifferences(sheetEvent);
if (eventDiffs > 0) {
// When there are only 1 or 2 event differences, it's quicker to
// update the event. For more event diffs, delete and re-add the event.
if (eventDiffs < 3) {
numUpdates += calGenericEvent.updateEvent(sheetEvent, calEvent);
} else {
addEvent = true;
calEventIds[eventIdx] = sheetEvent.id;
}
}
}
}
//Logger.log(`${sheetEvent.title} ${numUpdates} updates, time: ${Date.now() - scriptStart} msecs`);
if (addEvent) {
const eventOptions = {
description: sheetEvent.description,
location: sheetEvent.location,
guests: sheetEvent.guests,
sendInvites: userSettings.send_email_invites,
}
let newEvent: GoogleAppsScript.Calendar.CalendarEvent;
if (sheetEvent.allday) {
if (sheetEvent.endtime.getHours() === 23 && sheetEvent.endtime.getMinutes() === 59) {
sheetEvent.endtime.setSeconds(sheetEvent.endtime.getSeconds() + 1);
}
newEvent = calendar.createAllDayEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent.endtime, eventOptions);
} else {
newEvent = calendar.createEvent(sheetEvent.title, sheetEvent.starttime, sheetEvent.endtime, eventOptions);
}
// Put event ID back into spreadsheet
idData[ridx][0] = newEvent.getId();
eventsAdded = true;
// Set event color
const numericColor = parseInt(sheetEvent.color);
if (numericColor > 0 && numericColor < 12) {
newEvent.setColor(sheetEvent.color);
}
// Throttle updates.
numAdded++;
Utilities.sleep(Settings.THROTTLE_SLEEP_TIME);
if (numAdded % 10 === 0) {
//Logger.log('%d events added, time: %d msecs', numAdded, Date.now() - scriptStart);
}
}
// If the script is getting close to timing out, save the event IDs added so far to avoid lots
// of duplicate events.
if ((Date.now() - scriptStart) > Settings.MAX_RUN_TIME) {
idRange.setValues(idData);
}
}
// Save spreadsheet changes
if (eventsAdded) {
idRange.setValues(idData);
}
// Remove any calendar events not found in the spreadsheet
const countNonNull = (prevVal: number, curVal: string) => curVal === null ? prevVal : prevVal + 1;
const numToRemove = calEventIds.reduce(countNonNull, 0);
if (numToRemove > 0) {
const ui = SpreadsheetApp.getUi();
const response = ui.alert(`Delete ${numToRemove} calendar event(s) not found in spreadsheet?`,
ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
let numRemoved = 0;
calEventIds.forEach((id, idx) => {
if (id != null) {
calEvents[idx].deleteEvent();
Utilities.sleep(Settings.THROTTLE_SLEEP_TIME);
numRemoved++;
// if (numRemoved % 10 === 0) {
// Logger.log('%d events removed, time: %d msecs', numRemoved, Date.now() - scriptStart);
// }
}
});
}
}
}
if (calendarIdsFound.length === 0) {
Util.errorAlert('Could not find any calendar IDs in sheets. See Help for setup instructions.');
}
}
// Simple function to test syntax of this script, since otherwise it's not exercised until the
// code is uploaded via Clasp and run in Sheets.
export function exerciseSyntax() {
return true;
} | the_stack |
import { isDefined, isArray } from '../../../../shared/utils';
import {
TableInterface,
P_CREATE_TABLE_COMMON,
P_CREATE_TABLE_LIKE,
O_POSITION,
} from '../../../../typings';
import { TableOptions } from './table-options';
import { Column } from './column';
import { FulltextIndex } from './fulltext-index';
import { SpatialIndex } from './spatial-index';
import { ForeignKey } from './foreign-key';
import { UniqueKey } from './unique-key';
import { PrimaryKey } from './primary-key';
import { Index } from '.';
import {
TableModelInterface,
DatabaseModelInterface,
ColumnModelInterface,
TableOptionsModelInterface,
FulltextIndexModelInterface,
SpatialIndexModelInterface,
ForeignKeyModelInterface,
UniqueKeyModelInterface,
IndexModelInterface,
PrimaryKeyModelInterface,
IndexPropertyValue,
IndexPropertyKey,
} from './typings';
/**
* Class to represent a table as parsed from SQL.
*/
export class Table implements TableModelInterface {
database!: DatabaseModelInterface;
name!: string;
columns?: ColumnModelInterface[];
options?: TableOptionsModelInterface;
fulltextIndexes?: FulltextIndexModelInterface[];
spatialIndexes?: SpatialIndexModelInterface[];
foreignKeys?: ForeignKeyModelInterface[];
uniqueKeys?: UniqueKeyModelInterface[];
indexes?: IndexModelInterface[];
primaryKey?: PrimaryKeyModelInterface;
/**
* Creates a table from a JSON def.
*
* @param json JSON format parsed from SQL.
* @param database Database to assign table to.
*/
static fromCommonDef(json: P_CREATE_TABLE_COMMON, database: DatabaseModelInterface): Table {
if (json.id === 'P_CREATE_TABLE_COMMON') {
const def = json.def;
const table = new Table();
table.database = database;
table.name = def.table;
if (def.tableOptions) {
table.options = TableOptions.fromDef(def.tableOptions);
}
const createDefinitions = def.columnsDef.def;
createDefinitions.forEach((createDefinition) => {
/**
* If table create definition is about adding a column.
*/
if (isDefined(createDefinition.def.column)) {
const column = Column.fromDef(createDefinition);
table.addColumn(column);
} else if (isDefined(createDefinition.def.fulltextIndex)) {
/**
* If table create definition is about adding a fulltext index.
*/
table.pushFulltextIndex(FulltextIndex.fromDef(createDefinition));
} else if (isDefined(createDefinition.def.spatialIndex)) {
/**
* If table create definition is about adding a spatial index.
*/
table.pushSpatialIndex(SpatialIndex.fromDef(createDefinition));
} else if (isDefined(createDefinition.def.foreignKey)) {
/**
* If table create definition is about adding a foreign key.
*/
table.pushForeignKey(ForeignKey.fromDef(createDefinition));
} else if (isDefined(createDefinition.def.uniqueKey)) {
/**
* If table create definition is about adding an unique key.
*/
table.pushUniqueKey(UniqueKey.fromDef(createDefinition));
} else if (isDefined(createDefinition.def.primaryKey)) {
/**
* If table create definition is about adding a primary key.
*/
table.setPrimaryKey(PrimaryKey.fromDef(createDefinition));
} else if (isDefined(createDefinition.def.index)) {
/**
* If table create definition is about adding an index.
*/
table.pushIndex(Index.fromDef(createDefinition));
}
});
return table;
}
throw new TypeError(`Unknown json id to build table from: ${json.id}`);
}
/**
* Creates a table from a JSON def.
*
* @param json JSON format parsed from SQL.
* @param tables Already existing tables.
*/
static fromAlikeDef(json: P_CREATE_TABLE_LIKE, tables: TableModelInterface[] = []): Table | undefined {
if (json.id === 'P_CREATE_TABLE_LIKE') {
const def = json.def;
const alikeTable = tables.find((t) => t.name === def.like);
if (!alikeTable) {
// throw new Error(`Trying to "CREATE TABLE LIKE" unexisting table ${def.like}.`);
return undefined;
}
const table = alikeTable.clone();
table.name = def.table;
return table;
}
throw new TypeError(`Unknown json id to build table from: ${json.id}`);
}
/**
* JSON casting of this object calls this method.
*/
toJSON(): TableInterface {
const json: TableInterface = {
name: this.name,
columns: (this.columns ?? []).map((c) => c.toJSON()),
};
if (isDefined(this.primaryKey)) {
json.primaryKey = this.primaryKey.toJSON();
}
if (isDefined(this.foreignKeys) && this.foreignKeys.length) {
json.foreignKeys = this.foreignKeys.map((k) => k.toJSON());
}
if (isDefined(this.uniqueKeys) && this.uniqueKeys.length) {
json.uniqueKeys = this.uniqueKeys.map((k) => k.toJSON());
}
if (isDefined(this.indexes) && this.indexes.length) {
json.indexes = this.indexes.map((i) => i.toJSON());
}
if (isDefined(this.spatialIndexes) && this.spatialIndexes.length) {
json.spatialIndexes = this.spatialIndexes.map((i) => i.toJSON());
}
if (isDefined(this.fulltextIndexes) && this.fulltextIndexes.length) {
json.fulltextIndexes = this.fulltextIndexes.map((i) => i.toJSON());
}
if (isDefined(this.options)) {
json.options = this.options.toJSON();
}
return json;
}
/**
* Create a deep clone of this model.
*/
clone(): Table {
const table = new Table();
table.database = this.database;
table.name = this.name;
table.columns = (this.columns ?? []).map((c) => c.clone());
if (isDefined(this.options)) {
table.options = this.options.clone();
}
if (isDefined(this.primaryKey)) {
table.primaryKey = this.primaryKey.clone();
}
if (isDefined(this.uniqueKeys) && this.uniqueKeys.length) {
table.uniqueKeys = this.uniqueKeys.map((key) => key.clone());
}
if (isDefined(this.foreignKeys) && this.foreignKeys.length) {
table.foreignKeys = this.foreignKeys.map((key) => key.clone());
}
if (isDefined(this.fulltextIndexes) && this.fulltextIndexes.length) {
table.fulltextIndexes = this.fulltextIndexes.map((index) => index.clone());
}
if (isDefined(this.spatialIndexes) && this.spatialIndexes.length) {
table.spatialIndexes = this.spatialIndexes.map((index) => index.clone());
}
if (isDefined(this.indexes) && this.indexes.length) {
table.indexes = this.indexes.map((index) => index.clone());
}
return table;
}
/**
* Get table with given name.
*
* @param name Table name.
*/
getTable(name: string): TableModelInterface | undefined {
return this.database.getTable(name);
}
/**
* Get tables from database.
*/
getTables(): TableModelInterface[] {
return this.database.getTables();
}
/**
* Setter for database.
*
* @param database Database instance.
*/
setDatabase(database: DatabaseModelInterface): void {
this.database = database;
}
/**
* Rename table.
*
* @param newName New table name.
*/
renameTo(newName: string): void {
this.database.tables.forEach((t) => {
(t.foreignKeys ?? [])
.filter((k) => k.referencesTable(this as TableModelInterface))
.forEach((k) => k.updateReferencedTableName(newName));
});
this.name = newName;
}
/**
* Add a column to columns array, in a given position.
*
* @param column Column to be added.
* @param position Position object.
*/
addColumn(column: ColumnModelInterface, position?: O_POSITION): void {
/**
* Should not add column with same name.
*/
if (this.getColumn(column.name)) {
return;
}
/**
* Validate if there are any other autoincrement
* columns, as there should be only one.
*/
if (
column.options &&
column.options.autoincrement &&
(this.columns ?? []).some((c) => c.options && c.options.autoincrement)
) {
return;
}
/**
* Do not allow adding column with primary
* key if table already has primary key.
*/
if (this.primaryKey && column.options && column.options.primary) {
return;
}
if (!isArray(this.columns)) {
this.columns = [];
}
if (!isDefined(position)) {
this.columns.push(column);
} else if (!position.after) {
this.columns.unshift(column);
} else {
const refColumn = this.columns.find((c) => c.name === position.after);
if (!refColumn) {
return;
}
const pos = this.columns.indexOf(refColumn);
const end = this.columns.splice(pos + 1);
this.columns.push(column);
this.columns = this.columns.concat(end);
}
this.extractColumnKeys(column);
}
/**
* Extract column keys like PrimaryKey, ForeignKey,
* UniqueKey and add them to this table instance.
*
* @param column Column to be extracted.
*/
extractColumnKeys(column: ColumnModelInterface): void {
const primaryKey = column.extractPrimaryKey();
const foreignKey = column.extractForeignKey();
const uniqueKey = column.extractUniqueKey();
if (primaryKey) {
this.setPrimaryKey(primaryKey);
}
if (foreignKey) {
this.pushForeignKey(foreignKey);
}
if (uniqueKey) {
this.pushUniqueKey(uniqueKey);
}
}
/**
* Move a column to a given position. Returns whether operation was successful.
*
* @param column One of this table columns.
* @param position Position object.
*/
moveColumn(column: ColumnModelInterface, position: O_POSITION): boolean {
if (!isDefined(this.columns) || !isDefined(position)) {
return false;
}
if (!this.columns.includes(column)) {
return false;
}
let refColumn: ColumnModelInterface | undefined;
/**
* First of all, validate if 'after' column, if any, exists.
*/
if (position.after) {
refColumn = this.getColumn(position.after);
if (!refColumn) {
return false;
}
}
let pos = this.columns.indexOf(column);
let end = this.columns.splice(pos);
end.shift();
this.columns = this.columns.concat(end);
if (position.after) {
if (!refColumn) {
return false;
}
pos = this.columns.indexOf(refColumn);
end = this.columns.splice(pos + 1);
this.columns.push(column);
this.columns = this.columns.concat(end);
} else {
this.columns.unshift(column);
}
return true;
}
/**
* Rename column and references to it. Returns whether operation was successful.
*
* @param column Column being renamed.
* @param newName New name of column.
*/
renameColumn(column: ColumnModelInterface, newName: string): boolean {
if (!(this.columns ?? []).includes(column)) {
return false;
}
/**
* Rename references to column.
*/
this.getTables().forEach((table) => {
(table.foreignKeys ?? [])
.filter((k) => k.referencesTable(this as TableModelInterface))
.forEach((k) => k.renameColumn(column, newName));
});
(this.fulltextIndexes ?? []).forEach((i) => i.renameColumn(column, newName));
(this.spatialIndexes ?? []).forEach((i) => i.renameColumn(column, newName));
(this.indexes ?? []).forEach((i) => i.renameColumn(column, newName));
(this.uniqueKeys ?? []).forEach((k) => k.renameColumn(column, newName));
if (this.primaryKey) {
this.primaryKey.renameColumn(column, newName);
}
column.name = newName;
return true;
}
/**
* Get column position object.
*
* @param column Column.
*/
getColumnPosition(column: ColumnModelInterface): O_POSITION | undefined {
const index = (this.columns ?? []).indexOf(column);
/**
* First column.
*/
if (index === 0) {
return { after: null };
}
if (index + 1 === (this.columns ?? []).length) {
/**
* Last column.
*/
} else {
/**
* Somewhere in the middle.
*/
const refColumn = (this.columns ?? [])[index - 1];
return { after: refColumn.name };
}
return undefined;
}
/**
* Drops table's primary key.
*/
dropPrimaryKey(): void {
if (!this.primaryKey) {
return;
}
const tableColumns = this.primaryKey.getColumnsFromTable(this as TableModelInterface);
/**
* Should not drop primary key if pk column has autoincrement.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/14
*/
if (tableColumns.some((c) => c.options && c.options.autoincrement)) {
return;
}
delete this.primaryKey;
}
/**
* Drops a column from table.
*
* @param column Column to be dropped.
*/
dropColumn(column: ColumnModelInterface): void {
/**
* Validate whether there is a reference to given column.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/12
*/
const hasReference = this.getTables().some((t) =>
(t.foreignKeys ?? []).some((k) =>
k.referencesTableAndColumn(this as TableModelInterface, column),
),
);
if (hasReference) {
return;
}
if (!isDefined(this.columns)) {
return;
}
/**
* Should not drop the last column of table.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/13
*/
if (this.columns.length === 1) {
return;
}
const pos = this.columns.indexOf(column);
const end = this.columns.splice(pos);
end.shift();
this.columns = this.columns.concat(end);
/**
* Remove column from indexes. Also remove
* the index if removed column was last.
*
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/8
*/
if (isDefined(this.fulltextIndexes) && this.fulltextIndexes.length) {
this.fulltextIndexes.forEach((index) => {
if (index.dropColumn(column.name) && !index.columns.length) {
this.dropIndexByInstance(index);
}
});
}
if (isDefined(this.spatialIndexes) && this.spatialIndexes.length) {
this.spatialIndexes.forEach((index) => {
if (index.dropColumn(column.name) && !index.columns.length) {
this.dropIndexByInstance(index);
}
});
}
if (isDefined(this.indexes) && this.indexes.length) {
this.indexes.forEach((index) => {
if (index.dropColumn(column.name) && !index.columns.length) {
this.dropIndexByInstance(index);
}
});
}
if (isDefined(this.uniqueKeys) && this.uniqueKeys.length) {
this.uniqueKeys.forEach((key) => {
if (key.dropColumn(column.name) && !key.columns.length) {
this.dropIndexByInstance(key);
}
});
}
if (isDefined(this.foreignKeys) && this.foreignKeys.length) {
this.foreignKeys.forEach((key) => {
if (key.dropColumn(column.name) && !key.columns.length) {
this.dropForeignKey(key);
}
});
}
if (isDefined(this.primaryKey)) {
if (this.primaryKey.dropColumn(column.name) && !this.primaryKey.columns?.length) {
delete this.primaryKey;
}
}
}
/**
* Drops an index from table.
*
* @param index Index to be dropped.
*/
dropIndexByInstance(
index:
| UniqueKeyModelInterface
| IndexModelInterface
| FulltextIndexModelInterface
| SpatialIndexModelInterface,
): void {
const type = this.getIndexTypeByInstance(index);
if (!isDefined(type) || !isDefined(this[type])) {
return;
}
const indexes: IndexPropertyValue = this[type] as IndexPropertyValue;
const pos = indexes.indexOf(index);
const end = indexes.splice(pos);
end.shift();
(this[type] as IndexPropertyValue) = indexes.concat(end);
}
/**
* Drops a foreign key from table.
*
* @param foreignKey Foreign key to be dropped.
*/
dropForeignKey(foreignKey: ForeignKeyModelInterface): void {
if (!isDefined(this.foreignKeys)) {
return;
}
const pos = this.foreignKeys.indexOf(foreignKey);
const end = this.foreignKeys.splice(pos);
end.shift();
this.foreignKeys = this.foreignKeys.concat(end);
}
/**
* Get index by name.
*
* @param name Index name.
*/
getIndexByName(
name: string,
):
| UniqueKeyModelInterface
| IndexModelInterface
| FulltextIndexModelInterface
| SpatialIndexModelInterface
| undefined {
const type = this.getIndexTypeByName(name);
if (!type) {
// throw new Error(`Trying to reference an unexsisting index ${name} on table ${this.name}`);
return undefined;
}
const indexes: IndexPropertyValue = this[type] as IndexPropertyValue;
if (!isArray(indexes)) {
return undefined;
}
const result = indexes.find((index) => index.name === name);
return result ?? undefined;
}
/**
* Get which index array is storing a given index.
*
* @param indez
*/
getIndexTypeByInstance(
index:
| UniqueKeyModelInterface
| IndexModelInterface
| FulltextIndexModelInterface
| SpatialIndexModelInterface,
): IndexPropertyKey | undefined {
const props: IndexPropertyKey[] = [
'uniqueKeys',
'indexes',
'fulltextIndexes',
'spatialIndexes',
];
const type = props.find((prop) =>
(this[prop] ?? []).some(
(
i:
| UniqueKeyModelInterface
| IndexModelInterface
| FulltextIndexModelInterface
| SpatialIndexModelInterface,
) => i === index,
),
);
return type;
}
/**
* Get which index array is storing a given index.
*
* @param indez
*/
getIndexTypeByName(name: string): IndexPropertyKey | undefined {
const props: IndexPropertyKey[] = [
'uniqueKeys',
'indexes',
'fulltextIndexes',
'spatialIndexes',
];
const type = props.find((prop) =>
(this[prop] ?? []).some(
(
i:
| UniqueKeyModelInterface
| IndexModelInterface
| FulltextIndexModelInterface
| SpatialIndexModelInterface,
) => i.name === name,
),
);
return type;
}
/**
* Get column by name.
*
* @param name Column name.
*/
getColumn(name: string): ColumnModelInterface | undefined {
return (this.columns ?? []).find((c) => c.name === name);
}
/**
* Get foreign key by name.
*
* @param name Foreign key name.
*/
getForeignKey(name: string): ForeignKeyModelInterface | undefined {
return (this.foreignKeys ?? []).find((k) => k.name === name);
}
/**
* Whether there is a foreign key with given name in table.
*
* @param name Foreign key name.
*/
hasForeignKey(name: string): boolean {
return (this.foreignKeys ?? []).some((k) => k.name === name);
}
/**
* Setter for table's primary key.
*
* @param primaryKey Primary key.
*/
setPrimaryKey(primaryKey: PrimaryKeyModelInterface): void {
/**
* Should not add primary key over another one.
*/
if (this.primaryKey) {
return;
}
/**
* Validate columns referenced by primary key.
*/
if (!primaryKey.hasAllColumnsFromTable(this)) {
return;
}
/**
* Make necessary changes in columns.
*/
(primaryKey.columns ?? []).forEach((indexCol) => {
if (!indexCol.column) {
return;
}
const column = this.getColumn(indexCol.column);
if (!column || !column.options) {
return;
}
column.options.nullable = false;
});
this.primaryKey = primaryKey;
}
/**
* Push a fulltext index to fulltextIndexes array.
*
* @param fulltextIndex Index to be pushed.
*/
pushFulltextIndex(fulltextIndex: FulltextIndexModelInterface): void {
/**
* Should not add index or key with same name.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/15
*/
if (fulltextIndex.name && this.getIndexByName(fulltextIndex.name)) {
return;
}
/**
* Validate columns referenced by fulltext index.
*/
if (!fulltextIndex.hasAllColumnsFromTable(this)) {
return;
}
if (!isDefined(this.fulltextIndexes)) {
this.fulltextIndexes = [];
}
this.fulltextIndexes.push(fulltextIndex);
}
/**
* Push a spatial index to spatialIndexes array.
*
* @param spatialIndex Index to be pushed.
*/
pushSpatialIndex(spatialIndex: SpatialIndexModelInterface): void {
/**
* Should not add index or key with same name.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/15
*/
if (spatialIndex.name && this.getIndexByName(spatialIndex.name)) {
return;
}
/**
* Validate columns referenced by spatial index.
*/
if (!spatialIndex.hasAllColumnsFromTable(this)) {
return;
}
if (!isDefined(this.spatialIndexes)) {
this.spatialIndexes = [];
}
this.spatialIndexes.push(spatialIndex);
}
/**
* Push an unique key to uniqueKeys array.
*
* @param uniqueKey UniqueKey to be pushed.
*/
pushUniqueKey(uniqueKey: UniqueKeyModelInterface): void {
/**
* Should not add index or key with same name.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/15
*/
if (uniqueKey.name && this.getIndexByName(uniqueKey.name)) {
return;
}
/**
* Validate columns referenced by unique key.
*/
if (!uniqueKey.hasAllColumnsFromTable(this)) {
return;
}
/**
* If index column length is not set, set it to full column size.
*
* "If no length is specified, the whole column will be indexed."
* https://mariadb.com/kb/en/library/create-table/#index-types
*/
uniqueKey.setIndexSizeFromTable(this);
if (!isDefined(this.uniqueKeys)) {
this.uniqueKeys = [];
}
this.uniqueKeys.push(uniqueKey);
}
/**
* Push a foreign key to foreignKeys array.
*
* @param foreignKey ForeignKey to be pushed.
*/
pushForeignKey(foreignKey: ForeignKeyModelInterface): void {
/**
* Should not add index or key with same name.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/15
*/
if (foreignKey.name && this.getIndexByName(foreignKey.name)) {
return;
}
/**
* Validate if referenced table exists.
*
* UPDATE:
* Since DDLs can run with FOREIGN_KEY_CHECKS disabled, this has been disabled.
* @see https://github.com/duartealexf/sql-ddl-to-json-schema/issues/27
* ~ duartealexf
*/
// const referencedTable = foreignKey.getReferencedTable(this.getTables());
// if (!referencedTable) { return; }
/**
* Validate columns.
*
* UPDATE:
* Since DDLs can run with FOREIGN_KEY_CHECKS disabled, this has been disabled.
* @see https://github.com/duartealexf/sql-ddl-to-json-schema/issues/27
* ~ duartealexf
*/
// const hasAllColumnsFromThisTable = foreignKey.hasAllColumnsFromTable(this);
// const hasAllColumnsFromReference = foreignKey.hasAllColumnsFromRefTable(referencedTable);
// if (!hasAllColumnsFromThisTable || !hasAllColumnsFromReference) { return; }
/**
* If index column length is not set, set it to full column size.
*
* "If no length is specified, the whole column will be indexed."
* https://mariadb.com/kb/en/library/create-table/#index-types
*/
foreignKey.setIndexSizeFromTable(this);
if (!isDefined(this.foreignKeys)) {
this.foreignKeys = [];
}
this.foreignKeys.push(foreignKey);
}
/**
* Push an index to indexes array.
*
* @param index Index to be pushed.
*/
pushIndex(index: IndexModelInterface): void {
/**
* Should not add index or key with same name.
* https://github.com/duartealexf/sql-ddl-to-json-schema/issues/15
*/
if (index.name && this.getIndexByName(index.name)) {
return;
}
/**
* Validate columns referenced by index.
*/
if (!index.hasAllColumnsFromTable(this)) {
return;
}
/**
* If index column length is not set, set it to full column size.
*
* "If no length is specified, the whole column will be indexed."
* https://mariadb.com/kb/en/library/create-table/#index-types
*/
index.setIndexSizeFromTable(this);
if (!isDefined(this.indexes)) {
this.indexes = [];
}
this.indexes.push(index);
}
} | the_stack |
import { DaprClient, DaprServer, Temporal } from '../../src';
import DemoActorActivateImpl from '../actor/DemoActorActivateImpl';
import DemoActorCounterImpl from '../actor/DemoActorCounterImpl';
import DemoActorReminderImpl from '../actor/DemoActorReminderImpl';
import DemoActorReminder2Impl from '../actor/DemoActorReminder2Impl';
import DemoActorSayImpl from '../actor/DemoActorSayImpl';
import DemoActorTimerImpl from '../actor/DemoActorTimerImpl';
const serverHost = "127.0.0.1";
const serverPort = "50001";
const sidecarHost = "127.0.0.1";
const sidecarPort = "50000";
describe('http/actors', () => {
let server: DaprServer;
let client: DaprClient;
// We need to start listening on some endpoints already
// this because Dapr is not dynamic and registers endpoints on boot
beforeAll(async () => {
// Start server and client
server = new DaprServer(serverHost, serverPort, sidecarHost, sidecarPort);
client = new DaprClient(sidecarHost, sidecarPort);
// has to be initialized before the server started!
// This will initialize the actor routes.
// Actors themselves can be initialized later
await server.actor.init();
await server.actor.registerActor(DemoActorCounterImpl);
await server.actor.registerActor(DemoActorSayImpl);
await server.actor.registerActor(DemoActorReminderImpl);
await server.actor.registerActor(DemoActorReminder2Impl);
await server.actor.registerActor(DemoActorTimerImpl);
await server.actor.registerActor(DemoActorActivateImpl);
// Start server
await server.startServer(); // Start the general server
});
afterAll(async () => {
await server.stopServer();
});
describe('actorProxy', () => {
it('should be able to create an actor object through the proxy', async () => {
const builder = new ActorProxyBuilder<DemoActorCounterImpl>(DemoActorCounterImpl, client);
const actor = builder.build(ActorId.createRandomId());
const c1 = await actor.getCounter();
expect(c1).toEqual(0);
await actor.countBy(1);
const c2 = await actor.getCounter();
expect(c2).toEqual(1);
await actor.countBy(5);
const c3 = await actor.getCounter();
expect(c3).toEqual(6);
});
});
describe('invoke', () => {
it('should register actors correctly', async () => {
const actors = await server.actor.getRegisteredActors();
expect(actors.length).toEqual(6);
expect(actors).toContain(DemoActorCounterImpl.name);
expect(actors).toContain(DemoActorSayImpl.name);
expect(actors).toContain(DemoActorReminderImpl.name);
expect(actors).toContain(DemoActorTimerImpl.name);
expect(actors).toContain(DemoActorActivateImpl.name);
});
it('should be able to invoke an actor through a text message', async () => {
const res = await client.actor.invoke("PUT", DemoActorSayImpl.name, "my-actor-id", "sayString", "Hello World");
expect(res).toEqual(`Actor said: "Hello World"`)
});
it('should be able to invoke an actor through an object message', async () => {
const res = await client.actor.invoke("PUT", DemoActorSayImpl.name, "my-actor-id", "sayObject", { hello: "world" });
expect(JSON.stringify(res)).toEqual(`{"said":{"hello":"world"}}`)
});
});
describe('timers', () => {
it('should fire a timer correctly (expected execution time > 5s)', async () => {
const actorId = `my-actor-counter-id-${(new Date()).getTime()}}`;
const timerId = "my-timer";
// Activate our actor
await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "init");
// Register a timer
await client.actor.timerCreate(DemoActorTimerImpl.name, actorId, timerId, {
callback: "count", // method name to execute on DemoActorTimerImpl
dueTime: Temporal.Duration.from({ seconds: 2 }),
period: Temporal.Duration.from({ seconds: 1 })
})
const res0 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res0).toEqual(0);
// Now we wait for dueTime (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// After that the timer callback will be called
// In our case, the callback increments the count attribute
const res1 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res1).toEqual(1);
// Every 1 second the timer gets called again, so the count attribute should change
// we check this twice to ensure correct calling
await (new Promise(resolve => setTimeout(resolve, 1000)));
const res2 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res2).toEqual(2);
await (new Promise(resolve => setTimeout(resolve, 1000)));
const res3 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res3).toEqual(3);
// Stop the timer
await client.actor.timerDelete(DemoActorTimerImpl.name, actorId, timerId);
// We then expect the counter to stop increasing
await (new Promise(resolve => setTimeout(resolve, 1000)));
const res4 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res4).toEqual(3);
// Stop the timer
await client.actor.timerDelete(DemoActorTimerImpl.name, actorId, timerId);
}, 10000);
it('should fire a timer correctly with the configured data', async () => {
const actorId = `my-actor`;
const timerId = "my-timer";
// Activate our actor
await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "init");
// Register a timer
await client.actor.timerCreate(DemoActorTimerImpl.name, actorId, timerId, {
callback: "countBy", // method name to execute on DemoActorTimerImpl
dueTime: Temporal.Duration.from({ seconds: 2 }),
period: Temporal.Duration.from({ seconds: 1 }),
data: 100
})
const res0 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res0).toEqual(0);
// Now we wait for dueTime (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// After that the timer callback will be called
// In our case, the callback increments the count attribute
const res1 = await client.actor.invoke("PUT", DemoActorTimerImpl.name, actorId, "getCounter");
expect(res1).toEqual(100);
// Stop the timer
await client.actor.timerDelete(DemoActorTimerImpl.name, actorId, timerId);
});
});
describe('reminders', () => {
it('should be able to unregister a reminder', async () => {
const actorId = `my-actor-for-reminder-unregistering`;
const reminderId = `my-reminder`;
// Activate our actor
await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "init");
// Register a reminder, it has a default callback
await client.actor.reminderCreate(DemoActorReminderImpl.name, actorId, reminderId, {
dueTime: Temporal.Duration.from({ seconds: 2 }),
period: Temporal.Duration.from({ seconds: 1 }),
data: 100
})
const res0 = await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "getCounter");
expect(res0).toEqual(0);
// Now we wait for dueTime (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// After that the reminder callback will be called
// In our case, the callback increments the count attribute
const res1 = await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "getCounter");
expect(res1).toEqual(100);
// Unregister a reminder, it has a default callback
await client.actor.reminderDelete(DemoActorReminderImpl.name, actorId, reminderId);
// Now we wait an extra period (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// Make sure the counter didn't change
const res2 = await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "getCounter");
expect(res2).toEqual(100);
});
it('should fire a reminder correctly', async () => {
const actorId = `my-actor-counter-id-for-reminder-firing`;
const reminderId = `my-reminder`;
// Activate our actor
await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "init");
// Register a reminder, it has a default callback
await client.actor.reminderCreate(DemoActorReminderImpl.name, actorId, reminderId, {
dueTime: Temporal.Duration.from({ seconds: 2 }),
period: Temporal.Duration.from({ seconds: 1 }),
data: 100
})
const res0 = await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "getCounter");
expect(res0).toEqual(0);
// Now we wait for dueTime (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// After that the timer callback will be called
// In our case, the callback increments the count attribute
const res1 = await client.actor.invoke("PUT", DemoActorReminderImpl.name, actorId, "getCounter");
expect(res1).toEqual(100);
// Unregister the reminder
await client.actor.reminderDelete(DemoActorReminderImpl.name, actorId, reminderId);
});
it('should fire a reminder but with a warning if it\'s not implemented correctly', async () => {
const actorId = `my-actor-counter-id-for-reminder-implementation-check`;
const reminderId = `my-reminder-2`;
// Create spy object
const spy = jest.spyOn(global.console, 'warn');
// Activate our actor
await client.actor.invoke("PUT", DemoActorReminder2Impl.name, actorId, "init");
// Register a reminder, it has a default callback
await client.actor.reminderCreate(DemoActorReminder2Impl.name, actorId, reminderId, {
dueTime: Temporal.Duration.from({ seconds: 2 }),
period: Temporal.Duration.from({ seconds: 1 }),
data: 100
});
const res0 = await client.actor.invoke("PUT", DemoActorReminder2Impl.name, actorId, "getCounter");
expect(res0).toEqual(0);
// Now we wait for dueTime (2s)
await (new Promise(resolve => setTimeout(resolve, 2000)));
// The method receiveReminder on AbstractActor should be called at least once
// this will state the not implemented function
expect(spy.mock.calls[0].length).toBe(1);
expect(spy.mock.calls[0][0]).toEqual(`{"error":"ACTOR_METHOD_NOT_IMPLEMENTED","errorMsg":"A reminder was created for the actor with id: ${actorId} but the method 'receiveReminder' was not implemented"}`);
// Unregister the reminder
await client.actor.reminderDelete(DemoActorReminder2Impl.name, actorId, reminderId);
});
});
}) | the_stack |
import {
PortfolioPlanningQueryInput,
PortfolioPlanningQueryResult,
PortfolioPlanningQueryResultItem,
PortfolioPlanningProjectQueryInput,
PortfolioPlanningProjectQueryResult,
IQueryResultError,
Project,
WorkItem,
PortfolioPlanningWorkItemQueryResult,
PortfolioPlanningDirectory,
PortfolioPlanning,
ExtensionStorageError,
PortfolioPlanningTeamsInAreaQueryInput,
PortfolioPlanningTeamsInAreaQueryResult,
TeamsInArea,
PortfolioPlanningFullContentQueryResult,
PortfolioPlanningMetadata,
PortfolioPlanningDependencyQueryInput,
PortfolioPlanningDependencyQueryResult,
WorkItemLinksQueryInput,
WorkItemLinksQueryResult,
WorkItemLink,
LinkTypeReferenceName,
WorkItemLinkIdType,
WorkItemProjectIdsQueryResult,
WorkItemProjectId,
PortfolioItem,
WorkItemType,
ProjectIdsQueryResult
} from "../../../PortfolioPlanning/Models/PortfolioPlanningQueryModels";
import { ODataClient } from "../ODataClient";
import {
ODataWorkItemQueryResult,
ODataAreaQueryResult,
WellKnownEffortODataColumnNames,
WorkItemTypeAggregationClauses,
ODataConstants
} from "../../../PortfolioPlanning/Models/ODataQueryModels";
import { GUIDUtil } from "../Utilities/GUIDUtil";
import { IdentityRef } from "VSS/WebApi/Contracts";
import { defaultProjectComparer } from "../Utilities/Comparers";
import { ExtensionConstants, IProjectConfiguration } from "../../Contracts";
import { PortfolioTelemetry } from "../Utilities/Telemetry";
import { ProjectConfigurationDataService } from "./ProjectConfigurationDataService";
import { PageWorkItemHelper } from "../../../Common/redux/Helpers/PageWorkItemHelper";
export class PortfolioPlanningDataService {
private static _instance: PortfolioPlanningDataService;
private static readonly DirectoryDocumentId: string = "Default";
private static readonly DirectoryCollectionName: string = "Directory";
private static readonly PortfolioPlansCollectionName: string = "PortfolioPlans";
public static getInstance(): PortfolioPlanningDataService {
if (!PortfolioPlanningDataService._instance) {
PortfolioPlanningDataService._instance = new PortfolioPlanningDataService();
}
return PortfolioPlanningDataService._instance;
}
public async runPortfolioItemsQuery(
queryInput: PortfolioPlanningQueryInput
): Promise<PortfolioPlanningQueryResult> {
const workItemsQuery = ODataQueryBuilder.WorkItemsQueryString(queryInput);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, workItemsQuery.queryString);
return client
.runPostQuery(fullQueryUrl)
.then(
(results: any) =>
this.ParseODataPortfolioPlanningQueryResultResponseAsBatch(
results,
workItemsQuery.aggregationClauses
),
error => this.ParseODataErrorResponse(error)
);
}
public async runProjectQuery(
queryInput: PortfolioPlanningProjectQueryInput
): Promise<PortfolioPlanningProjectQueryResult> {
const odataQueryString = ODataQueryBuilder.ProjectsQueryString(queryInput);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, odataQueryString);
return client
.runPostQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataProjectQueryResultResponseAsBatch(results),
error => this.ParseODataErrorResponse(error)
);
}
public async runTeamsInAreasQuery(
queryInput: PortfolioPlanningTeamsInAreaQueryInput
): Promise<PortfolioPlanningTeamsInAreaQueryResult> {
if (!queryInput || Object.keys(queryInput).length === 0) {
return Promise.resolve({
exceptionMessage: null,
teamsInArea: {}
});
}
const odataQueryString = ODataQueryBuilder.TeamsInAreaQueryString(queryInput);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, odataQueryString);
return client
.runPostQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataTeamsInAreaQueryResultResponseAsBatch(results),
error => this.ParseODataErrorResponse(error)
);
}
public async runWorkItemLinksQuery(queryInput: WorkItemLinksQueryInput): Promise<WorkItemLinksQueryResult> {
if (
!queryInput ||
!queryInput.WorkItemIdsByProject ||
Object.keys(queryInput.WorkItemIdsByProject).length === 0
) {
return Promise.resolve({
exceptionMessage: null,
Links: [],
QueryInput: queryInput
});
}
const odataQueryString = ODataQueryBuilder.WorkItemLinksQueryString(queryInput);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, odataQueryString);
return client
.runPostQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataWorkItemLinksQueryQueryResultResponseAsBatch(results, queryInput),
error => this.ParseODataErrorResponse(error)
);
}
public async getWorkItemProjectIds(
workItemIds: number[],
telemetryService?: PortfolioTelemetry
): Promise<WorkItemProjectIdsQueryResult> {
if (!telemetryService) {
telemetryService = PortfolioTelemetry.getInstance();
}
if (!workItemIds || workItemIds.length === 0) {
return Promise.resolve({
exceptionMessage: null,
Results: null,
QueryInput: workItemIds
});
}
// Can't use OData service to get work item information just based on Ids.
// OData requires a project id or name filter to check security, and we don't have it.
// Using WIQL query service to get project name and work item type for each work item id,
// then using OData service to get project ids based on project names.
// Unfortunately, WIQL doesn't support System.ProjectId :-(.
const workItemIdsMap: { [workitemId: number]: number } = {};
workItemIds.forEach(id => {
workItemIdsMap[id.toString()] = true;
});
const workItemIdsSet = Object.keys(workItemIdsMap).map(idStr => Number(idStr));
const workItemInfo = await PageWorkItemHelper.pageWorkItems(workItemIdsSet, null /** projectName */, [
"System.Id",
"System.WorkItemType",
"System.TeamProject"
]);
const projectIdsByName: { [projectNameKey: string]: string } = {};
workItemInfo.forEach(wi => {
const projectNameKey = (wi.fields["System.TeamProject"] as string).toLowerCase();
// will add project id later.
projectIdsByName[projectNameKey] = null;
});
const projectNamesSet = Object.keys(projectIdsByName).map(name => name);
const projectIdQueryResult: ProjectIdsQueryResult = await PortfolioPlanningDataService.getInstance().getProjectIds(
projectNamesSet
);
if (projectIdQueryResult.exceptionMessage && projectIdQueryResult.exceptionMessage.length > 0) {
throw new Error(
`runDependencyQuery: Exception running project ids query. Inner exception: ${
projectIdQueryResult.exceptionMessage
}`
);
}
if (!projectIdQueryResult.Results || projectIdQueryResult.Results.length === 0) {
const exceptionMessage = `Could not retrieve project ids for linked work items: ${workItemIdsSet.join(
", "
)}. Project names found: ${projectNamesSet.join(", ")}`;
telemetryService.TrackException(new Error(exceptionMessage));
return {
exceptionMessage,
Results: [],
QueryInput: workItemIdsSet
};
}
projectIdQueryResult.Results.forEach(res => {
const projectNameKey = res.ProjectName.toLowerCase();
if (!projectIdsByName[projectNameKey]) {
projectIdsByName[projectNameKey] = res.ProjectSK;
}
});
const Results: WorkItemProjectId[] = [];
workItemInfo.forEach(wi => {
const projectNameKey = (wi.fields["System.TeamProject"] as string).toLowerCase();
if (!projectIdsByName[projectNameKey]) {
// Couldn't find the project id for this linked work item, so ignoring it.
const telemetryData = {
["ProjectName"]: projectNameKey,
["WorkItemId"]: wi.id
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/GetWorkItemProjectIds/MissingProjectId",
telemetryData
);
} else {
Results.push({
WorkItemId: wi.fields["System.Id"],
WorkItemType: wi.fields["System.WorkItemType"],
ProjectSK: projectIdsByName[projectNameKey]
});
}
});
return {
exceptionMessage: null,
Results,
QueryInput: workItemIdsSet
};
}
public async runDependencyQuery(
queryInput: PortfolioPlanningDependencyQueryInput
): Promise<PortfolioPlanningDependencyQueryResult> {
return DependencyQuery.runDependencyQuery(queryInput);
}
public async getODataColumnNameFromWorkItemFieldReferenceName(fieldReferenceName: string): Promise<string> {
// For out-of-the-box process templates (Agile, Scrum, etc...), we'll use well-known column names to avoid
// a call to the $metadata OData endpoint.
const columnName = this.GetODataColumnNameFromFieldRefName(fieldReferenceName);
if (!columnName) {
const client = await ODataClient.getInstance();
return client.runMetadataWorkItemReferenceNameQuery(fieldReferenceName);
}
return Promise.resolve(columnName);
}
public async loadPortfolioContent(
portfolioQueryInput: PortfolioPlanningQueryInput
): Promise<PortfolioPlanningFullContentQueryResult> {
const projects: { [projectId: string]: boolean } = {};
portfolioQueryInput.WorkItems.forEach(workItems => {
const projectIdKey = workItems.projectId.toLowerCase();
if (!projects[projectIdKey]) {
projects[projectIdKey] = true;
}
});
const projectsQueryInput: PortfolioPlanningProjectQueryInput = {
projects
};
const [portfolioQueryResult, projectQueryResult] = await Promise.all([
this.runPortfolioItemsQuery(portfolioQueryInput),
this.runProjectQuery(projectsQueryInput)
]);
const teamsInAreaQueryInput: PortfolioPlanningTeamsInAreaQueryInput = {};
for (let entry of (portfolioQueryResult as PortfolioPlanningQueryResult).items) {
const projectIdKey = entry.ProjectId.toLowerCase();
const areaIdKey = entry.AreaId.toLowerCase();
if (!teamsInAreaQueryInput[projectIdKey]) {
teamsInAreaQueryInput[projectIdKey] = {};
}
if (!teamsInAreaQueryInput[projectIdKey][areaIdKey]) {
teamsInAreaQueryInput[projectIdKey][areaIdKey] = true;
}
}
const teamAreasQueryResult = await this.runTeamsInAreasQuery(teamsInAreaQueryInput);
return {
items: portfolioQueryResult,
projects: projectQueryResult,
teamAreas: teamAreasQueryResult,
mergeStrategy: null
};
}
public async getAllProjects(): Promise<PortfolioPlanningProjectQueryResult> {
const odataQueryString = ODataQueryBuilder.AllProjectsQueryString();
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, odataQueryString);
return client
.runGetQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataProjectQueryResultResponse(results),
error => this.ParseODataErrorResponse(error)
);
}
public async getProjectIds(projectNamesSet: string[]): Promise<ProjectIdsQueryResult> {
if (!projectNamesSet || projectNamesSet.length === 0) {
return Promise.resolve({
exceptionMessage: null,
Results: [],
QueryInput: projectNamesSet
});
}
const odataQueryString = ODataQueryBuilder.ProjectIdsQueryString(projectNamesSet);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(undefined, odataQueryString);
return client
.runPostQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataProjectIdsQueryQueryResultResponseAsBatch(results, projectNamesSet),
error => this.ParseODataErrorResponse(error)
);
}
public async getAllWorkItemsOfTypeInProject(
projectGuid: string,
workItemType: string
): Promise<PortfolioPlanningWorkItemQueryResult> {
const odataQueryString = ODataQueryBuilder.WorkItemsOfTypeQueryString(workItemType);
const client = await ODataClient.getInstance();
const fullQueryUrl = client.generateProjectLink(projectGuid, odataQueryString);
return client
.runGetQuery(fullQueryUrl)
.then(
(results: any) => this.ParseODataWorkItemQueryResultResponse(results),
error => this.ParseODataErrorResponse(error)
);
}
public async GetAllPortfolioPlans(): Promise<PortfolioPlanningDirectory> {
const client = await this.GetStorageClient();
return client
.getDocument(
PortfolioPlanningDataService.DirectoryCollectionName,
PortfolioPlanningDataService.DirectoryDocumentId
)
.then(
doc => this.ParsePortfolioDirectory(doc),
error => {
const parsedError = this.ParseStorageError(error);
if (parsedError.status === 404) {
// Collection has not been created, initialize it.
const newDirectory: PortfolioPlanningDirectory = {
exceptionMessage: null,
id: PortfolioPlanningDataService.DirectoryDocumentId,
entries: []
};
return client
.createDocument(PortfolioPlanningDataService.DirectoryCollectionName, newDirectory)
.then(
newDirectory => newDirectory,
// We failed while creating the collection for the first time.
error => this.ParseStorageError(error)
);
}
return parsedError;
}
);
}
public async GetPortfolioPlanDirectoryEntry(id: string): Promise<PortfolioPlanningMetadata> {
const allPlans = await this.GetAllPortfolioPlans();
return allPlans.entries.find(plan => plan.id === id);
}
public async UpdatePortfolioPlanDirectoryEntry(updatedPlan: PortfolioPlanningMetadata): Promise<void> {
const client = await this.GetStorageClient();
const allPlans = await this.GetAllPortfolioPlans();
let indexToUpdate = allPlans.entries.findIndex(plan => plan.id === updatedPlan.id);
updatedPlan.id = allPlans.entries[indexToUpdate].id;
allPlans.entries[indexToUpdate] = updatedPlan;
await client.updateDocument(PortfolioPlanningDataService.DirectoryCollectionName, allPlans);
}
public async AddPortfolioPlan(
newPlanName: string,
newPlanDescription: string,
owner: IdentityRef
): Promise<PortfolioPlanning> {
const client = await this.GetStorageClient();
const newPlanId = GUIDUtil.newGuid().toLowerCase();
const newPlan: PortfolioPlanning = {
id: newPlanId,
name: newPlanName,
description: newPlanDescription,
teamNames: [],
projectNames: [],
owner: owner,
createdOn: new Date(),
projects: {},
SchemaVersion: ExtensionConstants.CURRENT_PORTFOLIO_SCHEMA_VERSION
};
const savedPlan = await client.setDocument(PortfolioPlanningDataService.PortfolioPlansCollectionName, newPlan);
let allPlans = await this.GetAllPortfolioPlans();
if (!allPlans) {
allPlans = {
exceptionMessage: null,
id: PortfolioPlanningDataService.DirectoryDocumentId,
entries: []
};
}
allPlans.entries.push(savedPlan);
await client.updateDocument(PortfolioPlanningDataService.DirectoryCollectionName, allPlans);
return newPlan;
}
public async GetPortfolioPlanById(portfolioPlanId: string): Promise<PortfolioPlanning> {
const client = await this.GetStorageClient();
const planIdLowercase = portfolioPlanId.toLowerCase();
return client.getDocument(PortfolioPlanningDataService.PortfolioPlansCollectionName, planIdLowercase);
}
public async UpdatePortfolioPlan(newPlan: PortfolioPlanning): Promise<PortfolioPlanning> {
const client = await this.GetStorageClient();
// TODO sanitize other properties (e.g. unique set of work item ids, all strings lower case)
newPlan.id = newPlan.id.toLowerCase();
return client
.updateDocument(PortfolioPlanningDataService.PortfolioPlansCollectionName, newPlan)
.then(doc => doc);
}
public async DeletePortfolioPlan(planId: string): Promise<void> {
const client = await this.GetStorageClient();
const planIdToDelete = planId.toLowerCase();
let allPlans = await this.GetAllPortfolioPlans();
allPlans.entries = allPlans.entries.filter(plan => plan.id !== planIdToDelete);
await client.updateDocument(PortfolioPlanningDataService.DirectoryCollectionName, allPlans);
return client.deleteDocument(PortfolioPlanningDataService.PortfolioPlansCollectionName, planIdToDelete);
}
public async DeleteAllData(): Promise<number> {
const client = await this.GetStorageClient();
let totalThatWillBeDeleted = 0;
// Delete documents in Directory collection.
const allEntriesInDirectory = await client.getDocuments(PortfolioPlanningDataService.DirectoryCollectionName);
totalThatWillBeDeleted += allEntriesInDirectory.length;
allEntriesInDirectory.forEach(doc => {
client
.deleteDocument(PortfolioPlanningDataService.DirectoryCollectionName, doc.id)
.then(deletedDoc => console.log(`Deleted Directory collection document: ${doc.id}`));
});
// Delete documents in Portfolio plans collection.
const allEntriesInPlans = await client.getDocuments(PortfolioPlanningDataService.PortfolioPlansCollectionName);
totalThatWillBeDeleted += allEntriesInPlans.length;
allEntriesInPlans.forEach(doc => {
client
.deleteDocument(PortfolioPlanningDataService.PortfolioPlansCollectionName, doc.id)
.then(deletedDoc => console.log(`Deleted Plans collection document: ${doc.id}`));
});
return totalThatWillBeDeleted;
}
public async AddWorkItemsToPlan(
planId: string,
workItemIds: number[],
telemetryService?: PortfolioTelemetry
): Promise<PortfolioPlanning> {
if (!telemetryService) {
telemetryService = PortfolioTelemetry.getInstance();
}
try {
console.log(`AddWorkItemsToPlan. WorkItemIds: ${workItemIds.join(", ")}. Plan: ${planId}`);
const telemetryData = {
["PlanId"]: planId,
["WorkItemCount"]: workItemIds.length
};
telemetryService.TrackAction("PortfolioPlanningDataService/AddWorkItemsToPlan", telemetryData);
if (workItemIds.length === 0) {
// No-op.
const props = {
["PlanId"]: planId
};
telemetryService.TrackAction("PortfolioPlanningDataService/AddWorkItemsToPlan/NoOp", props);
return null;
}
const plan = await this.GetPortfolioPlanById(planId);
if (!plan) {
// Couldn't find plan to update. Ignoring.
const props = {
["PlanId"]: planId,
["WorkItemIds"]: workItemIds
};
telemetryService.TrackAction("PortfolioPlanningDataService/AddWorkItemsToPlan/NoPlanFound", props);
return null;
}
const workItemIdsSet: { [workItemId: number]: true } = {};
workItemIds.forEach(id => (workItemIdsSet[id.toString()] = true));
const projectMapping = await this.getWorkItemProjectIds(
Object.keys(workItemIdsSet).map(id => Number(id)),
telemetryService
);
if (projectMapping && projectMapping.exceptionMessage && projectMapping.exceptionMessage.length > 0) {
throw new Error(
`Error querying project information for work item ids. Details: ${projectMapping.exceptionMessage}`
);
}
if (!projectMapping || !projectMapping.Results || projectMapping.Results.length === 0) {
// Work item project ids query returned no results.
const props = {
["WorkItemIds"]: workItemIds
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/AddWorkItemsToPlan/WorkItemProjectIdsNoResults",
props
);
return null;
}
const allProjectConfigPromises: Promise<IProjectConfiguration>[] = [];
const allProjectConfigPromisesProjectIds: { [projectIdKey: string]: boolean } = {};
const newProjectConfigsByProjectId: { [projectIdKey: string]: IProjectConfiguration } = {};
const byWorkItemId: { [workItemId: number]: WorkItemProjectId } = {};
// Do we need to get configuration for projects we are seeing for the first time?
projectMapping.Results.forEach(map => {
const projectIdKey = map.ProjectSK.toLowerCase();
const workItemId = map.WorkItemId;
byWorkItemId[workItemId.toString()] = map;
if (!plan.projects[projectIdKey] && !allProjectConfigPromisesProjectIds[projectIdKey]) {
// New project, need to get project configuration.
allProjectConfigPromises.push(
ProjectConfigurationDataService.getInstance().getProjectConfiguration(projectIdKey)
);
allProjectConfigPromisesProjectIds[projectIdKey] = true;
}
});
// Are we missing work item type data for new work item ids?
const projectIdsNoTypes: { [projectIdKey: string]: boolean } = {};
Object.keys(byWorkItemId).forEach(newWorkItemId => {
const newWorkItem: WorkItemProjectId = byWorkItemId[newWorkItemId];
const projectIdKey = newWorkItem.ProjectSK.toLowerCase();
const workItemTypeKey = newWorkItem.WorkItemType.toLowerCase();
if (
plan.projects[projectIdKey] &&
(!plan.projects[projectIdKey].WorkItemTypeData ||
!plan.projects[projectIdKey].WorkItemTypeData[workItemTypeKey]) &&
!allProjectConfigPromisesProjectIds[projectIdKey]
) {
projectIdsNoTypes[projectIdKey] = true;
}
});
Object.keys(projectIdsNoTypes).forEach(projectIdKey => {
allProjectConfigPromises.push(
ProjectConfigurationDataService.getInstance().getProjectConfiguration(projectIdKey)
);
});
// New projects?
if (allProjectConfigPromises.length > 0) {
const newProjectConfigs = await Promise.all(allProjectConfigPromises);
newProjectConfigs.forEach(config => {
const projectIdKey = config.id.toLowerCase();
newProjectConfigsByProjectId[projectIdKey] = config;
});
}
// Merge new data.
Object.keys(workItemIdsSet).forEach(newWorkItemId => {
if (byWorkItemId[newWorkItemId]) {
const workItemInfo: WorkItemProjectId = byWorkItemId[newWorkItemId];
const projectIdKey = workItemInfo.ProjectSK.toLowerCase();
const workItemTypeKey = workItemInfo.WorkItemType.toLowerCase();
if (plan.projects[projectIdKey]) {
if (!plan.projects[projectIdKey].Items) {
plan.projects[projectIdKey].Items = {};
}
if (!plan.projects[projectIdKey].Items[newWorkItemId]) {
if (!plan.projects[projectIdKey].WorkItemTypeData) {
plan.projects[projectIdKey].WorkItemTypeData = {};
}
if (!plan.projects[projectIdKey].WorkItemTypeData[workItemTypeKey]) {
// Did we just query for this project's config?
if (newProjectConfigsByProjectId[projectIdKey]) {
const projectConfig = newProjectConfigsByProjectId[projectIdKey];
// Does the project config support this work item type?
if (projectConfig.iconInfoByWorkItemType[workItemTypeKey]) {
// Ok, we can add the work item id to the project. It's type is
// supported based on the project configuration.
plan.projects[projectIdKey].Items[newWorkItemId] = {
workItemId: newWorkItemId,
workItemType: workItemInfo.WorkItemType
};
plan.projects[projectIdKey].WorkItemTypeData[workItemTypeKey] = {
workItemType: workItemInfo.WorkItemType,
backlogLevelName:
projectConfig.backlogLevelNamesByWorkItemType[workItemTypeKey],
iconProps: projectConfig.iconInfoByWorkItemType[workItemTypeKey]
};
} else {
// Work item type is not supported.
const props = {
["WorkItemId"]: newWorkItemId,
["WorkItemType"]: workItemTypeKey
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/AddWorkItemsToPlan/WorkItemTypeNotSupported",
props
);
}
} else {
const errorMessage = `Cannot add work item id '${newWorkItemId}' to plan id '${
plan.id
}'. Couldn't retrieve configuration for project '${projectIdKey}'`;
const error = new Error(errorMessage);
PortfolioTelemetry.getInstance().TrackException(error);
throw error;
}
} else {
// Work item type was already supported in the project, just add the work item id.
plan.projects[projectIdKey].Items[newWorkItemId] = {
workItemId: newWorkItemId,
workItemType: workItemInfo.WorkItemType
};
}
}
} else if (newProjectConfigsByProjectId[projectIdKey]) {
const newProjectInfo: IProjectConfiguration = newProjectConfigsByProjectId[projectIdKey];
// Does the project config support this work item type?
if (newProjectInfo.iconInfoByWorkItemType[workItemTypeKey]) {
const Items: { [workItemId: number]: PortfolioItem } = {};
const WorkItemTypeData: { [workItemTypeKey: string]: WorkItemType } = {};
Items[newWorkItemId] = {
workItemId: newWorkItemId,
workItemType: workItemInfo.WorkItemType
};
WorkItemTypeData[workItemTypeKey] = {
workItemType: workItemInfo.WorkItemType,
backlogLevelName: newProjectInfo.backlogLevelNamesByWorkItemType[workItemTypeKey],
iconProps: newProjectInfo.iconInfoByWorkItemType[workItemTypeKey]
};
plan.projects[projectIdKey] = {
ProjectId: projectIdKey,
RequirementWorkItemType: newProjectInfo.defaultRequirementWorkItemType,
EffortODataColumnName: newProjectInfo.effortODataColumnName,
EffortWorkItemFieldRefName: newProjectInfo.effortWorkItemFieldRefName,
Items,
WorkItemTypeData
};
} else {
// Work item type is not supported.
const props = {
["WorkItemId"]: newWorkItemId,
["WorkItemType"]: workItemTypeKey
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/AddWorkItemsToPlan/WorkItemTypeNotSupported",
props
);
}
} else {
// Couldn't find project configuration for work item's project id. Ignoring.
const props = {
["WorkItemId"]: newWorkItemId,
["ProjectId"]: projectIdKey
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/AddWorkItemsToPlan/MissingProjectConfiguration",
props
);
}
} else {
// Couldn't find project mapping for work item id. Ignoring.
const props = {
["WorkItemId"]: newWorkItemId
};
telemetryService.TrackAction(
"PortfolioPlanningDataService/AddWorkItemsToPlan/MissingProjectIdForNewWorkItemId",
props
);
}
});
// Persist plan changes
return await this.UpdatePortfolioPlan(plan);
} catch (error) {
telemetryService.TrackException(error);
console.log(error);
const exceptionMessage: string = (error as Error).message;
return Promise.reject(exceptionMessage);
}
}
private GetODataColumnNameFromFieldRefName(fieldReferenceName: string): WellKnownEffortODataColumnNames {
if (!fieldReferenceName) {
return null;
}
return PortfolioPlanningDataService.WellKnownODataColumnNamesByWorkItemRefName[
fieldReferenceName.toLowerCase()
];
}
private static readonly WellKnownODataColumnNamesByWorkItemRefName: {
[fieldReferenceName: string]: WellKnownEffortODataColumnNames;
} = {
"microsoft.vsts.scheduling.effort": WellKnownEffortODataColumnNames.Effort,
"microsoft.vsts.scheduling.storypoints": WellKnownEffortODataColumnNames.StoryPoints,
"microsoft.vsts.scheduling.size": WellKnownEffortODataColumnNames.Size
};
private async GetStorageClient(): Promise<IExtensionDataService> {
return VSS.getService<IExtensionDataService>(VSS.ServiceIds.ExtensionData);
}
private ParsePortfolioDirectory(doc: any): PortfolioPlanningDirectory {
if (!doc) {
return {
exceptionMessage: null,
id: null,
entries: null
};
}
const directory: PortfolioPlanningDirectory = doc;
for (const entry of directory.entries) {
entry.createdOn = new Date(entry.createdOn);
}
return directory;
}
private ParseStorageError(error: any): IQueryResultError {
if (!error) {
return {
exceptionMessage: "no error information"
};
}
const parsedError: ExtensionStorageError = error;
return {
exceptionMessage: parsedError.message,
status: parsedError.status
};
}
private ParseODataBatchResponse(
results: any
): {
exceptionMessage: any;
responseValue: any;
} {
if (!results) {
return null;
}
const responseString: string = results;
try {
// TODO hack hack ... Look for start of JSON response "{"@odata.context""
const start = responseString.indexOf('{"@odata.context"');
const end = responseString.lastIndexOf("}");
if (start !== -1) {
const jsonString = responseString.substring(start, end + 1);
const jsonObject = JSON.parse(jsonString);
if (!jsonObject || !jsonObject["value"]) {
return null;
}
return {
exceptionMessage: null,
responseValue: jsonObject
};
} else {
// TODO hack hack ... Didn't find OData success response, let's see if there was an OData error.
const start = responseString.indexOf('{"error"');
const end = responseString.lastIndexOf("}");
const jsonString = responseString.substring(start, end + 1);
const jsonObject = JSON.parse(jsonString);
return {
exceptionMessage: jsonObject.error.message,
responseValue: null
};
}
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
responseValue: null
};
}
}
private ParseODataProjectIdsQueryQueryResultResponseAsBatch(
results: any,
queryInput: string[]
): ProjectIdsQueryResult {
try {
const rawResponseValue = this.ParseODataBatchResponse(results);
if (
!rawResponseValue ||
(rawResponseValue.exceptionMessage && rawResponseValue.exceptionMessage.length > 0)
) {
const errorMessage =
rawResponseValue!.exceptionMessage || "No response payload found in OData batch query";
return {
exceptionMessage: errorMessage,
Results: [],
QueryInput: queryInput
};
}
return {
exceptionMessage: null,
Results: this.ProjectIdsQueryResultItems(rawResponseValue.responseValue),
QueryInput: queryInput
};
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
Results: [],
QueryInput: queryInput
};
}
}
private ProjectIdsQueryResultItems(jsonValuePayload: any): Project[] {
if (!jsonValuePayload || !jsonValuePayload["value"]) {
return null;
}
const rawResult: Project[] = jsonValuePayload.value;
return rawResult;
}
private ParseODataWorkItemLinksQueryQueryResultResponseAsBatch(
results: any,
queryInput: WorkItemLinksQueryInput
): WorkItemLinksQueryResult {
try {
const rawResponseValue = this.ParseODataBatchResponse(results);
if (
!rawResponseValue ||
(rawResponseValue.exceptionMessage && rawResponseValue.exceptionMessage.length > 0)
) {
const errorMessage =
rawResponseValue!.exceptionMessage || "No response payload found in OData batch query";
return {
exceptionMessage: errorMessage,
Links: [],
QueryInput: queryInput
};
}
return {
exceptionMessage: null,
Links: this.WorkItemLinksQueryResultItems(rawResponseValue.responseValue),
QueryInput: queryInput
};
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
Links: [],
QueryInput: queryInput
};
}
}
private WorkItemLinksQueryResultItems(jsonValuePayload: any): WorkItemLink[] {
if (!jsonValuePayload || !jsonValuePayload["value"]) {
return null;
}
const rawResult: WorkItemLink[] = jsonValuePayload.value;
return rawResult;
}
private ParseODataPortfolioPlanningQueryResultResponseAsBatch(
results: any,
aggregationClauses: WorkItemTypeAggregationClauses
): PortfolioPlanningQueryResult {
try {
const rawResponseValue = this.ParseODataBatchResponse(results);
if (
!rawResponseValue ||
(rawResponseValue.exceptionMessage && rawResponseValue.exceptionMessage.length > 0)
) {
const errorMessage =
rawResponseValue!.exceptionMessage || "No response payload found in OData batch query";
return {
exceptionMessage: errorMessage,
items: []
};
}
return {
exceptionMessage: null,
items: this.PortfolioPlanningQueryResultItems(rawResponseValue.responseValue, aggregationClauses)
};
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
items: []
};
}
}
private PortfolioPlanningQueryResultItems(
jsonValuePayload: any,
aggregationClauses: WorkItemTypeAggregationClauses
): PortfolioPlanningQueryResultItem[] {
if (!jsonValuePayload || !jsonValuePayload["value"]) {
return null;
}
return jsonValuePayload.value.map(jsonArrayItem => {
const rawItem: ODataWorkItemQueryResult = jsonArrayItem;
const areaIdValue: string = rawItem.AreaSK ? rawItem.AreaSK.toLowerCase() : null;
const result: PortfolioPlanningQueryResultItem = {
WorkItemId: rawItem.WorkItemId,
WorkItemType: rawItem.WorkItemType,
Title: rawItem.Title,
State: rawItem.State,
StartDate: rawItem.StartDate ? new Date(rawItem.StartDate) : null,
TargetDate: rawItem.TargetDate ? new Date(rawItem.TargetDate) : null,
ProjectId: rawItem.ProjectSK,
AreaId: areaIdValue,
TeamId: null, // Will be assigned when teams in areas data is retrieved.
CompletedCount: 0,
TotalCount: 0,
CompletedEffort: 0,
TotalEffort: 0,
EffortProgress: 0.0,
CountProgress: 0.0
};
const descendantsJsonObject = jsonArrayItem[ODataConstants.Descendants];
if (descendantsJsonObject && descendantsJsonObject.length === 1) {
const projectIdLowercase = rawItem.ProjectSK.toLowerCase();
const propertyAliases = aggregationClauses.aliasMap[projectIdLowercase]
? aggregationClauses.aliasMap[projectIdLowercase]
: null;
this.ParseDescendant(descendantsJsonObject[0], result, propertyAliases);
}
return result;
});
}
private ParseODataTeamsInAreaQueryResultResponseAsBatch(results: any): PortfolioPlanningTeamsInAreaQueryResult {
try {
const rawResponseValue = this.ParseODataBatchResponse(results);
if (
!rawResponseValue ||
(rawResponseValue.exceptionMessage && rawResponseValue.exceptionMessage.length > 0)
) {
const errorMessage =
rawResponseValue!.exceptionMessage || "No response payload found in OData batch query";
return {
exceptionMessage: errorMessage,
teamsInArea: null
};
}
return this.ParseODataTeamsInAreaQueryResultResponse(rawResponseValue.responseValue);
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
teamsInArea: null
};
}
}
private ParseODataTeamsInAreaQueryResultResponse(results: any): PortfolioPlanningTeamsInAreaQueryResult {
if (!results || !results["value"]) {
return null;
}
const rawResult: ODataAreaQueryResult[] = results.value;
return {
exceptionMessage: null,
teamsInArea: this.PortfolioPlanningAreaQueryResultItems(rawResult)
};
}
private ParseODataWorkItemQueryResultResponse(results: any): PortfolioPlanningWorkItemQueryResult {
if (!results || !results["value"]) {
return null;
}
const rawResult: WorkItem[] = results.value;
return {
exceptionMessage: null,
workItems: rawResult
};
}
private ParseODataProjectQueryResultResponseAsBatch(results: any): PortfolioPlanningProjectQueryResult {
try {
const rawResponseValue = this.ParseODataBatchResponse(results);
if (
!rawResponseValue ||
(rawResponseValue.exceptionMessage && rawResponseValue.exceptionMessage.length > 0)
) {
const errorMessage =
rawResponseValue!.exceptionMessage || "No response payload found in OData batch query";
return {
exceptionMessage: errorMessage,
projects: []
};
}
return this.ParseODataProjectQueryResultResponse(rawResponseValue.responseValue);
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
projects: null
};
}
}
private ParseODataProjectQueryResultResponse(results: any): PortfolioPlanningProjectQueryResult {
if (!results || !results["value"]) {
return null;
}
const rawResult: Project[] = results.value;
// Sort results by project name.
rawResult.sort(defaultProjectComparer);
return {
exceptionMessage: null,
projects: rawResult
};
}
private ParseDescendant(
descendantJsonObject: any,
resultItem: PortfolioPlanningQueryResultItem,
propertyAliases: {
totalEffortAlias: string;
completedEffortAlias: string;
}
): void {
// Parse static content. All queries, no matter the work item types project configuration
// will always return these values for each descendant.
const totalCount: number = descendantJsonObject[ODataConstants.TotalCount] || 0;
const completedCount: number = descendantJsonObject[ODataConstants.CompletedCount] || 0;
const countProgress: number = totalCount && completedCount && totalCount > 0 ? completedCount / totalCount : 0;
resultItem.TotalCount = totalCount;
resultItem.CompletedCount = completedCount;
resultItem.CountProgress = countProgress;
// Effort progress values depend on the work item type used for the requirement backlog level.
let totalEffort: number = 0;
let completedEffort: number = 0;
let effortProgress: number = 0;
if (propertyAliases) {
totalEffort = descendantJsonObject[propertyAliases.totalEffortAlias] || 0;
completedEffort = descendantJsonObject[propertyAliases.completedEffortAlias] || 0;
effortProgress = totalEffort && completedEffort && totalEffort > 0 ? completedEffort / totalEffort : 0;
}
resultItem.TotalEffort = totalEffort;
resultItem.CompletedEffort = completedEffort;
resultItem.EffortProgress = effortProgress;
}
private PortfolioPlanningAreaQueryResultItems(rawItems: ODataAreaQueryResult[]): TeamsInArea {
const result: TeamsInArea = {};
rawItems.forEach(areaQueryResult => {
const areaIdKey = areaQueryResult.AreaSK.toLowerCase();
result[areaIdKey] = areaQueryResult.Teams.map(odataTeam => {
return {
teamId: odataTeam.TeamSK.toLowerCase(),
teamName: odataTeam.TeamName
};
});
});
return result;
}
private ParseODataErrorResponse(results: any): IQueryResultError {
let errorMessage: string = "Unknown Error";
if (results && results.responseJSON && results.responseJSON.error && results.responseJSON.error.message) {
errorMessage = results.responseJSON.error.message;
} else if (results) {
errorMessage = JSON.stringify(results, null, " ");
}
return {
exceptionMessage: errorMessage
};
}
}
export class ODataQueryBuilder {
private static readonly ProjectEntitySelect: string = "ProjectSK,ProjectName";
private static readonly WorkItemLinksEntitySelect: string =
"WorkItemLinkSK,SourceWorkItemId,TargetWorkItemId,LinkTypeReferenceName,ProjectSK";
public static WorkItemsQueryString(
input: PortfolioPlanningQueryInput
): {
queryString: string;
aggregationClauses: WorkItemTypeAggregationClauses;
} {
const descendantsQuery = this.BuildODataDescendantsQuery(input);
// prettier-ignore
return {
queryString:
"WorkItems" +
"?" +
"$select=WorkItemId,WorkItemType,Title,State,StartDate,TargetDate,ProjectSK,AreaSK" +
"&" +
`$filter=${this.BuildODataQueryFilter(input)}` +
"&" +
`$expand=${descendantsQuery.queryString}`,
aggregationClauses: descendantsQuery.aggregationClauses
};
}
public static ProjectsQueryString(input: PortfolioPlanningProjectQueryInput): string {
// prettier-ignore
return (
"Projects" +
"?" +
`$select=${ODataQueryBuilder.ProjectEntitySelect}` +
"&" +
`$filter=${this.ProjectsQueryFilter(input)}`
);
}
public static AllProjectsQueryString(): string {
// prettier-ignore
return (
"Projects" +
"?" +
`$select=${ODataQueryBuilder.ProjectEntitySelect}`
);
}
public static ProjectIdsQueryString(projectNamesSet: string[]): string {
const filters: string[] = projectNamesSet.map(projectName => `ProjectName eq '${projectName}'`);
// prettier-ignore
return (
"Projects" +
"?" +
`$select=${ODataQueryBuilder.ProjectEntitySelect}` +
"&" +
`$filter=(${filters.join(" or ")})`
);
}
public static WorkItemsOfTypeQueryString(workItemType: string): string {
// prettier-ignore
return (
"WorkItems" +
"?" +
"$select=WorkItemId,WorkItemType,Title,State" +
"&" +
`$filter=WorkItemType eq '${workItemType}'`
);
}
public static TeamsInAreaQueryString(input: PortfolioPlanningTeamsInAreaQueryInput): string {
// prettier-ignore
return (
"Areas" +
"?" +
"$select=ProjectSK,AreaSK" +
"&" +
`$filter=${this.ProjectAreasFilter(input)}` +
"&" +
"$expand=Teams($select=TeamSK,TeamName)"
);
}
/**
* (
ProjectSK eq FBED1309-56DB-44DB-9006-24AD73EEE785
and (
AreaSK eq aaf9cd34-350e-45da-8600-a39bbfe14cb8
or AreaSK eq 549aa146-cad9-48ba-86da-09f0bdee4a03
)
) or (
ProjectId eq 6974D8FE-08C8-4123-AD1D-FB830A098DFB
and (
AreaSK eq fa64fee6-434f-4405-94e3-10c1694d5d26
)
)
*/
private static ProjectAreasFilter(input: PortfolioPlanningTeamsInAreaQueryInput): string {
return Object.keys(input)
.map(
projectId =>
`(ProjectSK eq ${projectId} and (${Object.keys(input[projectId])
.map(areaId => `AreaSK eq ${areaId}`)
.join(" or ")}))`
)
.join(" or ");
}
/**
* (
ProjectId eq FBED1309-56DB-44DB-9006-24AD73EEE785
) or (
ProjectId eq 6974D8FE-08C8-4123-AD1D-FB830A098DFB
)
* @param input
*/
private static ProjectsQueryFilter(input: PortfolioPlanningProjectQueryInput): string {
return Object.keys(input.projects)
.map(pid => `(ProjectId eq ${pid})`)
.join(" or ");
}
/**
* (
Project/ProjectId eq FBED1309-56DB-44DB-9006-24AD73EEE785
and (
WorkItemId eq 5250
or WorkItemId eq 5251
)
) or (
Project/ProjectId eq 6974D8FE-08C8-4123-AD1D-FB830A098DFB
and (
WorkItemId eq 5249
)
)
* @param input
*/
private static BuildODataQueryFilter(input: PortfolioPlanningQueryInput): string {
const projectFilters = input.WorkItems.map(wi => {
const wiIdClauses = wi.workItemIds.map(id => `WorkItemId eq ${id}`);
const parts: string[] = [];
parts.push(`Project/ProjectId eq ${wi.projectId}`);
parts.push(`(${wiIdClauses.join(" or ")})`);
return `(${parts.join(" and ")})`;
});
return projectFilters.join(" or ");
}
/**
* (
Project/ProjectId eq FBED1309-56DB-44DB-9006-24AD73EEE785
and WorkItemType eq 'Epic'
) or (
Project/ProjectId eq 6974D8FE-08C8-4123-AD1D-FB830A098DFB
and WorkItemType eq 'Epic'
)
* @param input
*/
private static BuildODataDescendantsQueryFilter(input: PortfolioPlanningQueryInput): string {
const projectFilters = input.WorkItems.map(wi => {
const parts: string[] = [];
parts.push(`Project/ProjectId eq ${wi.projectId}`);
parts.push(`WorkItemType eq '${wi.DescendantsWorkItemTypeFilter}'`);
return `(${parts.join(" and ")})`;
});
return projectFilters.join(" or ");
}
/**
* Descendants(
$apply=
filter(WorkItemType eq 'User Story' or WorkItemType eq 'Task')
/aggregate(
$count as TotalCount,
iif(StateCategory eq 'Completed',1,0) with sum as CompletedCount,
StoryPoints with sum as TotalStoryPoints,
iif(StateCategory eq 'Completed',StoryPoints,0) with sum as CompletedStoryPoints
)
/compute(
(CompletedCount div cast(TotalCount, Edm.Decimal)) as CountProgress,
(CompletedStoryPoints div TotalStoryPoints) as StoryPointsProgress
)
)
* @param input
*/
private static BuildODataDescendantsQuery(
input: PortfolioPlanningQueryInput
): {
queryString: string;
aggregationClauses: WorkItemTypeAggregationClauses;
} {
const aggregationClauses = this.BuildEffortSelectionConditional(input);
const descendantsWorkItemTypeFilters = this.BuildODataDescendantsQueryFilter(input);
const allAggregationClauses = Object.keys(aggregationClauses.allClauses);
// prettier-ignore
return {
queryString:
"Descendants(" +
"$apply=" +
`filter(${descendantsWorkItemTypeFilters})` +
"/aggregate(" +
"$count as TotalCount," +
"iif(StateCategory eq 'Completed',1,0) with sum as CompletedCount," +
`${allAggregationClauses.join(", ")}` +
")" +
")",
aggregationClauses: aggregationClauses
};
}
private static BuildEffortSelectionConditional(input: PortfolioPlanningQueryInput): WorkItemTypeAggregationClauses {
const result: WorkItemTypeAggregationClauses = {
aliasMap: {},
allClauses: {},
allDescendantsWorkItemTypes: {}
};
if (!input) {
return result;
}
let temporaryIdCounter: number = 0;
const colTypeMap: {
[oDataColumnName: string]: { [descendantWorkItemType: string]: number /**alias seed */ };
} = {};
input.WorkItems.forEach(project => {
const descendantWorkItemTypeLowercase = project.DescendantsWorkItemTypeFilter.toLowerCase();
const oDataColumnName = project.EffortODataColumnName;
const projectIdKeyLowercase = project.projectId.toLowerCase();
if (!colTypeMap[oDataColumnName]) {
colTypeMap[oDataColumnName] = {};
}
if (!colTypeMap[oDataColumnName][descendantWorkItemTypeLowercase]) {
temporaryIdCounter++;
colTypeMap[oDataColumnName][descendantWorkItemTypeLowercase] = temporaryIdCounter;
}
const aliasSeed: number = colTypeMap[oDataColumnName][descendantWorkItemTypeLowercase];
const totalAlias = `Total${aliasSeed}`.toLowerCase();
const totalClause =
`iif(WorkItemType eq '${descendantWorkItemTypeLowercase}', ${oDataColumnName}, 0) ` +
`with sum as ${totalAlias}`.toLowerCase();
const completedAlias = `Completed${aliasSeed}`.toLowerCase();
const completedClause =
"iif(" +
" StateCategory eq 'Completed' " +
`and WorkItemType eq '${descendantWorkItemTypeLowercase}', ${oDataColumnName}, 0) ` +
`with sum as ${completedAlias}`.toLowerCase();
// Save column alias used by project to read results.
if (!result.aliasMap[projectIdKeyLowercase]) {
result.aliasMap[projectIdKeyLowercase] = {
totalEffortAlias: totalAlias,
completedEffortAlias: completedAlias
};
}
// Add clauses set.
result.allClauses[totalClause] = "";
result.allClauses[completedClause] = "";
// Keep a set of descendants work item types.
if (!result.allDescendantsWorkItemTypes[descendantWorkItemTypeLowercase]) {
result.allDescendantsWorkItemTypes[
descendantWorkItemTypeLowercase
] = `WorkItemType eq '${descendantWorkItemTypeLowercase}'`;
}
});
return result;
}
public static WorkItemProjectIds(workItemIds: number[]): string {
const workItemIdFilters = workItemIds.map(workItemId => `WorkItemId eq ${workItemId}`);
// prettier-ignore
return "WorkItems" +
"?" +
`$select=WorkItemId,ProjectSK,WorkItemType` +
"&" +
`$filter=${workItemIdFilters.join(" or ")}`;
}
/**
*
$select=WorkItemLinkSK,SourceWorkItemId,TargetWorkItemId,LinkTypeReferenceName,ProjectSK
&
$filter=(
LinkTypeReferenceName eq 'System.LinkTypes.Dependency-Reverse'
and (
SourceWorkItemId eq 175
or SourceWorkItemId eq 176)
)
*
*/
public static WorkItemLinksQueryString(input: WorkItemLinksQueryInput): string {
// prettier-ignore
return "WorkItemLinks" +
"?" +
`$select=${ODataQueryBuilder.WorkItemLinksEntitySelect}` +
"&" +
`$filter=${this.BuildODataWorkItemLinksQueryFilter(input)}`;
}
private static BuildODataWorkItemLinksQueryFilter(input: WorkItemLinksQueryInput): string {
const workItemIdFilters: string[] = [];
Object.keys(input.WorkItemIdsByProject).forEach(projectId => {
const idsFilter = input.WorkItemIdsByProject[projectId].map(id => {
return `${input.WorkItemIdColumn} eq ${id.toString()}`;
});
workItemIdFilters.push(`(ProjectSK eq ${projectId} and (${idsFilter.join(" or ")}))`);
});
// prettier-ignore
return "( " +
`LinkTypeReferenceName eq '${input.RefName}' ` +
`and (${workItemIdFilters.join(" or ")}) ` +
")";
}
}
export class DependencyQuery {
public static async runDependencyQuery(
queryInput: PortfolioPlanningDependencyQueryInput
): Promise<PortfolioPlanningDependencyQueryResult> {
try {
const dataService = PortfolioPlanningDataService.getInstance();
const workItemLinksQueryResults = await this.GetWorkItemLinks(queryInput);
if (!workItemLinksQueryResults || workItemLinksQueryResults.length === 0) {
return {
byProject: {},
targetsProjectConfiguration: {},
exceptionMessage: null
};
}
const workItemProjectIds = await this.GetWorkItemProjectIds(workItemLinksQueryResults);
const targetLinksProjectConfiguration = await this.GetProjectConfigurations(workItemProjectIds);
const { linksResultsIndexed, workItemRollUpQueryInput } = this.BuildPortfolioItemsQuery(
workItemLinksQueryResults,
workItemProjectIds,
targetLinksProjectConfiguration
);
if (!linksResultsIndexed || Object.keys(linksResultsIndexed).length === 0) {
return {
byProject: {},
targetsProjectConfiguration: {},
exceptionMessage: null
};
}
const dependenciesRollUpQueryResult = await dataService.runPortfolioItemsQuery(workItemRollUpQueryInput);
const results = DependencyQuery.MatchWorkItemLinksAndRollUpValues(
queryInput,
dependenciesRollUpQueryResult,
linksResultsIndexed,
targetLinksProjectConfiguration
);
// Sort items by target date before returning
Object.keys(results.byProject).forEach(projectIdKey => {
results.byProject[projectIdKey].Predecessors.sort((a, b) => (a.TargetDate > b.TargetDate ? 1 : -1));
results.byProject[projectIdKey].Successors.sort((a, b) => (a.TargetDate > b.TargetDate ? 1 : -1));
});
return results;
} catch (error) {
console.log(error);
const exceptionMessage: string = (error as Error).message;
return {
exceptionMessage,
byProject: {},
targetsProjectConfiguration: {}
};
}
}
private static async GetProjectConfigurations(
workItemProjectIdsQueryResult: WorkItemProjectIdsQueryResult
): Promise<{ [projectIdKey: string]: IProjectConfiguration }> {
if (
workItemProjectIdsQueryResult.exceptionMessage &&
workItemProjectIdsQueryResult.exceptionMessage.length > 0
) {
throw new Error(
`runDependencyQuery: Exception running work item project ids query. Inner exception: ${
workItemProjectIdsQueryResult.exceptionMessage
}`
);
}
if (!workItemProjectIdsQueryResult.Results || workItemProjectIdsQueryResult.Results.length === 0) {
return {};
}
const result: { [projectIdKey: string]: IProjectConfiguration } = {};
const allPromises: Promise<IProjectConfiguration>[] = [];
const dataService = ProjectConfigurationDataService.getInstance();
workItemProjectIdsQueryResult.Results.forEach(workItem => {
const projectIdKey = workItem.ProjectSK.toLowerCase();
if (!result[projectIdKey]) {
// Will query config later, this is just building the set of project ids.
result[projectIdKey] = null;
allPromises.push(dataService.getProjectConfiguration(projectIdKey));
}
});
const projectConfigurations = await Promise.all(allPromises);
projectConfigurations.forEach(projectConfig => {
const projectIdKey = projectConfig.id.toLowerCase();
result[projectIdKey] = projectConfig;
});
return result;
}
private static MatchWorkItemLinksAndRollUpValues(
queryInput: PortfolioPlanningDependencyQueryInput,
dependenciesRollUpQueryResult: PortfolioPlanningQueryResult,
linksResultsIndexed: { [projectKey: string]: { [linkTypeKey: string]: number[] } },
targetLinksProjectConfiguration: { [projectId: string]: IProjectConfiguration }
) {
if (
dependenciesRollUpQueryResult.exceptionMessage &&
dependenciesRollUpQueryResult.exceptionMessage.length > 0
) {
throw new Error(
`runDependencyQuery: Exception running portfolio items query for dependencies. Inner exception: ${
dependenciesRollUpQueryResult.exceptionMessage
}`
);
}
const successorKey = LinkTypeReferenceName.Successor.toLowerCase();
const predecessorKey = LinkTypeReferenceName.Predecessor.toLowerCase();
const rollupsIndexed: {
[projectKey: string]: {
[workItemId: number]: PortfolioPlanningQueryResultItem;
};
} = {};
const result: PortfolioPlanningDependencyQueryResult = {
byProject: {},
targetsProjectConfiguration: targetLinksProjectConfiguration,
exceptionMessage: null
};
// Indexing portfolio items results query by project id and work item id.
dependenciesRollUpQueryResult.items.forEach(resultItem => {
const projectIdKey = resultItem.ProjectId.toLowerCase();
const workItemId = resultItem.WorkItemId;
if (!rollupsIndexed[projectIdKey]) {
rollupsIndexed[projectIdKey] = {};
}
rollupsIndexed[projectIdKey][workItemId] = resultItem;
});
// Walk through all work item links found, and find the corresponding
// roll-up value from the portfolio items query results.
Object.keys(linksResultsIndexed).forEach(projectIdKey => {
Object.keys(linksResultsIndexed[projectIdKey]).forEach(linkTypeKey => {
linksResultsIndexed[projectIdKey][linkTypeKey].forEach(workItemId => {
if (!result.byProject[projectIdKey]) {
result.byProject[projectIdKey] = {
Predecessors: [],
Successors: []
};
}
const rollUpValues = rollupsIndexed[projectIdKey]![workItemId];
if (!rollUpValues) {
// Shouldn't happen. Portfolio items query result should contain an entry for every
// work item link found.
const props = {
["WorkItemId"]: workItemId,
["ProjectId"]: projectIdKey
};
const actionName =
"PortfolioPlanningDataService/runDependencyQuery/MissingWorkItemRollUpValues";
console.log(`${actionName}. ${JSON.stringify(props, null, " ")}`);
PortfolioTelemetry.getInstance().TrackAction(actionName, props);
} else {
if (linkTypeKey === predecessorKey) {
result.byProject[projectIdKey].Predecessors.push(rollUpValues);
} else if (linkTypeKey === successorKey) {
result.byProject[projectIdKey].Successors.push(rollUpValues);
} else {
// Shouldn't happen. We are only querying for these two types of links.
const props = {
["WorkItemId"]: workItemId,
["ProjectId"]: projectIdKey,
["LinkType"]: linkTypeKey
};
const actionName = "PortfolioPlanningDataService/runDependencyQuery/UnknownLinkType";
console.log(`${actionName}. ${JSON.stringify(props, null, " ")}`);
PortfolioTelemetry.getInstance().TrackAction(actionName, props);
}
}
});
});
});
return result;
}
private static async GetWorkItemLinks(
queryInput: PortfolioPlanningDependencyQueryInput
): Promise<WorkItemLinksQueryResult[]> {
const dataService = PortfolioPlanningDataService.getInstance();
const workItemLinkQueries: Promise<WorkItemLinksQueryResult>[] = [];
workItemLinkQueries.push(
dataService.runWorkItemLinksQuery({
RefName: LinkTypeReferenceName.Predecessor,
WorkItemIdColumn: WorkItemLinkIdType.Source,
WorkItemIdsByProject: queryInput.byProject
})
);
workItemLinkQueries.push(
dataService.runWorkItemLinksQuery({
RefName: LinkTypeReferenceName.Successor,
WorkItemIdColumn: WorkItemLinkIdType.Source,
WorkItemIdsByProject: queryInput.byProject
})
);
return await Promise.all(workItemLinkQueries);
}
private static async GetWorkItemProjectIds(
linkResults: WorkItemLinksQueryResult[]
): Promise<WorkItemProjectIdsQueryResult> {
const workItemIds: { [workItemId: number]: boolean } = {};
linkResults.forEach(linkQueryResult => {
if (linkQueryResult.exceptionMessage && linkQueryResult.exceptionMessage.length > 0) {
// Throw at first exception.
throw new Error(
`runDependencyQuery: Exception running work item links query. Inner exception: ${
linkQueryResult.exceptionMessage
}`
);
}
linkQueryResult.Links.forEach(linkFound => {
workItemIds[linkFound.TargetWorkItemId] = true;
});
});
const workItemIdsSet = Object.keys(workItemIds).map(idStr => Number(idStr));
return PortfolioPlanningDataService.getInstance().getWorkItemProjectIds(workItemIdsSet);
}
private static BuildPortfolioItemsQuery(
linkResults: WorkItemLinksQueryResult[],
workItemProjectIdsQueryResult: WorkItemProjectIdsQueryResult,
targetLinksProjectConfiguration: { [projectId: string]: IProjectConfiguration }
) {
if (
workItemProjectIdsQueryResult.exceptionMessage &&
workItemProjectIdsQueryResult.exceptionMessage.length > 0
) {
throw new Error(
`runDependencyQuery: Exception running work item project ids query. Inner exception: ${
workItemProjectIdsQueryResult.exceptionMessage
}`
);
}
const linksResultsIndexed: { [projectKey: string]: { [linkTypeKey: string]: number[] } } = {};
const targetWorkItemIdsByProject: { [projectKey: string]: { [workItemId: number]: boolean } } = {};
const linkTargetWorkItemsProjectIds: { [workItemId: number]: string } = {};
const workItemProjectIds = workItemProjectIdsQueryResult.Results || [];
// Index linked work item's project id by work item id.
workItemProjectIds.forEach(targetItem => {
linkTargetWorkItemsProjectIds[targetItem.WorkItemId] = targetItem.ProjectSK.toLowerCase();
});
linkResults.forEach(linkQueryResult => {
if (linkQueryResult.exceptionMessage && linkQueryResult.exceptionMessage.length > 0) {
// Throw at first exception.
throw new Error(
`runDependencyQuery: Exception running work item links query. Inner exception: ${
linkQueryResult.exceptionMessage
}`
);
}
linkQueryResult.Links.forEach(linkFound => {
const linkTypeKey = linkFound.LinkTypeReferenceName.toLowerCase();
const projectIdKey = linkTargetWorkItemsProjectIds[linkFound.TargetWorkItemId]!.toLowerCase();
if (!projectIdKey) {
// Shouldn't happen. We should have project id information for all work item ids
// found as target for all links queried.
const props = {
["TargetWorkItemId"]: linkFound.TargetWorkItemId,
["linkTypeKey"]: linkTypeKey
};
const actionName =
"PortfolioPlanningDataService/runDependencyQuery/MissingProjectIdForLinkedWorkItemId";
console.log(`${actionName}. ${JSON.stringify(props, null, " ")}`);
PortfolioTelemetry.getInstance().TrackAction(actionName, props);
} else {
if (!linksResultsIndexed[projectIdKey]) {
linksResultsIndexed[projectIdKey] = {};
}
if (!linksResultsIndexed[projectIdKey][linkTypeKey]) {
linksResultsIndexed[projectIdKey][linkTypeKey] = [];
}
if (!targetWorkItemIdsByProject[projectIdKey]) {
targetWorkItemIdsByProject[projectIdKey] = {};
}
linksResultsIndexed[projectIdKey][linkTypeKey].push(linkFound.TargetWorkItemId);
targetWorkItemIdsByProject[projectIdKey][linkFound.TargetWorkItemId] = true;
}
});
});
const workItemRollUpQueryInput: PortfolioPlanningQueryInput = { WorkItems: [] };
Object.keys(targetWorkItemIdsByProject).forEach(projectIdKey => {
const projectConfig = targetLinksProjectConfiguration[projectIdKey];
workItemRollUpQueryInput.WorkItems.push({
projectId: projectIdKey,
workItemIds: Object.keys(targetWorkItemIdsByProject[projectIdKey]).map(workItemIdStr =>
Number(workItemIdStr)
),
DescendantsWorkItemTypeFilter: projectConfig.defaultRequirementWorkItemType,
EffortODataColumnName: projectConfig.effortODataColumnName,
EffortWorkItemFieldRefName: projectConfig.effortWorkItemFieldRefName
});
});
return { linksResultsIndexed, workItemRollUpQueryInput };
}
} | the_stack |
import { BigNumber } from "bignumber.js";
import type { DatasetTest } from "../../types";
import {
InvalidAddress,
InvalidAddressBecauseDestinationIsAlsoSource,
NotEnoughBalance,
AmountRequired,
} from "@ledgerhq/errors";
import { ClaimRewardsFeesWarning } from "../../errors";
import invariant from "invariant";
import type { Transaction } from "./types";
import transactionTransformer from "./transaction";
// eslint-disable-next-line no-unused-vars
const cosmos = {
FIXME_ignoreAccountFields: [
"cosmosResources.unbondingBalance", // They move once all unbonding are done
"cosmosResources.pendingRewardsBalance", // They are always movings
"cosmosResources.delegations", // They are always movings because of pending Rewards
"cosmosResources.redelegations", // will change ince a redelegation it's done
"cosmosResources.unbondings", // will change once a unbonding it's done
"spendableBalance", // will change with the rewards that automatically up
],
scanAccounts: [
{
name: "cosmos seed 1",
apdus: `
=> 550400001b06636f736d6f732c00008076000080000000800000000000000000
<= 0388459b2653519948b12492f1a0b464720110c147a8155d23d423a5cc3c21d89a636f736d6f73316738343933346a70753376356465357971756b6b6b68786d63767377337532616a787670646c9000
=> 550400001b06636f736d6f732c00008076000080000000800000000000000000
<= 0388459b2653519948b12492f1a0b464720110c147a8155d23d423a5cc3c21d89a636f736d6f73316738343933346a70753376356465357971756b6b6b68786d63767377337532616a787670646c9000
=> 550400001b06636f736d6f732c00008076000080010000800000000000000000
<= 02624ac83690d5ef627927104767d679aef73d3d3c9544abe4206b1d0c463c94ff636f736d6f7331303875793571396a743539677775677135797264686b7a6364396a7279736c6d706373746b359000
=> 550400001b06636f736d6f732c00008076000080020000800000000000000000
<= 038ff98278402aa3e46ccfd020561dc9724ab63d7179ca507c8154b5257c7d5200636f736d6f733163676336393661793270673664346763656a656b3279386c6136366a376535793363376b79779000
=> 550400001b06636f736d6f732c00008076000080030000800000000000000000
<= 02ecca2a8c647b50bcea2cb4667bb8b2c5f5b2b8439d51c842bc9fd20c4185a95c636f736d6f73313474673476736430713734356678687a6e333239706b78306b727174737a6378797a6c356b759000
`,
},
],
accounts: [
{
FIXME_tests: ["balance is sum of ops"],
raw: {
id: "libcore:1:cosmos:cosmospub1addwnpepqwyytxex2dgejj93yjf0rg95v3eqzyxpg75p2hfr6s36tnpuy8vf5p6kez4:",
seedIdentifier:
"0388459b2653519948b12492f1a0b464720110c147a8155d23d423a5cc3c21d89a",
xpub: "cosmospub1addwnpepqwyytxex2dgejj93yjf0rg95v3eqzyxpg75p2hfr6s36tnpuy8vf5p6kez4",
derivationMode: "",
index: 0,
freshAddress: "cosmos1g84934jpu3v5de5yqukkkhxmcvsw3u2ajxvpdl",
freshAddressPath: "44'/118'/0'/0/0",
freshAddresses: [
{
address: "cosmos1g84934jpu3v5de5yqukkkhxmcvsw3u2ajxvpdl",
derivationPath: "44'/118'/0'/0/0",
},
],
name: "Cosmos 1",
balance: "2180673",
spendableBalance: "2180673",
blockHeight: 1615299,
currencyId: "cosmos",
unit: {
name: "Muon",
code: "MUON",
magnitude: 6,
},
unitMagnitude: 6,
operationsCount: 85,
operations: [],
pendingOperations: [],
lastSyncDate: "",
},
transactions: [
{
name: "Same as Recipient",
transaction: (t) => ({
...t,
amount: new BigNumber(100),
recipient: "cosmos1g84934jpu3v5de5yqukkkhxmcvsw3u2ajxvpdl",
}),
expectedStatus: {
errors: {
recipient: new InvalidAddressBecauseDestinationIsAlsoSource(),
},
warnings: {},
},
},
{
name: "Invalid Address",
transaction: (t) => ({
...t,
amount: new BigNumber(100),
recipient: "dsadasdasdasdas",
}),
expectedStatus: {
errors: {
recipient: new InvalidAddress(),
},
warnings: {},
},
},
{
name: "send max",
transaction: transactionTransformer.fromTransactionRaw({
amount: "0",
recipient: "cosmos108uy5q9jt59gwugq5yrdhkzcd9jryslmpcstk5",
useAllAmount: true,
family: "cosmos",
networkInfo: null,
validators: [],
cosmosSourceValidator: null,
fees: null,
gas: null,
memo: null,
mode: "send",
}),
expectedStatus: (account) => {
const { cosmosResources } = account;
invariant(cosmosResources, "Should exist because it's cosmos");
const totalSpent = account.balance.minus(
cosmosResources.unbondingBalance.plus(
cosmosResources.delegatedBalance
)
);
return {
errors: {},
warnings: {},
totalSpent,
};
},
},
{
name: "send with memo",
transaction: transactionTransformer.fromTransactionRaw({
amount: "0",
recipient: "cosmos108uy5q9jt59gwugq5yrdhkzcd9jryslmpcstk5",
useAllAmount: true,
family: "cosmos",
networkInfo: null,
validators: [],
cosmosSourceValidator: null,
fees: null,
gas: null,
memo: "test",
mode: "send",
}),
expectedStatus: (account, t) => {
const { cosmosResources } = account;
invariant(cosmosResources, "Should exist because it's cosmos");
invariant(t.memo === "test", "Should have a memo");
const totalSpent = account.balance.minus(
cosmosResources.unbondingBalance.plus(
cosmosResources.delegatedBalance
)
);
return {
errors: {},
warnings: {},
totalSpent,
};
},
},
{
name: "Not Enough balance",
transaction: (t) => ({
...t,
amount: new BigNumber("99999999999999999"),
recipient: "cosmos108uy5q9jt59gwugq5yrdhkzcd9jryslmpcstk5",
}),
expectedStatus: {
errors: {
amount: new NotEnoughBalance(),
},
warnings: {},
},
},
{
name: "Redelegation - success",
transaction: (t) => ({
...t,
amount: new BigNumber(100),
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(100),
},
],
cosmosSourceValidator:
"cosmosvaloper1sd4tl9aljmmezzudugs7zlaya7pg2895ws8tfs",
mode: "redelegate",
}),
expectedStatus: (a, t) => {
invariant(t.memo === "Ledger Live", "Should have a memo");
return {
errors: {},
warnings: {},
};
},
},
{
name: "redelegation - AmountRequired",
transaction: (t) => ({
...t,
mode: "redelegate",
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(0),
},
],
cosmosSourceValidator:
"cosmosvaloper1sd4tl9aljmmezzudugs7zlaya7pg2895ws8tfs",
}),
expectedStatus: {
errors: {
amount: new AmountRequired(),
},
warnings: {},
},
},
{
name: "redelegation - Source is Destination",
transaction: (t) => ({
...t,
mode: "redelegate",
validators: [
{
address: "cosmosvaloper1sd4tl9aljmmezzudugs7zlaya7pg2895ws8tfs",
amount: new BigNumber(100),
},
],
cosmosSourceValidator:
"cosmosvaloper1sd4tl9aljmmezzudugs7zlaya7pg2895ws8tfs",
}),
expectedStatus: {
errors: {
redelegation: new InvalidAddressBecauseDestinationIsAlsoSource(),
},
warnings: {},
},
},
{
name: "Unbonding - success",
transaction: (t) => ({
...t,
mode: "undelegate",
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(100),
},
],
}),
expectedStatus: (a, t) => {
invariant(t.memo === "Ledger Live", "Should have a memo");
return {
errors: {},
warnings: {},
};
},
},
{
name: "Unbonding - AmountRequired",
transaction: (t) => ({
...t,
mode: "undelegate",
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(0),
},
],
}),
expectedStatus: {
errors: {
amount: new AmountRequired(),
},
warnings: {},
},
},
{
name: "Delegate - success",
transaction: (t) => ({
...t,
mode: "delegate",
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(100),
},
],
}),
expectedStatus: (a, t) => {
invariant(t.memo === "Ledger Live", "Should have a memo");
return {
errors: {},
warnings: {},
};
},
},
{
name: "Delegate - not a valid",
transaction: (t) => ({
...t,
mode: "delegate",
validators: [
{
address: "cosmos108uy5q9jt59gwugq5yrdhkzcd9jryslmpcstk5",
amount: new BigNumber(100),
},
],
}),
expectedStatus: {
errors: {
recipient: new InvalidAddress(),
},
warnings: {},
},
},
{
name: "ClaimReward - success",
transaction: (t) => ({
...t,
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(0),
},
],
mode: "claimReward",
}),
expectedStatus: (a, t) => {
invariant(t.memo === "Ledger Live", "Should have a memo");
return {
errors: {},
warnings: {},
};
},
},
{
name: "ClaimReward - Warning",
transaction: (t) => ({
...t,
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(0),
},
],
fees: new BigNumber(9999999999999999),
mode: "claimReward",
}),
expectedStatus: {
errors: {},
warnings: {
claimReward: new ClaimRewardsFeesWarning(),
},
},
},
{
name: "ClaimReward - not a cosmosvaloper",
transaction: (t) => ({
...t,
validators: [
{
address: "cosmos108uy5q9jt59gwugq5yrdhkzcd9jryslmpcstk5",
amount: new BigNumber(0),
},
],
mode: "claimReward",
}),
expectedStatus: {
errors: {
recipient: new InvalidAddress(),
},
warnings: {},
},
},
{
name: "claimRewardCompound - success",
transaction: (t) => ({
...t,
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(100),
},
],
mode: "claimRewardCompound",
}),
expectedStatus: (a, t) => {
invariant(t.memo === "Ledger Live", "Should have a memo");
return {
errors: {},
warnings: {},
};
},
},
{
name: "ClaimRewardCompound - Warning",
transaction: (t) => ({
...t,
validators: [
{
address: "cosmosvaloper1grgelyng2v6v3t8z87wu3sxgt9m5s03xfytvz7",
amount: new BigNumber(100),
},
],
fees: new BigNumber(99999999999999999999),
mode: "claimRewardCompound",
}),
expectedStatus: {
errors: {},
warnings: {
claimReward: new ClaimRewardsFeesWarning(),
},
},
},
],
},
{
FIXME_tests: ["balance is sum of ops"],
raw: {
id: "libcore:1:cosmos:cosmospub1addwnpepqd3nvwwx39pqqvw88sg409675u6wyt4wtzqyt2t0e9y4629t50cdzftxnvz:",
seedIdentifier:
"cosmospub1addwnpepqd3nvwwx39pqqvw88sg409675u6wyt4wtzqyt2t0e9y4629t50cdzftxnvz",
name: "Cosmos Static Account",
starred: true,
derivationMode: "",
index: 0,
freshAddress: "cosmos10l6h3qw05u7qduqgafj8wlrx3fjhr8523sm0c3",
freshAddressPath: "44'/118'/0'/0/0",
freshAddresses: [],
blockHeight: 2220318,
creationDate: "2020-04-01T13:51:08.000Z",
operationsCount: 0,
operations: [],
pendingOperations: [],
currencyId: "cosmos",
unitMagnitude: 6,
lastSyncDate: "2020-06-11T07:44:10.266Z",
balance: "1000000",
spendableBalance: "0",
balanceHistory: {},
xpub: "cosmospub1addwnpepqd3nvwwx39pqqvw88sg409675u6wyt4wtzqyt2t0e9y4629t50cdzftxnvz",
cosmosResources: {
delegations: [],
redelegations: [],
unbondings: [],
delegatedBalance: "0",
pendingRewardsBalance: "0",
unbondingBalance: "1000000",
withdrawAddress: "",
},
},
},
],
};
const currencies = {
cosmos,
};
const dataset: DatasetTest<Transaction> = {
implementations: ["libcore"],
// FIXEM: bad any
currencies: currencies as any,
};
export default dataset; | the_stack |
import * as React from 'react';
export class Accordion extends React.Component <any> {
constructor(e: any);
accordionClasses(): any;
changePanels(): void;
componentDidUpdate(e: any): any;
getPanel(e: any): any;
getPanelIndex(e: any): any;
getPanels(e: any): any;
getSelectedIndex(): any;
getSelectedPanel(): any;
getSelectedPanels(): any;
handlePanelAdd(e: any): void;
handlePanelRemove(e: any): void;
handlePanelSelect(e: any): void;
handlePanelUnselect(e: any): void;
initPanels(): any;
initSelectedPanel(): any;
render(): any;
select(e: any): void;
unselect(e: any): void;
}
export class AccordionPanel extends React.Component <any> {
constructor(e: any);
bodyClasses(): any;
clickCollapsibleTool(e: any): void;
clickPanelHeader(e: any): void;
componentDidMount(): void;
componentWillUnmount(): void;
full(): any;
headerClasses(): any;
panelClasses(): any;
select(): any;
selectedState(): any;
setLast(e: any): void;
unselect(): void;
}
export class ButtonGroup extends React.Component <any> {
constructor(e: any);
render(): any;
static defaultProps: {
selectionMode: string; };
}
export class Calendar extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): any;
getHeaderData(): any;
getWeeks(): any;
handleDayClick(e: any): void;
handleDayMouseEnter(e: any): void;
handleDayMouseLeave(): void;
handleMenuClick(): void;
handleMonthClick(e: any): any;
handleMonthMouseEnter(e: any): void;
handleMonthMouseLeave(): void;
handleMonthNext(): void;
handleMonthPrev(): void;
handleYearChange(e: any): any;
handleYearNext(): void;
handleYearPrev(): void;
highlightDate(e: any): void;
isDiff(e: any, t: any): any;
isStateEmpty(e: any): any;
isValid(e: any): any;
moveTo(e: any): any;
navDate(e: any): void;
refresh(): void;
render(): any;
selectDate(...args: any[]): void;
toArray(e: any): any;
toDate(e: any): any;
}
export class CheckBox extends React.Component <any> {
constructor(e: any);
checkClasses(): any;
componentDidMount(): void;
componentDidUpdate(e: any): void;
handleChange(): void;
handleClick(e: any): void;
initChecked(e: any, ...args: any[]): void;
render(): any;
updateValues(): void;
wrapperClasses(): any;
}
export class ComboBox extends React.Component <any> {
constructor(e: any);
blur(): void;
clearSelections(): void;
closePanel(): void;
componentDidMount(): void;
componentDidUpdate(e: any): void;
doFilter(e: any): any;
findItem(e: any, ...args: any[]): any;
fixValue(): any;
focus(): void;
handleKeyDown(e: any): any;
handlePageChange(e: any): void;
handleRowClick(e: any): any;
handleSelectionChange(e: any): any;
initValue(e: any): any;
openPanel(): void;
renderInput(): any;
renderItem(e: any): any;
renderPanel(): any;
setData(e: any): void;
setValue(e: any): void;
text(): any;
updateSelection(e: any): void;
updateText(e: any): void;
}
export class ComboGrid extends React.Component <any> {
constructor(e: any);
blur(): void;
closePanel(): void;
componentDidMount(): void;
doFilter(): void;
findRow(e: any): any;
fixValue(): any;
handleSelectionChange(e: any): any;
initValue(e: any): any;
openPanel(): void;
renderContent(): any;
setValue(e: any): void;
updateText(): void;
}
export class ComboTree extends React.Component <any> {
constructor(e: any);
blur(): void;
componentDidMount(): void;
doFilter(e: any): void;
fixValue(): any;
handleCheckChange(e: any): any;
handleSelectionChange(e: any): void;
initTreeValue(e: any): any;
initValue(e: any): any;
isDiff(e: any, t: any): any;
openPanel(): any;
renderContent(): any;
setValue(e: any): void;
updateText(): void;
}
export class DataGrid extends React.Component <any> {
constructor(e: any);
collapseGroup(e: any): void;
collapseRow(e: any): any;
expandGroup(e: any): void;
expandRow(e: any): void;
frozenRows(): any;
getAbsoluteIndex(e: any): any;
getExpandedIndex(e: any): any;
getGroup(e: any, t: any): any;
handleBodyScroll(e: any): void;
isGroupRow(e: any): any;
isGrouped(e: any): any;
isRowExpanded(e: any): any;
makeGroup(e: any): any;
makeGroupedRows(): any;
setGroupData(): void;
sortData(): any;
toggleGroup(e: any): void;
toggleRow(e: any): void;
updateFrozenView(e: any, t: any): void;
viewComponent(): any;
}
export class DataList extends React.Component <any> {
constructor(...args: any[]);
container(): any;
getItemClass(e: any): any;
getRowIndex(e: any): any;
handleMouseEnter(e: any): any;
handleMouseLeave(): void;
handleRowClick(e: any): any;
handleScroll(e: any): void;
highlightFirstRow(): void;
innerClasses(): any;
innerStyle(): any;
navRow(e: any): void;
render(): any;
renderList(): any;
renderLoading(): any;
renderPagination(e: any): any;
renderVirtualList(): any;
scrollToSelectedRow(): void;
scrollTop(e: any): any;
setData(e: any): void;
virtualItemStyle(): any;
}
export class DateBox extends React.Component <any> {
constructor(...args: any[]);
blur(): void;
componentDidMount(): void;
defaultFormatter(e: any): any;
defaultParser(e: any): any;
doFilter(e: any): void;
fixValue(): void;
handleCloseClick(e: any): void;
handleKeyDown(e: any): any;
handleSelectionChange(e: any): void;
handleTodayClick(e: any): void;
isDiff(e: any, t: any): any;
renderInput(): any;
renderPanel(): any;
setValue(e: any): void;
text(): any;
}
export class Dialog extends React.Component <any> {
constructor(e: any);
bodyClasses(): any;
center(): void;
clickCloseTool(e: any): void;
close(): void;
closeMask(): void;
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
displaying(): void;
footerClasses(): any;
handleDragEnd(e: any): void;
handleResizeStop(e: any): void;
hcenter(): void;
headerClasses(): any;
initDialog(): void;
moveToTop(): void;
open(): void;
openMask(): void;
panelClasses(): any;
panelStyles(): any;
render(): any;
vcenter(): void;
static zIndex: number;
}
export class Draggable {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
hideProxy(): void;
render(): any;
renderProxy(): any;
showProxy(): any;
}
export class DraggableProxy extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
handleTransitionEnd(): void;
proxyClasses(): any;
proxyStyles(): any;
render(): any;
}
export class Droppable extends React.Component <any> {
constructor(...args: any[]);
componentDidMount(): void;
componentDidUpdate(): void;
componentWillUnmount(): void;
render(): any;
}
export class FieldBase extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
getFieldName(): any;
render(): any;
static defaultProps: {
invalid: boolean;
validateOnBlur: boolean;
validateOnChange: boolean;
validateOnCreate: boolean; };
}
export class FileButton extends React.Component <any> {
constructor(...args: any[]);
clear(): void;
componentDidMount(): void;
getFiles(): any;
handleFileSelect(): void;
renderOthers(): any;
upload(): void;
static fileId: number;
}
export class Form extends React.Component <any> {
constructor(...args: any[]);
getChildContext(): any;
handleSubmit(e: any): void;
render(): any;
}
export class FormField extends React.Component <any> {
constructor(e: any);
render(): any;
renderError(e: any): any;
renderField(e: any): any;
renderInput(e: any, t: any): any;
renderLabel(e: any): any;
static idIndex: number;
}
export class GridBase extends React.Component <any> {
constructor(e: any);
addFilterRule(e: any): void;
addSort(e: any): any;
allColumns(): any;
beginEdit(e: any, ...args: any[]): void;
cancelEdit(): void;
changeColumns(): void;
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
endEdit(): any;
findColumn(e: any): any;
footerRows(): any;
getColumnCount(e: any): any;
getColumnIndex(e: any): any;
getColumnLayout(e: any): any;
handleBodyScroll(e: any): void;
initColumnSort(): void;
initColumns(): any;
initFilterRules(): void;
initHeaderHeight(): void;
isEditing(e: any, ...args: any[]): any;
leftFrozenWidth(): any;
moveColumn(e: any, t: any, n: any): any;
onColumnAdd(e: any): void;
onColumnGroupAdd(e: any): void;
onColumnGroupRemove(e: any): void;
onColumnRemove(e: any): void;
render(): any;
renderColumns(): any;
renderLoading(): any;
renderPagination(e: any): any;
renderSplitHelper(): any;
renderToolbar(): any;
renderView(e: any): any;
resizeColumn(e: any, t: any): void;
rightFrozenWidth(): any;
scrollTo(e: any): void;
scrollTop(e: any): any;
viewComponent(): any;
}
export class GridColumn extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
doFilter(): void;
render(): any;
updateFilterRule(): void;
static defaultProps: {
colspan: number;
defaultFilterOperator: string;
editable: boolean;
expander: boolean;
filterOperators: any[];
filterable: boolean;
frozen: boolean;
order: string;
rowspan: number;
sortable: boolean; };
}
export class GridColumnGroup extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentWillUnmount(): void;
onRowAdd(e: any): void;
onRowRemove(e: any): void;
render(): any;
static defaultProps: {
align: string;
frozen: boolean; };
}
export class GridHeaderRow extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentWillUnmount(): void;
onColumnAdd(e: any): void;
onColumnRemove(e: any): void;
render(): any;
}
export class InputBase extends React.Component <any> {
constructor(e: any);
addonClasses(): any;
addonIconClasses(): any;
baseClasses(): any;
blur(): void;
componentDidUpdate(e: any): void;
focus(): void;
getSelectionRange(): any;
getSelectionStart(): any;
handleInputChange(e: any): void;
inputClasses(): any;
isDiff(e: any, t: any): any;
render(): any;
renderAddon(e: any): any;
renderInput(): any;
renderOthers(): any;
setSelectionRange(e: any, t: any): void;
setValue(e: any): void;
text(): any;
}
export class Label extends React.Component <any> {
constructor(...args: any[]);
render(): any;
static defaultProps: {
align: string; };
}
export class Layout extends React.Component <any> {
constructor(e: any);
changePanels(): void;
getPaddingValue(e: any): any;
getPanel(e: any): any;
handleClick(e: any): any;
handlePanelAdd(e: any): void;
handlePanelRemove(e: any): void;
handlePanelResizeStart(e: any, t: any): void;
handlePanelResizeStop(e: any, t: any): void;
handlePanelResizing(e: any, t: any): void;
render(): any;
renderCollapsedPanel(e: any): any;
renderConsumer(): any;
renderLayout(): any;
updatePaddings(): void;
}
export class LayoutPanel extends React.Component <any> {
constructor(e: any);
clickCollapsibleTool(e: any): void;
collapse(): void;
collapsibleClasses(): any;
componentDidMount(): void;
componentWillUnmount(): void;
expand(): void;
fixStyle(): void;
handleResizeStart(e: any): void;
handleResizeStop(e: any): void;
handleResizing(e: any): void;
handleSlideEnd(): void;
panelClasses(): any;
panelStyles(): any;
render(): any;
}
export class LinkButton extends React.Component <any> {
constructor(e: any);
blur(): void;
btnIconCls(): any;
btnLeftCls(): any;
btnTextCls(): any;
componentDidUpdate(e: any): void;
focus(): void;
handleClick(e: any): any;
innerCls(): any;
isDisabled(): any;
isEmpty(): any;
render(): any;
renderButton(): any;
renderInners(): any;
renderOthers(): any;
text(): any;
}
export class LocaleBase {
constructor(...args: any[]);
t(e: any, ...args: any[]): any;
}
export class LocaleProvider extends React.Component <any> {
constructor(e: any, ...args: any[]);
componentDidUpdate(e: any): void;
getChildContext(): any;
render(): any;
}
export class MaskedBox extends React.Component <any> {
constructor(...args: any[]);
componentDidMount(): void;
deleteChar(e: any): void;
formatter(e: any): any;
getInputOffset(e: any): any;
handleKeyDown(e: any): void;
insertChar(e: any): void;
parser(e: any): any;
renderInput(): any;
seekNext(e: any): any;
seekPrev(e: any): any;
}
export class Menu extends React.Component <any> {
constructor(e: any);
alignContextMenu(): void;
alignTo(e: any, ...args: any[]): void;
componentDidMount(): void;
componentWillUnmount(): void;
containerClasses(): any;
containerStyle(): any;
delayHide(): void;
handleDocumentClick(e: any): void;
handleItemClick(e: any): void;
handleMouseOut(): void;
handleMouseOver(): void;
hide(): void;
render(): any;
show(e: any, n: any): any;
showAt(e: any, ...args: any[]): any;
showContextMenu(e: any, t: any): any;
static zIndex: number;
}
export class MenuButton extends React.Component <any> {
constructor(e: any);
handleClick(e: any): void;
handleItemClick(e: any): void;
handleMenuHide(): void;
handleMenuShow(): void;
handleMouseEnter(): void;
handleMouseLeave(): void;
innerCls(): any;
render(): any;
renderInners(): any;
renderMenu(): any;
showMenu(): void;
}
export class MenuItem extends React.Component <any> {
constructor(e: any);
componentDidUpdate(e: any): void;
handleItemClick(e: any): void;
handleMenuAdd(e: any): void;
handleMenuRemove(): void;
handleMouseEnter(): void;
handleMouseLeave(): void;
itemClasses(): any;
render(): any;
static defaultProps: {
disabled: boolean; };
}
export class MenuSep extends React.Component <any> {
constructor(...args: any[]);
render(): any;
}
export class Messager extends React.Component <any> {
constructor(e: any);
alert(e: any): void;
close(e: any): void;
confirm(e: any): void;
openDialog(e: any, ...args: any[]): void;
prompt(e: any): void;
render(): any;
static defaultProps: {
buttons: any[];
defaultCancel: string;
defaultOk: string; };
}
export class NumberBox extends React.Component <any> {
constructor(...args: any[]);
blur(): void;
componentDidMount(): void;
componentDidUpdate(e: any): void;
doSpinDown(): void;
doSpinUp(): void;
filter(e: any): any;
formatter(e: any): any;
handleInputChange(e: any): void;
handleKeyPress(e: any): void;
parser(e: any): any;
renderInput(): any;
setValue(e: any): void;
}
export class Pagination extends React.Component <any> {
constructor(e: any);
adjustPage(): void;
afterPageText(): any;
beforePageText(): any;
componentDidMount(): void;
componentDidUpdate(e: any): void;
handleButtonClick(e: any): void;
handleLinkChange(e: any): void;
handleListChange(e: any): void;
handlePageInput(e: any): void;
isButton(e: any): any;
pageCount(): any;
pageInfo(): any;
refreshPage(): void;
render(): any;
renderLayout(e: any, t: any): any;
selectPage(e: any): void;
}
export class Panel extends React.Component <any> {
constructor(e: any);
bodyClasses(): any;
clickCloseTool(e: any): void;
clickCollapsibleTool(e: any): void;
clickPanelHeader(): void;
closableClasses(): any;
collapse(): void;
collapsibleClasses(): any;
componentDidUpdate(e: any): void;
expand(): void;
footerClasses(): any;
hasFooter(): any;
hasHeader(): any;
headerClasses(): any;
panelBody(): any;
panelClasses(): any;
panelFooter(): any;
panelHeader(): any;
panelStyles(): any;
render(): any;
toggle(): void;
}
export class PasswordBox extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
convert(e: any, ...args: any[]): void;
eyeClasses(): any;
eyeIconClasses(): any;
handleEyeClick(): void;
handleInputChange(e: any): void;
renderOthers(): any;
}
export class ProgressBar extends React.Component <any> {
constructor(...args: any[]);
barClasses(): any;
barStyles(): any;
render(): any;
static defaultProps: {
showValue: boolean;
value: number; };
}
export class RadioButton extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
handleChange(): void;
handleClick(): void;
radioClasses(): any;
render(): any;
select(): void;
setChecked(e: any): void;
wrapperClasses(): any;
}
export class Resizable extends React.Component <any> {
constructor(...args: any[]);
componentDidMount(): void;
componentDidUpdate(): void;
componentWillUnmount(): void;
render(): any;
}
export class SearchBox extends React.Component <any> {
constructor(e: any);
baseClasses(): any;
componentDidMount(): void;
componentDidUpdate(e: any): void;
doSearch(): void;
findItem(e: any): any;
handleIconClick(): void;
handleKeyDown(e: any): void;
handleMenuItemClick(e: any): void;
renderInput(): any;
renderMenu(): any;
renderOthers(): any;
setCategory(e: any): void;
}
export class SideMenu extends React.Component <any> {
constructor(e: any);
componentDidMount(): void;
componentDidUpdate(e: any): void;
handleItemClick(e: any): void;
handleNodeClick(e: any): any;
handleSelectionChange(e: any): void;
render(): any;
renderCollapsed(): any;
renderItems(): any;
setData(e: any): void;
}
export class Slider extends React.Component <any> {
constructor(e: any);
componentDidUpdate(e: any): void;
displayingRule(): any;
getPosStyle(e: any): any;
getRuleValueStyle(e: any): any;
handleDown(e: any): void;
handleDrag(e: any, ...args: any[]): void;
isDiff(e: any, t: any): any;
pos2value(e: any): any;
render(): any;
renderHandle(e: any): any;
renderRule(): any;
renderTip(e: any): any;
setPos(e: any, ...args: any[]): any;
setValue(e: any): void;
sliderClasses(): any;
value1(): any;
value2(): any;
value2pos(e: any): any;
}
export class SplitButton extends React.Component <any> {
constructor(e: any);
handleLineClick(e: any): void;
innerCls(): any;
render(): any;
renderInners(): any;
}
export class SubMenu extends React.Component <any> {
constructor(e: any);
alignMenu(): void;
componentDidMount(): void;
componentWillUnmount(): void;
render(): any;
}
export class SwitchButton extends React.Component <any> {
constructor(e: any);
buttonClasses(): any;
componentDidUpdate(e: any): void;
handleClick(e: any): void;
render(): any;
setValue(e: any): void;
}
export class TabPanel extends React.Component <any> {
constructor(e: any);
close(): void;
componentDidMount(): void;
componentWillUnmount(): void;
panelClasses(): any;
render(): any;
select(): any;
unselect(): void;
}
export class Tabs extends React.Component <any> {
constructor(e: any);
addHis(e: any): void;
backHis(): void;
bodyClasses(): any;
changePanels(): void;
componentDidUpdate(e: any): void;
componentWillUnmount(): void;
containerClasses(): any;
getPanel(e: any): any;
getPanelIndex(e: any): any;
getSelectedPanel(): any;
handlePanelAdd(e: any): void;
handlePanelRemove(e: any): void;
handleTabClick(e: any): void;
handleTabClose(e: any): void;
headerClasses(): any;
initPanels(): any;
initSelectedPanel(): any;
initUsedPanels(): any;
isHorizontal(): any;
isScrollable(): any;
isScrollerVisible(): any;
removeHis(e: any): any;
render(): any;
scrollBy(e: any): void;
select(e: any): void;
setMaxScrollDistance(e: any): void;
setScrollers(): void;
tabsClasses(): any;
tabsStyle(): any;
unselect(e: any): void;
}
export class TagBox extends React.Component <any> {
constructor(...args: any[]);
autoSizeInput(): any;
baseClasses(): any;
blur(): void;
clearText(): void;
componentDidMount(): void;
componentWillUnmount(): void;
doEnter(): any;
fixValue(): void;
getCss(e: any, t: any, n: any): any;
getTagClass(e: any): any;
getTagStyle(e: any): any;
handleClick(): any;
handleInputChange(e: any): void;
handleKeyDown(e: any): void;
handleRemoveClick(e: any, t: any): any;
renderInput(): any;
updateText(e: any): void;
}
export class TextBox extends React.Component <any> {
constructor(...args: any[]);
text(): any;
}
export class TextEditor extends React.Component <any> {
constructor(e: any);
baseClasses(): any;
componentDidMount(): void;
componentDidUpdate(e: any): void;
handleInputBlur(e: any): void;
handleInputFocus(e: any): void;
isDiff(e: any, t: any): any;
render(): any;
setValue(e: any): void;
}
export class TimePicker extends React.Component <any> {
constructor(e: any);
handleCloseClick(e: any): void;
handleOkClick(e: any): void;
handleTimeChange(e: any): void;
renderPanel(): any;
}
export class TimeSpinner extends React.Component <any> {
constructor(e: any);
blur(): void;
componentDidMount(): void;
defaultFormatter(e: any): any;
defaultParser(e: any): any;
doSpin(e: any): void;
doSpinDown(): void;
doSpinUp(): void;
handleClick(): void;
handleInputChange(e: any): void;
handleKeyDown(e: any): void;
handleKeyPress(e: any): any;
highlightRange(e: any): void;
parseD(e: any): any;
renderInput(): any;
setValue(e: any): void;
text(): any;
}
export class Tooltip extends React.Component <any> {
constructor(e: any);
bindEvents(...args: any[]): void;
clearTimeouts(): void;
componentDidMount(): void;
componentWillUnmount(): void;
handleActive(e: any): void;
handleContentMouseEnter(): any;
handleContentMouseLeave(): void;
handleDeactive(): void;
handleDocumentClick(e: any): void;
handleMouseMove(e: any): void;
hide(): void;
render(): any;
renderTip(): any;
show(): void;
}
export class Tree extends React.Component <any> {
constructor(e: any);
beginEdit(e: any, ...args: any[]): any;
cancelEdit(): void;
checkNode(e: any): void;
collapseNode(e: any): void;
componentDidUpdate(e: any): void;
doFilter(e: any): void;
endEdit(): any;
expandNode(e: any): void;
getCheckedNodes(...args: any[]): any;
isEditing(e: any): any;
render(): any;
selectNode(e: any): void;
uncheckAllNodes(): void;
uncheckNode(e: any): void;
}
export class TreeGrid extends React.Component <any> {
constructor(...args: any[]);
checkRow(e: any): void;
collapseRow(e: any): void;
doFilter(e: any): void;
expandRow(e: any): void;
getCheckedRows(...args: any[]): any;
sortData(): any;
uncheckAllRows(): void;
uncheckRow(e: any): void;
viewComponent(): any;
}
export class Validation extends React.Component <any> {
constructor(e: any);
getChildContext(): any;
getError(e: any): any;
getErrors(e: any): any;
getFieldValue(e: any): any;
hasError(e: any): any;
isFocused(e: any): any;
render(): any;
valid(): any;
validate(e: any): void;
validateField(e: any, t: any): any;
}
export class VirtualScroll extends React.Component <any> {
constructor(e: any);
componentDidMount(): any;
componentDidUpdate(e: any): void;
fetchPage(e: any): void;
handleScroll(e: any): void;
loadPage(e: any): void;
populate(e: any): void;
refresh(): void;
relativeScrollTop(): any;
render(): any;
renderContent(): any;
resetData(e: any): void;
scrollLeft(e: any): any;
scrollState(e: any): any;
scrollTop(e: any): any;
scrollbarWidth(): any;
scrolling(): void;
setData(e: any): void;
splitHeights(e: any): any;
}
export const filterOperators: {
beginwith: {
isMatch: any;
text: string; };
contains: {
isMatch: any;
text: string; };
endwith: {
isMatch: any;
text: string; };
equal: {
isMatch: any;
text: string; };
greater: {
isMatch: any;
text: string; };
greaterorequal: {
isMatch: any;
text: string; };
less: {
isMatch: any;
text: string; };
lessorequal: {
isMatch: any;
text: string; };
nofilter: {
isMatch: any;
text: string; };
notequal: {
isMatch: any;
text: string; };
};
export function DateTimeSpinner(...args: any[]): any;
export namespace Accordion {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Accordion.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Accordion.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const multiple: boolean;
const selectedIndex: number;
function onPanelSelect(e: any): void;
function onPanelUnselect(e: any): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onPanelSelect(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onPanelUnselect(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectedIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.Accordion.propTypes.animate
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.Accordion.propTypes.border
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.Accordion.propTypes.className
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.Accordion.propTypes.multiple
const isRequired: any;
}
namespace onPanelSelect {
// Circular reference from rc_easyui.Accordion.propTypes.onPanelSelect
const isRequired: any;
}
namespace onPanelUnselect {
// Circular reference from rc_easyui.Accordion.propTypes.onPanelUnselect
const isRequired: any;
}
namespace selectedIndex {
// Circular reference from rc_easyui.Accordion.propTypes.selectedIndex
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Accordion.propTypes.style
const isRequired: any;
}
}
}
export namespace AccordionPanel {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.AccordionPanel.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.AccordionPanel.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const closable: boolean;
const closeIconCls: string;
const closed: boolean;
const collapseIconCls: string;
const collapsed: boolean;
const collapsible: boolean;
const expandIconCls: string;
const selected: boolean;
const showFooter: boolean;
const showHeader: boolean;
const title: string;
function onCollapse(): void;
function onExpand(): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapseIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsible(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expandIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onCollapse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onExpand(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.AccordionPanel.propTypes.animate
const isRequired: any;
}
namespace bodyCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.bodyCls
const isRequired: any;
}
namespace bodyStyle {
// Circular reference from rc_easyui.AccordionPanel.propTypes.bodyStyle
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.AccordionPanel.propTypes.border
const isRequired: any;
}
namespace closable {
// Circular reference from rc_easyui.AccordionPanel.propTypes.closable
const isRequired: any;
}
namespace closeIconCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.closeIconCls
const isRequired: any;
}
namespace closed {
// Circular reference from rc_easyui.AccordionPanel.propTypes.closed
const isRequired: any;
}
namespace collapseIconCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.collapseIconCls
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.AccordionPanel.propTypes.collapsed
const isRequired: any;
}
namespace collapsible {
// Circular reference from rc_easyui.AccordionPanel.propTypes.collapsible
const isRequired: any;
}
namespace expandIconCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.expandIconCls
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.AccordionPanel.propTypes.footer
const isRequired: any;
}
namespace footerCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.footerCls
const isRequired: any;
}
namespace footerStyle {
// Circular reference from rc_easyui.AccordionPanel.propTypes.footerStyle
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.AccordionPanel.propTypes.header
const isRequired: any;
}
namespace headerCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.headerCls
const isRequired: any;
}
namespace headerStyle {
// Circular reference from rc_easyui.AccordionPanel.propTypes.headerStyle
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.AccordionPanel.propTypes.iconCls
const isRequired: any;
}
namespace onCollapse {
// Circular reference from rc_easyui.AccordionPanel.propTypes.onCollapse
const isRequired: any;
}
namespace onExpand {
// Circular reference from rc_easyui.AccordionPanel.propTypes.onExpand
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.AccordionPanel.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.AccordionPanel.propTypes.showHeader
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.AccordionPanel.propTypes.title
const isRequired: any;
}
}
}
export namespace ButtonGroup {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.ButtonGroup.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.ButtonGroup.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function selectionMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace selectionMode {
// Circular reference from rc_easyui.ButtonGroup.propTypes.selectionMode
const isRequired: any;
}
}
}
export namespace Calendar {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Calendar.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Calendar.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const border: boolean;
const defaultMonths: string[];
const defaultWeeks: string[];
const firstDay: number;
const info: any;
const month: number;
const showInfo: boolean;
const showWeek: boolean;
const weekNumberHeader: string;
const year: number;
function defaultInfo(e: any): any;
function onSelectionChange(e: any): void;
function validator(e: any): any;
}
namespace propTypes {
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function firstDay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function info(e: any, t: any, n: any, r: any, i: any, a: any): void;
function month(e: any, t: any, n: any, r: any, i: any, a: any): void;
function months(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showInfo(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showWeek(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function weekNumberHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function weeks(e: any, t: any, n: any, r: any, i: any, a: any): void;
function year(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace border {
// Circular reference from rc_easyui.Calendar.propTypes.border
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.Calendar.propTypes.className
const isRequired: any;
}
namespace firstDay {
// Circular reference from rc_easyui.Calendar.propTypes.firstDay
const isRequired: any;
}
namespace info {
// Circular reference from rc_easyui.Calendar.propTypes.info
const isRequired: any;
}
namespace month {
// Circular reference from rc_easyui.Calendar.propTypes.month
const isRequired: any;
}
namespace months {
// Circular reference from rc_easyui.Calendar.propTypes.months
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.Calendar.propTypes.selection
const isRequired: any;
}
namespace showInfo {
// Circular reference from rc_easyui.Calendar.propTypes.showInfo
const isRequired: any;
}
namespace showWeek {
// Circular reference from rc_easyui.Calendar.propTypes.showWeek
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Calendar.propTypes.style
const isRequired: any;
}
namespace validator {
// Circular reference from rc_easyui.Calendar.propTypes.validator
const isRequired: any;
}
namespace weekNumberHeader {
// Circular reference from rc_easyui.Calendar.propTypes.weekNumberHeader
const isRequired: any;
}
namespace weeks {
// Circular reference from rc_easyui.Calendar.propTypes.weeks
const isRequired: any;
}
namespace year {
// Circular reference from rc_easyui.Calendar.propTypes.year
const isRequired: any;
}
}
}
export namespace CheckBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.CheckBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.CheckBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.CheckBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const checked: boolean;
const disabled: boolean;
const multiple: boolean;
const values: any[];
function onChange(e: any): void;
}
namespace propTypes {
function checked(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
function values(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace checked {
// Circular reference from rc_easyui.CheckBox.propTypes.checked
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.CheckBox.propTypes.disabled
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.CheckBox.propTypes.inputId
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.CheckBox.propTypes.multiple
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.CheckBox.propTypes.onChange
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.CheckBox.propTypes.value
const isRequired: any;
}
namespace values {
// Circular reference from rc_easyui.CheckBox.propTypes.values
const isRequired: any;
}
}
}
export namespace ComboBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.ComboBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.ComboBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.ComboBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const arrowAlign: string;
const arrowIconCls: string;
const data: any[];
const delay: number;
const disabled: boolean;
const editable: boolean;
const hasDownArrow: boolean;
const iconAlign: string;
const invalid: boolean;
const lazy: boolean;
const limitToList: boolean;
const multiline: boolean;
const multiple: boolean;
const pageNumber: number;
const pageSize: number;
const panelAlign: string;
const readOnly: boolean;
const rowHeight: number;
const separator: string;
const textField: string;
const total: number;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
const valueField: string;
const virtualScroll: boolean;
function filter(e: any, t: any): any;
function onBlur(): void;
function onChange(e: any): void;
function onFilterChange(e: any): void;
function onFocus(): void;
function onSelectionChange(e: any): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function groupField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function limitToList(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderItem(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
function valueField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.ComboBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.ComboBox.propTypes.addonRight
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.ComboBox.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.ComboBox.propTypes.arrowIconCls
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.ComboBox.propTypes.className
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.ComboBox.propTypes.data
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.ComboBox.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.ComboBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.ComboBox.propTypes.editable
const isRequired: any;
}
namespace filter {
// Circular reference from rc_easyui.ComboBox.propTypes.filter
const isRequired: any;
}
namespace groupField {
// Circular reference from rc_easyui.ComboBox.propTypes.groupField
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.ComboBox.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.ComboBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.ComboBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.ComboBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.ComboBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.ComboBox.propTypes.inputStyle
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.ComboBox.propTypes.lazy
const isRequired: any;
}
namespace limitToList {
// Circular reference from rc_easyui.ComboBox.propTypes.limitToList
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.ComboBox.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.ComboBox.propTypes.multiple
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.ComboBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.ComboBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.ComboBox.propTypes.onFocus
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.ComboBox.propTypes.pageNumber
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.ComboBox.propTypes.pageSize
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.ComboBox.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.ComboBox.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.ComboBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.ComboBox.propTypes.readOnly
const isRequired: any;
}
namespace renderItem {
// Circular reference from rc_easyui.ComboBox.propTypes.renderItem
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.ComboBox.propTypes.rowHeight
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.ComboBox.propTypes.separator
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.ComboBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.ComboBox.propTypes.tabIndex
const isRequired: any;
}
namespace textField {
// Circular reference from rc_easyui.ComboBox.propTypes.textField
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.ComboBox.propTypes.textFormatter
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.ComboBox.propTypes.total
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.ComboBox.propTypes.value
const isRequired: any;
}
namespace valueField {
// Circular reference from rc_easyui.ComboBox.propTypes.valueField
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.ComboBox.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace ComboGrid {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.ComboGrid.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.ComboGrid.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.ComboGrid.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const arrowAlign: string;
const arrowIconCls: string;
const data: any[];
const delay: number;
const disabled: boolean;
const editable: boolean;
const hasDownArrow: boolean;
const iconAlign: string;
const invalid: boolean;
const limitToList: boolean;
const multiline: boolean;
const multiple: boolean;
const panelAlign: string;
const readOnly: boolean;
const separator: string;
const textField: string;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
const valueField: string;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.ComboGrid.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.ComboGrid.propTypes.addonRight
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.ComboGrid.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.ComboGrid.propTypes.arrowIconCls
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.ComboGrid.propTypes.className
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.ComboGrid.propTypes.data
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.ComboGrid.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.ComboGrid.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.ComboGrid.propTypes.editable
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.ComboGrid.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.ComboGrid.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.ComboGrid.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.ComboGrid.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.ComboGrid.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.ComboGrid.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.ComboGrid.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.ComboGrid.propTypes.multiple
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.ComboGrid.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.ComboGrid.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.ComboGrid.propTypes.onFocus
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.ComboGrid.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.ComboGrid.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.ComboGrid.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.ComboGrid.propTypes.readOnly
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.ComboGrid.propTypes.separator
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.ComboGrid.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.ComboGrid.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.ComboGrid.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.ComboGrid.propTypes.value
const isRequired: any;
}
}
}
export namespace ComboTree {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.ComboTree.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.ComboTree.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.ComboTree.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const arrowAlign: string;
const arrowIconCls: string;
const data: any[];
const delay: number;
const disabled: boolean;
const editable: boolean;
const hasDownArrow: boolean;
const iconAlign: string;
const invalid: boolean;
const limitToList: boolean;
const multiline: boolean;
const multiple: boolean;
const panelAlign: string;
const readOnly: boolean;
const separator: string;
const textField: string;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
const valueField: string;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.ComboTree.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.ComboTree.propTypes.addonRight
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.ComboTree.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.ComboTree.propTypes.arrowIconCls
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.ComboTree.propTypes.className
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.ComboTree.propTypes.data
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.ComboTree.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.ComboTree.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.ComboTree.propTypes.editable
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.ComboTree.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.ComboTree.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.ComboTree.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.ComboTree.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.ComboTree.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.ComboTree.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.ComboTree.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.ComboTree.propTypes.multiple
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.ComboTree.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.ComboTree.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.ComboTree.propTypes.onFocus
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.ComboTree.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.ComboTree.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.ComboTree.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.ComboTree.propTypes.readOnly
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.ComboTree.propTypes.separator
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.ComboTree.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.ComboTree.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.ComboTree.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.ComboTree.propTypes.value
const isRequired: any;
}
}
}
export namespace DataGrid {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.DataGrid.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.DataGrid.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const border: boolean;
const clickToEdit: boolean;
const columnMoving: boolean;
const columnResizing: boolean;
const data: any[];
const dblclickToEdit: boolean;
const defaultLoadMsg: string;
const expanderWidth: number;
const filterBtnPosition: string;
const filterDelay: number;
const filterMatchingType: string;
const filterOperators: {
beginwith: {
isMatch: any;
text: string;
};
contains: {
isMatch: any;
text: string;
};
endwith: {
isMatch: any;
text: string;
};
equal: {
isMatch: any;
text: string;
};
greater: {
isMatch: any;
text: string;
};
greaterorequal: {
isMatch: any;
text: string;
};
less: {
isMatch: any;
text: string;
};
lessorequal: {
isMatch: any;
text: string;
};
nofilter: {
isMatch: any;
text: string;
};
notequal: {
isMatch: any;
text: string;
}; };
const filterPosition: string;
const filterRules: any[];
const filterable: boolean;
const footerData: any[];
const frozenAlign: string;
const frozenWidth: string;
const lazy: boolean;
const loading: boolean;
const multiSort: boolean;
const pageNumber: number;
const pagePosition: string;
const pageSize: number;
const pagination: boolean;
const rowHeight: number;
const showFooter: boolean;
const showHeader: boolean;
const sorts: any[];
const striped: boolean;
const total: number;
const virtualScroll: boolean;
function onCellClick(): void;
function onCellContextMenu(e: any): void;
function onCellDblClick(): void;
function onCellSelect(): void;
function onCellUnselect(): void;
function onColumnMove(e: any): void;
function onColumnResize(e: any): void;
function onEditBegin(e: any): void;
function onEditCancel(e: any): void;
function onEditEnd(e: any): void;
function onEditValidate(e: any): void;
function onFilterChange(): void;
function onGroupCollapse(e: any): void;
function onGroupExpand(e: any): void;
function onPageChange(): void;
function onRowClick(e: any): void;
function onRowCollapse(e: any): void;
function onRowContextMenu(e: any): void;
function onRowDblClick(e: any): void;
function onRowExpand(e: any): void;
function onRowSelect(): void;
function onRowUnselect(): void;
function onSelectionChange(): void;
function onSortChange(): void;
}
namespace propTypes {
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function clickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function columnMoving(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function dblclickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expanderWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterBtnPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterMatchingType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterOperators(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerData(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function groupField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function idField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loadMsg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loading(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiSort(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageOptions(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagePosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagination(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderDetail(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderGroup(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowCss(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectionMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function sorts(e: any, t: any, n: any, r: any, i: any, a: any): void;
function striped(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace border {
// Circular reference from rc_easyui.DataGrid.propTypes.border
const isRequired: any;
}
namespace clickToEdit {
// Circular reference from rc_easyui.DataGrid.propTypes.clickToEdit
const isRequired: any;
}
namespace columnMoving {
// Circular reference from rc_easyui.DataGrid.propTypes.columnMoving
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.DataGrid.propTypes.data
const isRequired: any;
}
namespace dblclickToEdit {
// Circular reference from rc_easyui.DataGrid.propTypes.dblclickToEdit
const isRequired: any;
}
namespace editMode {
// Circular reference from rc_easyui.DataGrid.propTypes.editMode
const isRequired: any;
}
namespace expanderWidth {
// Circular reference from rc_easyui.DataGrid.propTypes.expanderWidth
const isRequired: any;
}
namespace filterBtnPosition {
// Circular reference from rc_easyui.DataGrid.propTypes.filterBtnPosition
const isRequired: any;
}
namespace filterDelay {
// Circular reference from rc_easyui.DataGrid.propTypes.filterDelay
const isRequired: any;
}
namespace filterMatchingType {
// Circular reference from rc_easyui.DataGrid.propTypes.filterMatchingType
const isRequired: any;
}
namespace filterOperators {
// Circular reference from rc_easyui.DataGrid.propTypes.filterOperators
const isRequired: any;
}
namespace filterPosition {
// Circular reference from rc_easyui.DataGrid.propTypes.filterPosition
const isRequired: any;
}
namespace filterRules {
// Circular reference from rc_easyui.DataGrid.propTypes.filterRules
const isRequired: any;
}
namespace filterable {
// Circular reference from rc_easyui.DataGrid.propTypes.filterable
const isRequired: any;
}
namespace footerData {
// Circular reference from rc_easyui.DataGrid.propTypes.footerData
const isRequired: any;
}
namespace frozenAlign {
// Circular reference from rc_easyui.DataGrid.propTypes.frozenAlign
const isRequired: any;
}
namespace frozenWidth {
// Circular reference from rc_easyui.DataGrid.propTypes.frozenWidth
const isRequired: any;
}
namespace groupField {
// Circular reference from rc_easyui.DataGrid.propTypes.groupField
const isRequired: any;
}
namespace idField {
// Circular reference from rc_easyui.DataGrid.propTypes.idField
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.DataGrid.propTypes.lazy
const isRequired: any;
}
namespace loadMsg {
// Circular reference from rc_easyui.DataGrid.propTypes.loadMsg
const isRequired: any;
}
namespace loading {
// Circular reference from rc_easyui.DataGrid.propTypes.loading
const isRequired: any;
}
namespace multiSort {
// Circular reference from rc_easyui.DataGrid.propTypes.multiSort
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.DataGrid.propTypes.pageNumber
const isRequired: any;
}
namespace pageOptions {
// Circular reference from rc_easyui.DataGrid.propTypes.pageOptions
const isRequired: any;
}
namespace pagePosition {
// Circular reference from rc_easyui.DataGrid.propTypes.pagePosition
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.DataGrid.propTypes.pageSize
const isRequired: any;
}
namespace pagination {
// Circular reference from rc_easyui.DataGrid.propTypes.pagination
const isRequired: any;
}
namespace renderDetail {
// Circular reference from rc_easyui.DataGrid.propTypes.renderDetail
const isRequired: any;
}
namespace renderGroup {
// Circular reference from rc_easyui.DataGrid.propTypes.renderGroup
const isRequired: any;
}
namespace rowCss {
// Circular reference from rc_easyui.DataGrid.propTypes.rowCss
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.DataGrid.propTypes.rowHeight
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.DataGrid.propTypes.selection
const isRequired: any;
}
namespace selectionMode {
// Circular reference from rc_easyui.DataGrid.propTypes.selectionMode
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.DataGrid.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.DataGrid.propTypes.showHeader
const isRequired: any;
}
namespace sorts {
// Circular reference from rc_easyui.DataGrid.propTypes.sorts
const isRequired: any;
}
namespace striped {
// Circular reference from rc_easyui.DataGrid.propTypes.striped
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.DataGrid.propTypes.total
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.DataGrid.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace DataList {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.DataList.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.DataList.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const border: boolean;
const data: any[];
const defaultLoadMsg: string;
const filterBtnPosition: string;
const filterDelay: number;
const filterMatchingType: string;
const filterOperators: {
beginwith: {
isMatch: any;
text: string;
};
contains: {
isMatch: any;
text: string;
};
endwith: {
isMatch: any;
text: string;
};
equal: {
isMatch: any;
text: string;
};
greater: {
isMatch: any;
text: string;
};
greaterorequal: {
isMatch: any;
text: string;
};
less: {
isMatch: any;
text: string;
};
lessorequal: {
isMatch: any;
text: string;
};
nofilter: {
isMatch: any;
text: string;
};
notequal: {
isMatch: any;
text: string;
}; };
const filterPosition: string;
const filterRules: any[];
const filterable: boolean;
const hoverCls: string;
const lazy: boolean;
const loading: boolean;
const pageNumber: number;
const pagePosition: string;
const pageSize: number;
const pagination: boolean;
const rowHeight: number;
const selectedCls: string;
const total: number;
const virtualScroll: boolean;
function onCellClick(): void;
function onCellDblClick(): void;
function onCellSelect(): void;
function onCellUnselect(): void;
function onFilterChange(): void;
function onListScroll(e: any): void;
function onPageChange(): void;
function onRowClick(e: any): void;
function onRowDblClick(e: any): void;
function onRowSelect(): void;
function onRowUnselect(): void;
function onSelectionChange(): void;
}
namespace propTypes {
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterBtnPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterMatchingType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterOperators(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hoverCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function idField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function itemCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function itemStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loadMsg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loading(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onListScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageOptions(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagePosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagination(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderItem(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function scrollPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectedCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectionMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace border {
// Circular reference from rc_easyui.DataList.propTypes.border
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.DataList.propTypes.data
const isRequired: any;
}
namespace filterBtnPosition {
// Circular reference from rc_easyui.DataList.propTypes.filterBtnPosition
const isRequired: any;
}
namespace filterDelay {
// Circular reference from rc_easyui.DataList.propTypes.filterDelay
const isRequired: any;
}
namespace filterMatchingType {
// Circular reference from rc_easyui.DataList.propTypes.filterMatchingType
const isRequired: any;
}
namespace filterOperators {
// Circular reference from rc_easyui.DataList.propTypes.filterOperators
const isRequired: any;
}
namespace filterPosition {
// Circular reference from rc_easyui.DataList.propTypes.filterPosition
const isRequired: any;
}
namespace filterRules {
// Circular reference from rc_easyui.DataList.propTypes.filterRules
const isRequired: any;
}
namespace filterable {
// Circular reference from rc_easyui.DataList.propTypes.filterable
const isRequired: any;
}
namespace hoverCls {
// Circular reference from rc_easyui.DataList.propTypes.hoverCls
const isRequired: any;
}
namespace idField {
// Circular reference from rc_easyui.DataList.propTypes.idField
const isRequired: any;
}
namespace itemCls {
// Circular reference from rc_easyui.DataList.propTypes.itemCls
const isRequired: any;
}
namespace itemStyle {
// Circular reference from rc_easyui.DataList.propTypes.itemStyle
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.DataList.propTypes.lazy
const isRequired: any;
}
namespace loadMsg {
// Circular reference from rc_easyui.DataList.propTypes.loadMsg
const isRequired: any;
}
namespace loading {
// Circular reference from rc_easyui.DataList.propTypes.loading
const isRequired: any;
}
namespace onListScroll {
// Circular reference from rc_easyui.DataList.propTypes.onListScroll
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.DataList.propTypes.pageNumber
const isRequired: any;
}
namespace pageOptions {
// Circular reference from rc_easyui.DataList.propTypes.pageOptions
const isRequired: any;
}
namespace pagePosition {
// Circular reference from rc_easyui.DataList.propTypes.pagePosition
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.DataList.propTypes.pageSize
const isRequired: any;
}
namespace pagination {
// Circular reference from rc_easyui.DataList.propTypes.pagination
const isRequired: any;
}
namespace renderItem {
// Circular reference from rc_easyui.DataList.propTypes.renderItem
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.DataList.propTypes.rowHeight
const isRequired: any;
}
namespace scrollPosition {
// Circular reference from rc_easyui.DataList.propTypes.scrollPosition
const isRequired: any;
}
namespace selectedCls {
// Circular reference from rc_easyui.DataList.propTypes.selectedCls
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.DataList.propTypes.selection
const isRequired: any;
}
namespace selectionMode {
// Circular reference from rc_easyui.DataList.propTypes.selectionMode
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.DataList.propTypes.total
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.DataList.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace DateBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.DateBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.DateBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.DateBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const arrowAlign: string;
const arrowIconCls: string;
const defaultCloseText: string;
const defaultCurrentText: string;
const defaultOkText: string;
const delay: number;
const disabled: boolean;
const editable: boolean;
const format: string;
const hasDownArrow: boolean;
const iconAlign: string;
const info: any;
const invalid: boolean;
const multiline: boolean;
const multiple: boolean;
const panelAlign: string;
const readOnly: boolean;
const separator: string;
const showInfo: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function calendarOptions(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function currentText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function format(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function info(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function okText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showInfo(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.DateBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.DateBox.propTypes.addonRight
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.DateBox.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.DateBox.propTypes.arrowIconCls
const isRequired: any;
}
namespace calendarOptions {
// Circular reference from rc_easyui.DateBox.propTypes.calendarOptions
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.DateBox.propTypes.className
const isRequired: any;
}
namespace closeText {
// Circular reference from rc_easyui.DateBox.propTypes.closeText
const isRequired: any;
}
namespace currentText {
// Circular reference from rc_easyui.DateBox.propTypes.currentText
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.DateBox.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.DateBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.DateBox.propTypes.editable
const isRequired: any;
}
namespace format {
// Circular reference from rc_easyui.DateBox.propTypes.format
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.DateBox.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.DateBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.DateBox.propTypes.iconCls
const isRequired: any;
}
namespace info {
// Circular reference from rc_easyui.DateBox.propTypes.info
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.DateBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.DateBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.DateBox.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.DateBox.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.DateBox.propTypes.multiple
const isRequired: any;
}
namespace okText {
// Circular reference from rc_easyui.DateBox.propTypes.okText
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.DateBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.DateBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.DateBox.propTypes.onFocus
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.DateBox.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.DateBox.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.DateBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.DateBox.propTypes.readOnly
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.DateBox.propTypes.separator
const isRequired: any;
}
namespace showInfo {
// Circular reference from rc_easyui.DateBox.propTypes.showInfo
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.DateBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.DateBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.DateBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.DateBox.propTypes.value
const isRequired: any;
}
}
}
export namespace DateTimeSpinner {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.DateTimeSpinner.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const ampm: string[];
const disabled: boolean;
const editable: boolean;
const format: string;
const highlight: number;
const iconAlign: string;
const increment: number;
const invalid: boolean;
const multiline: boolean;
const readOnly: boolean;
const reversed: boolean;
const selections: Array<(number[])>;
const spinAlign: string;
const spinners: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function ampm(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function format(e: any, t: any, n: any, r: any, i: any, a: any): void;
function highlight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function increment(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function max(e: any, t: any, n: any, r: any, i: any, a: any): void;
function min(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function reversed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selections(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinners(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.addonRight
const isRequired: any;
}
namespace ampm {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.ampm
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.editable
const isRequired: any;
}
namespace format {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.format
const isRequired: any;
}
namespace highlight {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.highlight
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.iconCls
const isRequired: any;
}
namespace increment {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.increment
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.inputStyle
const isRequired: any;
}
namespace max {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.max
const isRequired: any;
}
namespace min {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.min
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.readOnly
const isRequired: any;
}
namespace reversed {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.reversed
const isRequired: any;
}
namespace selections {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.selections
const isRequired: any;
}
namespace spinAlign {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.spinAlign
const isRequired: any;
}
namespace spinners {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.spinners
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.DateTimeSpinner.propTypes.value
const isRequired: any;
}
}
}
export namespace Dialog {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Dialog.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Dialog.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const autoCenter: boolean;
const border: boolean;
const borderType: string;
const closable: boolean;
const closeIconCls: string;
const closed: boolean;
const collapseIconCls: string;
const collapsed: boolean;
const collapsible: boolean;
const draggable: boolean;
const expandIconCls: string;
const modal: boolean;
const resizable: boolean;
const showFooter: boolean;
const showHeader: boolean;
function onClose(): void;
function onCollapse(): void;
function onExpand(): void;
function onMove(e: any): void;
function onOpen(): void;
function onResize(e: any): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function autoCenter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function borderType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapseIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsible(e: any, t: any, n: any, r: any, i: any, a: any): void;
function draggable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expandIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function modal(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onCollapse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onExpand(e: any, t: any, n: any, r: any, i: any, a: any): void;
function resizable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.Dialog.propTypes.animate
const isRequired: any;
}
namespace autoCenter {
// Circular reference from rc_easyui.Dialog.propTypes.autoCenter
const isRequired: any;
}
namespace bodyCls {
// Circular reference from rc_easyui.Dialog.propTypes.bodyCls
const isRequired: any;
}
namespace bodyStyle {
// Circular reference from rc_easyui.Dialog.propTypes.bodyStyle
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.Dialog.propTypes.border
const isRequired: any;
}
namespace borderType {
// Circular reference from rc_easyui.Dialog.propTypes.borderType
const isRequired: any;
}
namespace closable {
// Circular reference from rc_easyui.Dialog.propTypes.closable
const isRequired: any;
}
namespace closeIconCls {
// Circular reference from rc_easyui.Dialog.propTypes.closeIconCls
const isRequired: any;
}
namespace closed {
// Circular reference from rc_easyui.Dialog.propTypes.closed
const isRequired: any;
}
namespace collapseIconCls {
// Circular reference from rc_easyui.Dialog.propTypes.collapseIconCls
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.Dialog.propTypes.collapsed
const isRequired: any;
}
namespace collapsible {
// Circular reference from rc_easyui.Dialog.propTypes.collapsible
const isRequired: any;
}
namespace draggable {
// Circular reference from rc_easyui.Dialog.propTypes.draggable
const isRequired: any;
}
namespace expandIconCls {
// Circular reference from rc_easyui.Dialog.propTypes.expandIconCls
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.Dialog.propTypes.footer
const isRequired: any;
}
namespace footerCls {
// Circular reference from rc_easyui.Dialog.propTypes.footerCls
const isRequired: any;
}
namespace footerStyle {
// Circular reference from rc_easyui.Dialog.propTypes.footerStyle
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.Dialog.propTypes.header
const isRequired: any;
}
namespace headerCls {
// Circular reference from rc_easyui.Dialog.propTypes.headerCls
const isRequired: any;
}
namespace headerStyle {
// Circular reference from rc_easyui.Dialog.propTypes.headerStyle
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.Dialog.propTypes.iconCls
const isRequired: any;
}
namespace modal {
// Circular reference from rc_easyui.Dialog.propTypes.modal
const isRequired: any;
}
namespace onCollapse {
// Circular reference from rc_easyui.Dialog.propTypes.onCollapse
const isRequired: any;
}
namespace onExpand {
// Circular reference from rc_easyui.Dialog.propTypes.onExpand
const isRequired: any;
}
namespace resizable {
// Circular reference from rc_easyui.Dialog.propTypes.resizable
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.Dialog.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.Dialog.propTypes.showHeader
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.Dialog.propTypes.title
const isRequired: any;
}
}
}
export namespace Draggable {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Draggable.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Draggable.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const cursor: string;
const delay: number;
const disabled: boolean;
const edge: number;
const revert: boolean;
function onDrag(e: any): void;
function onDragEnd(e: any): void;
function onDragStart(e: any): void;
}
namespace propTypes {
function axis(e: any, t: any, n: any, r: any, i: any, a: any): void;
function cursor(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function deltaX(e: any, t: any, n: any, r: any, i: any, a: any): void;
function deltaY(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function edge(e: any, t: any, n: any, r: any, i: any, a: any): void;
function handle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onDrag(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onDragEnd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onDragStart(e: any, t: any, n: any, r: any, i: any, a: any): void;
function proxy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function proxyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function proxyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function revert(e: any, t: any, n: any, r: any, i: any, a: any): void;
function scope(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace axis {
// Circular reference from rc_easyui.Draggable.propTypes.axis
const isRequired: any;
}
namespace cursor {
// Circular reference from rc_easyui.Draggable.propTypes.cursor
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.Draggable.propTypes.delay
const isRequired: any;
}
namespace deltaX {
// Circular reference from rc_easyui.Draggable.propTypes.deltaX
const isRequired: any;
}
namespace deltaY {
// Circular reference from rc_easyui.Draggable.propTypes.deltaY
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.Draggable.propTypes.disabled
const isRequired: any;
}
namespace edge {
// Circular reference from rc_easyui.Draggable.propTypes.edge
const isRequired: any;
}
namespace handle {
// Circular reference from rc_easyui.Draggable.propTypes.handle
const isRequired: any;
}
namespace onDrag {
// Circular reference from rc_easyui.Draggable.propTypes.onDrag
const isRequired: any;
}
namespace onDragEnd {
// Circular reference from rc_easyui.Draggable.propTypes.onDragEnd
const isRequired: any;
}
namespace onDragStart {
// Circular reference from rc_easyui.Draggable.propTypes.onDragStart
const isRequired: any;
}
namespace proxy {
// Circular reference from rc_easyui.Draggable.propTypes.proxy
const isRequired: any;
}
namespace proxyCls {
// Circular reference from rc_easyui.Draggable.propTypes.proxyCls
const isRequired: any;
}
namespace proxyStyle {
// Circular reference from rc_easyui.Draggable.propTypes.proxyStyle
const isRequired: any;
}
namespace revert {
// Circular reference from rc_easyui.Draggable.propTypes.revert
const isRequired: any;
}
namespace scope {
// Circular reference from rc_easyui.Draggable.propTypes.scope
const isRequired: any;
}
}
}
export namespace DraggableProxy {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.DraggableProxy.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.DraggableProxy.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.DraggableProxy.propTypes.className
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.DraggableProxy.propTypes.style
const isRequired: any;
}
}
}
export namespace Droppable {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Droppable.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Droppable.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
function onDragEnter(e: any): void;
function onDragLeave(e: any): void;
function onDragOver(e: any): void;
function onDrop(e: any): void;
}
namespace propTypes {
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function scope(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace disabled {
// Circular reference from rc_easyui.Droppable.propTypes.disabled
const isRequired: any;
}
namespace scope {
// Circular reference from rc_easyui.Droppable.propTypes.scope
const isRequired: any;
}
}
}
export namespace FieldBase {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.FieldBase.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.FieldBase.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.FieldBase.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function invalid(e: any, t: any, n: any, r: any, i: any, a: any): void;
function name(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnCreate(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace invalid {
// Circular reference from rc_easyui.FieldBase.propTypes.invalid
const isRequired: any;
}
namespace name {
// Circular reference from rc_easyui.FieldBase.propTypes.name
const isRequired: any;
}
namespace validateOnBlur {
// Circular reference from rc_easyui.FieldBase.propTypes.validateOnBlur
const isRequired: any;
}
namespace validateOnChange {
// Circular reference from rc_easyui.FieldBase.propTypes.validateOnChange
const isRequired: any;
}
namespace validateOnCreate {
// Circular reference from rc_easyui.FieldBase.propTypes.validateOnCreate
const isRequired: any;
}
}
}
export namespace FileButton {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.FileButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.FileButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const autoUpload: boolean;
const disabled: boolean;
const href: string;
const iconAlign: string;
const method: string;
const multiple: boolean;
const name: string;
const outline: boolean;
const plain: boolean;
const selected: boolean;
const size: string;
const toggle: boolean;
const withCredentials: boolean;
function onClick(): void;
function onError(e: any): void;
function onProgress(e: any): void;
function onSelect(e: any): void;
function onSuccess(e: any): void;
}
namespace propTypes {
function accept(e: any, t: any, n: any, r: any, i: any, a: any): void;
function autoUpload(e: any, t: any, n: any, r: any, i: any, a: any): void;
function capture(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function href(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function method(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onClick(e: any, t: any, n: any, r: any, i: any, a: any): void;
function outline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function plain(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selected(e: any, t: any, n: any, r: any, i: any, a: any): void;
function size(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function text(e: any, t: any, n: any, r: any, i: any, a: any): void;
function toggle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function url(e: any, t: any, n: any, r: any, i: any, a: any): void;
function withCredentials(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace accept {
// Circular reference from rc_easyui.FileButton.propTypes.accept
const isRequired: any;
}
namespace autoUpload {
// Circular reference from rc_easyui.FileButton.propTypes.autoUpload
const isRequired: any;
}
namespace capture {
// Circular reference from rc_easyui.FileButton.propTypes.capture
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.FileButton.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.FileButton.propTypes.disabled
const isRequired: any;
}
namespace href {
// Circular reference from rc_easyui.FileButton.propTypes.href
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.FileButton.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.FileButton.propTypes.iconCls
const isRequired: any;
}
namespace method {
// Circular reference from rc_easyui.FileButton.propTypes.method
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.FileButton.propTypes.multiple
const isRequired: any;
}
namespace onClick {
// Circular reference from rc_easyui.FileButton.propTypes.onClick
const isRequired: any;
}
namespace outline {
// Circular reference from rc_easyui.FileButton.propTypes.outline
const isRequired: any;
}
namespace plain {
// Circular reference from rc_easyui.FileButton.propTypes.plain
const isRequired: any;
}
namespace selected {
// Circular reference from rc_easyui.FileButton.propTypes.selected
const isRequired: any;
}
namespace size {
// Circular reference from rc_easyui.FileButton.propTypes.size
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.FileButton.propTypes.style
const isRequired: any;
}
namespace text {
// Circular reference from rc_easyui.FileButton.propTypes.text
const isRequired: any;
}
namespace toggle {
// Circular reference from rc_easyui.FileButton.propTypes.toggle
const isRequired: any;
}
namespace url {
// Circular reference from rc_easyui.FileButton.propTypes.url
const isRequired: any;
}
namespace withCredentials {
// Circular reference from rc_easyui.FileButton.propTypes.withCredentials
const isRequired: any;
}
}
}
export namespace Form {
namespace childContextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function floatingLabel(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.Form.childContextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.Form.childContextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.Form.childContextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.Form.childContextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.Form.childContextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.Form.childContextTypes.fieldRemove
const isRequired: any;
}
namespace floatingLabel {
// Circular reference from rc_easyui.Form.childContextTypes.floatingLabel
const isRequired: any;
}
namespace labelAlign {
// Circular reference from rc_easyui.Form.childContextTypes.labelAlign
const isRequired: any;
}
namespace labelPosition {
// Circular reference from rc_easyui.Form.childContextTypes.labelPosition
const isRequired: any;
}
namespace labelWidth {
// Circular reference from rc_easyui.Form.childContextTypes.labelWidth
const isRequired: any;
}
}
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Form.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Form.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const delay: number;
const errorType: string;
const floatingLabel: boolean;
const labelAlign: string;
const labelPosition: string;
const labelWidth: number;
const tooltipPosition: string;
function onChange(e: any, t: any): void;
function onSubmit(e: any): void;
function onValidate(e: any): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function errorType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function floatingLabel(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function model(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onValidate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tooltipPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.Form.propTypes.className
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.Form.propTypes.delay
const isRequired: any;
}
namespace errorType {
// Circular reference from rc_easyui.Form.propTypes.errorType
const isRequired: any;
}
namespace floatingLabel {
// Circular reference from rc_easyui.Form.propTypes.floatingLabel
const isRequired: any;
}
namespace labelAlign {
// Circular reference from rc_easyui.Form.propTypes.labelAlign
const isRequired: any;
}
namespace labelPosition {
// Circular reference from rc_easyui.Form.propTypes.labelPosition
const isRequired: any;
}
namespace labelWidth {
// Circular reference from rc_easyui.Form.propTypes.labelWidth
const isRequired: any;
}
namespace model {
// Circular reference from rc_easyui.Form.propTypes.model
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.Form.propTypes.onChange
const isRequired: any;
}
namespace onValidate {
// Circular reference from rc_easyui.Form.propTypes.onValidate
const isRequired: any;
}
namespace rules {
// Circular reference from rc_easyui.Form.propTypes.rules
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Form.propTypes.style
const isRequired: any;
}
namespace tooltipPosition {
// Circular reference from rc_easyui.Form.propTypes.tooltipPosition
const isRequired: any;
}
namespace validateRules {
// Circular reference from rc_easyui.Form.propTypes.validateRules
const isRequired: any;
}
}
}
export namespace FormField {
namespace contextTypes {
function floatingLabel(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace floatingLabel {
// Circular reference from rc_easyui.FormField.contextTypes.floatingLabel
const isRequired: any;
}
namespace labelAlign {
// Circular reference from rc_easyui.FormField.contextTypes.labelAlign
const isRequired: any;
}
namespace labelPosition {
// Circular reference from rc_easyui.FormField.contextTypes.labelPosition
const isRequired: any;
}
namespace labelWidth {
// Circular reference from rc_easyui.FormField.contextTypes.labelWidth
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.FormField.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.FormField.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function label(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function labelWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function name(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.FormField.propTypes.className
const isRequired: any;
}
namespace label {
// Circular reference from rc_easyui.FormField.propTypes.label
const isRequired: any;
}
namespace labelAlign {
// Circular reference from rc_easyui.FormField.propTypes.labelAlign
const isRequired: any;
}
namespace labelPosition {
// Circular reference from rc_easyui.FormField.propTypes.labelPosition
const isRequired: any;
}
namespace labelWidth {
// Circular reference from rc_easyui.FormField.propTypes.labelWidth
const isRequired: any;
}
namespace name {
// Circular reference from rc_easyui.FormField.propTypes.name
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.FormField.propTypes.style
const isRequired: any;
}
}
}
export namespace GridBase {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.GridBase.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.GridBase.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const border: boolean;
const clickToEdit: boolean;
const columnMoving: boolean;
const columnResizing: boolean;
const data: any[];
const dblclickToEdit: boolean;
const defaultLoadMsg: string;
const filterBtnPosition: string;
const filterDelay: number;
const filterMatchingType: string;
const filterOperators: {
beginwith: {
isMatch: any;
text: string;
};
contains: {
isMatch: any;
text: string;
};
endwith: {
isMatch: any;
text: string;
};
equal: {
isMatch: any;
text: string;
};
greater: {
isMatch: any;
text: string;
};
greaterorequal: {
isMatch: any;
text: string;
};
less: {
isMatch: any;
text: string;
};
lessorequal: {
isMatch: any;
text: string;
};
nofilter: {
isMatch: any;
text: string;
};
notequal: {
isMatch: any;
text: string;
}; };
const filterPosition: string;
const filterRules: any[];
const filterable: boolean;
const footerData: any[];
const frozenAlign: string;
const frozenWidth: string;
const lazy: boolean;
const loading: boolean;
const multiSort: boolean;
const pageNumber: number;
const pagePosition: string;
const pageSize: number;
const pagination: boolean;
const rowHeight: number;
const showFooter: boolean;
const showHeader: boolean;
const sorts: any[];
const striped: boolean;
const total: number;
const virtualScroll: boolean;
function onCellClick(): void;
function onCellContextMenu(e: any): void;
function onCellDblClick(): void;
function onCellSelect(): void;
function onCellUnselect(): void;
function onColumnMove(e: any): void;
function onColumnResize(e: any): void;
function onEditBegin(e: any): void;
function onEditCancel(e: any): void;
function onEditEnd(e: any): void;
function onEditValidate(e: any): void;
function onFilterChange(): void;
function onPageChange(): void;
function onRowClick(e: any): void;
function onRowContextMenu(e: any): void;
function onRowDblClick(e: any): void;
function onRowSelect(): void;
function onRowUnselect(): void;
function onSelectionChange(): void;
function onSortChange(): void;
}
namespace propTypes {
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function clickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function columnMoving(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function dblclickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterBtnPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterMatchingType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterOperators(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerData(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function idField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loadMsg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loading(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiSort(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageOptions(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagePosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagination(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowCss(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectionMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function sorts(e: any, t: any, n: any, r: any, i: any, a: any): void;
function striped(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace border {
// Circular reference from rc_easyui.GridBase.propTypes.border
const isRequired: any;
}
namespace clickToEdit {
// Circular reference from rc_easyui.GridBase.propTypes.clickToEdit
const isRequired: any;
}
namespace columnMoving {
// Circular reference from rc_easyui.GridBase.propTypes.columnMoving
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.GridBase.propTypes.data
const isRequired: any;
}
namespace dblclickToEdit {
// Circular reference from rc_easyui.GridBase.propTypes.dblclickToEdit
const isRequired: any;
}
namespace editMode {
// Circular reference from rc_easyui.GridBase.propTypes.editMode
const isRequired: any;
}
namespace filterBtnPosition {
// Circular reference from rc_easyui.GridBase.propTypes.filterBtnPosition
const isRequired: any;
}
namespace filterDelay {
// Circular reference from rc_easyui.GridBase.propTypes.filterDelay
const isRequired: any;
}
namespace filterMatchingType {
// Circular reference from rc_easyui.GridBase.propTypes.filterMatchingType
const isRequired: any;
}
namespace filterOperators {
// Circular reference from rc_easyui.GridBase.propTypes.filterOperators
const isRequired: any;
}
namespace filterPosition {
// Circular reference from rc_easyui.GridBase.propTypes.filterPosition
const isRequired: any;
}
namespace filterRules {
// Circular reference from rc_easyui.GridBase.propTypes.filterRules
const isRequired: any;
}
namespace filterable {
// Circular reference from rc_easyui.GridBase.propTypes.filterable
const isRequired: any;
}
namespace footerData {
// Circular reference from rc_easyui.GridBase.propTypes.footerData
const isRequired: any;
}
namespace frozenAlign {
// Circular reference from rc_easyui.GridBase.propTypes.frozenAlign
const isRequired: any;
}
namespace frozenWidth {
// Circular reference from rc_easyui.GridBase.propTypes.frozenWidth
const isRequired: any;
}
namespace idField {
// Circular reference from rc_easyui.GridBase.propTypes.idField
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.GridBase.propTypes.lazy
const isRequired: any;
}
namespace loadMsg {
// Circular reference from rc_easyui.GridBase.propTypes.loadMsg
const isRequired: any;
}
namespace loading {
// Circular reference from rc_easyui.GridBase.propTypes.loading
const isRequired: any;
}
namespace multiSort {
// Circular reference from rc_easyui.GridBase.propTypes.multiSort
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.GridBase.propTypes.pageNumber
const isRequired: any;
}
namespace pageOptions {
// Circular reference from rc_easyui.GridBase.propTypes.pageOptions
const isRequired: any;
}
namespace pagePosition {
// Circular reference from rc_easyui.GridBase.propTypes.pagePosition
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.GridBase.propTypes.pageSize
const isRequired: any;
}
namespace pagination {
// Circular reference from rc_easyui.GridBase.propTypes.pagination
const isRequired: any;
}
namespace rowCss {
// Circular reference from rc_easyui.GridBase.propTypes.rowCss
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.GridBase.propTypes.rowHeight
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.GridBase.propTypes.selection
const isRequired: any;
}
namespace selectionMode {
// Circular reference from rc_easyui.GridBase.propTypes.selectionMode
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.GridBase.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.GridBase.propTypes.showHeader
const isRequired: any;
}
namespace sorts {
// Circular reference from rc_easyui.GridBase.propTypes.sorts
const isRequired: any;
}
namespace striped {
// Circular reference from rc_easyui.GridBase.propTypes.striped
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.GridBase.propTypes.total
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.GridBase.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace GridColumn {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.GridColumn.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.GridColumn.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function align(e: any, t: any, n: any, r: any, i: any, a: any): void;
function cellCss(e: any, t: any, n: any, r: any, i: any, a: any): void;
function colspan(e: any, t: any, n: any, r: any, i: any, a: any): void;
function defaultFilterOperator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editor(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expander(e: any, t: any, n: any, r: any, i: any, a: any): void;
function field(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterOperators(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozen(e: any, t: any, n: any, r: any, i: any, a: any): void;
function halign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function order(e: any, t: any, n: any, r: any, i: any, a: any): void;
function render(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowspan(e: any, t: any, n: any, r: any, i: any, a: any): void;
function sortable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function sorter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
function width(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace align {
// Circular reference from rc_easyui.GridColumn.propTypes.align
const isRequired: any;
}
namespace cellCss {
// Circular reference from rc_easyui.GridColumn.propTypes.cellCss
const isRequired: any;
}
namespace colspan {
// Circular reference from rc_easyui.GridColumn.propTypes.colspan
const isRequired: any;
}
namespace defaultFilterOperator {
// Circular reference from rc_easyui.GridColumn.propTypes.defaultFilterOperator
const isRequired: any;
}
namespace editRules {
// Circular reference from rc_easyui.GridColumn.propTypes.editRules
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.GridColumn.propTypes.editable
const isRequired: any;
}
namespace editor {
// Circular reference from rc_easyui.GridColumn.propTypes.editor
const isRequired: any;
}
namespace expander {
// Circular reference from rc_easyui.GridColumn.propTypes.expander
const isRequired: any;
}
namespace field {
// Circular reference from rc_easyui.GridColumn.propTypes.field
const isRequired: any;
}
namespace filter {
// Circular reference from rc_easyui.GridColumn.propTypes.filter
const isRequired: any;
}
namespace filterOperators {
// Circular reference from rc_easyui.GridColumn.propTypes.filterOperators
const isRequired: any;
}
namespace filterable {
// Circular reference from rc_easyui.GridColumn.propTypes.filterable
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.GridColumn.propTypes.footer
const isRequired: any;
}
namespace frozen {
// Circular reference from rc_easyui.GridColumn.propTypes.frozen
const isRequired: any;
}
namespace halign {
// Circular reference from rc_easyui.GridColumn.propTypes.halign
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.GridColumn.propTypes.header
const isRequired: any;
}
namespace order {
// Circular reference from rc_easyui.GridColumn.propTypes.order
const isRequired: any;
}
namespace render {
// Circular reference from rc_easyui.GridColumn.propTypes.render
const isRequired: any;
}
namespace rowspan {
// Circular reference from rc_easyui.GridColumn.propTypes.rowspan
const isRequired: any;
}
namespace sortable {
// Circular reference from rc_easyui.GridColumn.propTypes.sortable
const isRequired: any;
}
namespace sorter {
// Circular reference from rc_easyui.GridColumn.propTypes.sorter
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.GridColumn.propTypes.title
const isRequired: any;
}
namespace width {
// Circular reference from rc_easyui.GridColumn.propTypes.width
const isRequired: any;
}
}
}
export namespace GridColumnGroup {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.GridColumnGroup.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.GridColumnGroup.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function align(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozen(e: any, t: any, n: any, r: any, i: any, a: any): void;
function width(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace align {
// Circular reference from rc_easyui.GridColumnGroup.propTypes.align
const isRequired: any;
}
namespace frozen {
// Circular reference from rc_easyui.GridColumnGroup.propTypes.frozen
const isRequired: any;
}
namespace width {
// Circular reference from rc_easyui.GridColumnGroup.propTypes.width
const isRequired: any;
}
}
}
export namespace GridHeaderRow {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.GridHeaderRow.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.GridHeaderRow.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.GridHeaderRow.propTypes.className
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.GridHeaderRow.propTypes.style
const isRequired: any;
}
}
}
export namespace InputBase {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.InputBase.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.InputBase.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.InputBase.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const editable: boolean;
const iconAlign: string;
const invalid: boolean;
const multiline: boolean;
const readOnly: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.InputBase.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.InputBase.propTypes.addonRight
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.InputBase.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.InputBase.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.InputBase.propTypes.editable
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.InputBase.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.InputBase.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.InputBase.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.InputBase.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.InputBase.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.InputBase.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.InputBase.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.InputBase.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.InputBase.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.InputBase.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.InputBase.propTypes.readOnly
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.InputBase.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.InputBase.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.InputBase.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.InputBase.propTypes.value
const isRequired: any;
}
}
}
export namespace Label {
namespace propTypes {
function align(e: any, t: any, n: any, r: any, i: any, a: any): void;
function htmlFor(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace align {
// Circular reference from rc_easyui.Label.propTypes.align
const isRequired: any;
}
namespace htmlFor {
// Circular reference from rc_easyui.Label.propTypes.htmlFor
const isRequired: any;
}
}
}
export namespace Layout {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Layout.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Layout.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
function onPanelResizeStart(e: any): void;
function onPanelResizeStop(e: any): void;
function onPanelResizing(e: any): void;
}
namespace propTypes {
function selectedTab(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace selectedTab {
// Circular reference from rc_easyui.Layout.propTypes.selectedTab
const isRequired: any;
}
}
}
export namespace LayoutPanel {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.LayoutPanel.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.LayoutPanel.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const closable: boolean;
const closeIconCls: string;
const closed: boolean;
const collapseIconCls: any;
const collapsed: boolean;
const collapsedSize: number;
const collapsible: boolean;
const expandIconCls: any;
const expander: boolean;
const region: string;
const showFooter: boolean;
const showHeader: boolean;
const split: boolean;
function onCollapse(): void;
function onExpand(): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapseIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsedSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsible(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expandIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expander(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onCollapse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onExpand(e: any, t: any, n: any, r: any, i: any, a: any): void;
function region(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function split(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.LayoutPanel.propTypes.animate
const isRequired: any;
}
namespace bodyCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.bodyCls
const isRequired: any;
}
namespace bodyStyle {
// Circular reference from rc_easyui.LayoutPanel.propTypes.bodyStyle
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.LayoutPanel.propTypes.border
const isRequired: any;
}
namespace closable {
// Circular reference from rc_easyui.LayoutPanel.propTypes.closable
const isRequired: any;
}
namespace closeIconCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.closeIconCls
const isRequired: any;
}
namespace closed {
// Circular reference from rc_easyui.LayoutPanel.propTypes.closed
const isRequired: any;
}
namespace collapseIconCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.collapseIconCls
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.LayoutPanel.propTypes.collapsed
const isRequired: any;
}
namespace collapsedSize {
// Circular reference from rc_easyui.LayoutPanel.propTypes.collapsedSize
const isRequired: any;
}
namespace collapsible {
// Circular reference from rc_easyui.LayoutPanel.propTypes.collapsible
const isRequired: any;
}
namespace expandIconCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.expandIconCls
const isRequired: any;
}
namespace expander {
// Circular reference from rc_easyui.LayoutPanel.propTypes.expander
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.LayoutPanel.propTypes.footer
const isRequired: any;
}
namespace footerCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.footerCls
const isRequired: any;
}
namespace footerStyle {
// Circular reference from rc_easyui.LayoutPanel.propTypes.footerStyle
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.LayoutPanel.propTypes.header
const isRequired: any;
}
namespace headerCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.headerCls
const isRequired: any;
}
namespace headerStyle {
// Circular reference from rc_easyui.LayoutPanel.propTypes.headerStyle
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.LayoutPanel.propTypes.iconCls
const isRequired: any;
}
namespace onCollapse {
// Circular reference from rc_easyui.LayoutPanel.propTypes.onCollapse
const isRequired: any;
}
namespace onExpand {
// Circular reference from rc_easyui.LayoutPanel.propTypes.onExpand
const isRequired: any;
}
namespace region {
// Circular reference from rc_easyui.LayoutPanel.propTypes.region
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.LayoutPanel.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.LayoutPanel.propTypes.showHeader
const isRequired: any;
}
namespace split {
// Circular reference from rc_easyui.LayoutPanel.propTypes.split
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.LayoutPanel.propTypes.title
const isRequired: any;
}
}
}
export namespace LinkButton {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.LinkButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.LinkButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const iconAlign: string;
const outline: boolean;
const plain: boolean;
const selected: boolean;
const size: string;
const toggle: boolean;
function onClick(): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function href(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onClick(e: any, t: any, n: any, r: any, i: any, a: any): void;
function outline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function plain(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selected(e: any, t: any, n: any, r: any, i: any, a: any): void;
function size(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function text(e: any, t: any, n: any, r: any, i: any, a: any): void;
function toggle(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.LinkButton.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.LinkButton.propTypes.disabled
const isRequired: any;
}
namespace href {
// Circular reference from rc_easyui.LinkButton.propTypes.href
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.LinkButton.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.LinkButton.propTypes.iconCls
const isRequired: any;
}
namespace onClick {
// Circular reference from rc_easyui.LinkButton.propTypes.onClick
const isRequired: any;
}
namespace outline {
// Circular reference from rc_easyui.LinkButton.propTypes.outline
const isRequired: any;
}
namespace plain {
// Circular reference from rc_easyui.LinkButton.propTypes.plain
const isRequired: any;
}
namespace selected {
// Circular reference from rc_easyui.LinkButton.propTypes.selected
const isRequired: any;
}
namespace size {
// Circular reference from rc_easyui.LinkButton.propTypes.size
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.LinkButton.propTypes.style
const isRequired: any;
}
namespace text {
// Circular reference from rc_easyui.LinkButton.propTypes.text
const isRequired: any;
}
namespace toggle {
// Circular reference from rc_easyui.LinkButton.propTypes.toggle
const isRequired: any;
}
}
}
export namespace LocaleBase {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.LocaleBase.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.LocaleBase.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.LocaleBase.propTypes.className
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.LocaleBase.propTypes.style
const isRequired: any;
}
}
}
export namespace LocaleProvider {
namespace childContextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.LocaleProvider.childContextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.LocaleProvider.childContextTypes.t
const isRequired: any;
}
}
}
export namespace MaskedBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.MaskedBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.MaskedBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.MaskedBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const editable: boolean;
const iconAlign: string;
const invalid: boolean;
const masks: {
"*": string;
"9": string;
a: string; };
const multiline: boolean;
const promptChar: string;
const readOnly: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function mask(e: any, t: any, n: any, r: any, i: any, a: any): void;
function masks(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function promptChar(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.MaskedBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.MaskedBox.propTypes.addonRight
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.MaskedBox.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.MaskedBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.MaskedBox.propTypes.editable
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.MaskedBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.MaskedBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.MaskedBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.MaskedBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.MaskedBox.propTypes.inputStyle
const isRequired: any;
}
namespace mask {
// Circular reference from rc_easyui.MaskedBox.propTypes.mask
const isRequired: any;
}
namespace masks {
// Circular reference from rc_easyui.MaskedBox.propTypes.masks
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.MaskedBox.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.MaskedBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.MaskedBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.MaskedBox.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.MaskedBox.propTypes.placeholder
const isRequired: any;
}
namespace promptChar {
// Circular reference from rc_easyui.MaskedBox.propTypes.promptChar
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.MaskedBox.propTypes.readOnly
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.MaskedBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.MaskedBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.MaskedBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.MaskedBox.propTypes.value
const isRequired: any;
}
}
}
export namespace Menu {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Menu.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Menu.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const duration: number;
const inline: boolean;
const noline: boolean;
function onHide(): void;
function onItemClick(e: any): void;
function onShow(): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function duration(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function noline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.Menu.propTypes.className
const isRequired: any;
}
namespace duration {
// Circular reference from rc_easyui.Menu.propTypes.duration
const isRequired: any;
}
namespace inline {
// Circular reference from rc_easyui.Menu.propTypes.inline
const isRequired: any;
}
namespace menuCls {
// Circular reference from rc_easyui.Menu.propTypes.menuCls
const isRequired: any;
}
namespace menuStyle {
// Circular reference from rc_easyui.Menu.propTypes.menuStyle
const isRequired: any;
}
namespace menuWidth {
// Circular reference from rc_easyui.Menu.propTypes.menuWidth
const isRequired: any;
}
namespace noline {
// Circular reference from rc_easyui.Menu.propTypes.noline
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Menu.propTypes.style
const isRequired: any;
}
}
}
export namespace MenuButton {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.MenuButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.MenuButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const duration: number;
const iconAlign: string;
const menuAlign: string;
const outline: boolean;
const plain: boolean;
const selected: boolean;
const size: string;
const toggle: boolean;
function onClick(): void;
function onMenuHide(): void;
function onMenuItemClick(e: any): void;
function onMenuShow(): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function duration(e: any, t: any, n: any, r: any, i: any, a: any): void;
function href(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menu(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onClick(e: any, t: any, n: any, r: any, i: any, a: any): void;
function outline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function plain(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selected(e: any, t: any, n: any, r: any, i: any, a: any): void;
function size(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function text(e: any, t: any, n: any, r: any, i: any, a: any): void;
function toggle(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.MenuButton.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.MenuButton.propTypes.disabled
const isRequired: any;
}
namespace duration {
// Circular reference from rc_easyui.MenuButton.propTypes.duration
const isRequired: any;
}
namespace href {
// Circular reference from rc_easyui.MenuButton.propTypes.href
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.MenuButton.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.MenuButton.propTypes.iconCls
const isRequired: any;
}
namespace menu {
// Circular reference from rc_easyui.MenuButton.propTypes.menu
const isRequired: any;
}
namespace menuAlign {
// Circular reference from rc_easyui.MenuButton.propTypes.menuAlign
const isRequired: any;
}
namespace onClick {
// Circular reference from rc_easyui.MenuButton.propTypes.onClick
const isRequired: any;
}
namespace outline {
// Circular reference from rc_easyui.MenuButton.propTypes.outline
const isRequired: any;
}
namespace plain {
// Circular reference from rc_easyui.MenuButton.propTypes.plain
const isRequired: any;
}
namespace selected {
// Circular reference from rc_easyui.MenuButton.propTypes.selected
const isRequired: any;
}
namespace size {
// Circular reference from rc_easyui.MenuButton.propTypes.size
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.MenuButton.propTypes.style
const isRequired: any;
}
namespace text {
// Circular reference from rc_easyui.MenuButton.propTypes.text
const isRequired: any;
}
namespace toggle {
// Circular reference from rc_easyui.MenuButton.propTypes.toggle
const isRequired: any;
}
}
}
export namespace MenuItem {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.MenuItem.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.MenuItem.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function text(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.MenuItem.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.MenuItem.propTypes.disabled
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.MenuItem.propTypes.iconCls
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.MenuItem.propTypes.style
const isRequired: any;
}
namespace text {
// Circular reference from rc_easyui.MenuItem.propTypes.text
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.MenuItem.propTypes.value
const isRequired: any;
}
}
}
export namespace Messager {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Messager.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Messager.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function buttons(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function content(e: any, t: any, n: any, r: any, i: any, a: any): void;
function icon(e: any, t: any, n: any, r: any, i: any, a: any): void;
function messagerType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function msg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace buttons {
// Circular reference from rc_easyui.Messager.propTypes.buttons
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.Messager.propTypes.className
const isRequired: any;
}
namespace content {
// Circular reference from rc_easyui.Messager.propTypes.content
const isRequired: any;
}
namespace icon {
// Circular reference from rc_easyui.Messager.propTypes.icon
const isRequired: any;
}
namespace messagerType {
// Circular reference from rc_easyui.Messager.propTypes.messagerType
const isRequired: any;
}
namespace msg {
// Circular reference from rc_easyui.Messager.propTypes.msg
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Messager.propTypes.style
const isRequired: any;
}
}
}
export namespace NumberBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.NumberBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.NumberBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.NumberBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const decimalSeparator: string;
const disabled: boolean;
const editable: boolean;
const groupSeparator: string;
const iconAlign: string;
const increment: number;
const invalid: boolean;
const multiline: boolean;
const precision: number;
const prefix: string;
const readOnly: boolean;
const reversed: boolean;
const spinAlign: string;
const spinners: boolean;
const suffix: string;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function decimalSeparator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function groupSeparator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function increment(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function max(e: any, t: any, n: any, r: any, i: any, a: any): void;
function min(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function precision(e: any, t: any, n: any, r: any, i: any, a: any): void;
function prefix(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function reversed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinners(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function suffix(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.NumberBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.NumberBox.propTypes.addonRight
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.NumberBox.propTypes.className
const isRequired: any;
}
namespace decimalSeparator {
// Circular reference from rc_easyui.NumberBox.propTypes.decimalSeparator
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.NumberBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.NumberBox.propTypes.editable
const isRequired: any;
}
namespace groupSeparator {
// Circular reference from rc_easyui.NumberBox.propTypes.groupSeparator
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.NumberBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.NumberBox.propTypes.iconCls
const isRequired: any;
}
namespace increment {
// Circular reference from rc_easyui.NumberBox.propTypes.increment
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.NumberBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.NumberBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.NumberBox.propTypes.inputStyle
const isRequired: any;
}
namespace max {
// Circular reference from rc_easyui.NumberBox.propTypes.max
const isRequired: any;
}
namespace min {
// Circular reference from rc_easyui.NumberBox.propTypes.min
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.NumberBox.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.NumberBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.NumberBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.NumberBox.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.NumberBox.propTypes.placeholder
const isRequired: any;
}
namespace precision {
// Circular reference from rc_easyui.NumberBox.propTypes.precision
const isRequired: any;
}
namespace prefix {
// Circular reference from rc_easyui.NumberBox.propTypes.prefix
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.NumberBox.propTypes.readOnly
const isRequired: any;
}
namespace reversed {
// Circular reference from rc_easyui.NumberBox.propTypes.reversed
const isRequired: any;
}
namespace spinAlign {
// Circular reference from rc_easyui.NumberBox.propTypes.spinAlign
const isRequired: any;
}
namespace spinners {
// Circular reference from rc_easyui.NumberBox.propTypes.spinners
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.NumberBox.propTypes.style
const isRequired: any;
}
namespace suffix {
// Circular reference from rc_easyui.NumberBox.propTypes.suffix
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.NumberBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.NumberBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.NumberBox.propTypes.value
const isRequired: any;
}
}
}
export namespace Pagination {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Pagination.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Pagination.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const defaultAfterPageText: string;
const defaultBeforePageText: string;
const defaultDisplayMsg: string;
const layout: string[];
const links: number;
const loading: boolean;
const pageList: number[];
const pageNumber: number;
const pageSize: number;
const showPageInfo: boolean;
const showPageList: boolean;
const showPageRefresh: boolean;
const total: number;
function onPageChange(): void;
}
namespace propTypes {
function afterPageText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function beforePageText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function displayMsg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function layout(e: any, t: any, n: any, r: any, i: any, a: any): void;
function links(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loading(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onPageChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageList(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderExt(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showPageInfo(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showPageList(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showPageRefresh(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace afterPageText {
// Circular reference from rc_easyui.Pagination.propTypes.afterPageText
const isRequired: any;
}
namespace beforePageText {
// Circular reference from rc_easyui.Pagination.propTypes.beforePageText
const isRequired: any;
}
namespace displayMsg {
// Circular reference from rc_easyui.Pagination.propTypes.displayMsg
const isRequired: any;
}
namespace layout {
// Circular reference from rc_easyui.Pagination.propTypes.layout
const isRequired: any;
}
namespace links {
// Circular reference from rc_easyui.Pagination.propTypes.links
const isRequired: any;
}
namespace loading {
// Circular reference from rc_easyui.Pagination.propTypes.loading
const isRequired: any;
}
namespace onPageChange {
// Circular reference from rc_easyui.Pagination.propTypes.onPageChange
const isRequired: any;
}
namespace pageList {
// Circular reference from rc_easyui.Pagination.propTypes.pageList
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.Pagination.propTypes.pageNumber
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.Pagination.propTypes.pageSize
const isRequired: any;
}
namespace renderExt {
// Circular reference from rc_easyui.Pagination.propTypes.renderExt
const isRequired: any;
}
namespace showPageInfo {
// Circular reference from rc_easyui.Pagination.propTypes.showPageInfo
const isRequired: any;
}
namespace showPageList {
// Circular reference from rc_easyui.Pagination.propTypes.showPageList
const isRequired: any;
}
namespace showPageRefresh {
// Circular reference from rc_easyui.Pagination.propTypes.showPageRefresh
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.Pagination.propTypes.total
const isRequired: any;
}
}
}
export namespace Panel {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Panel.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Panel.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const closable: boolean;
const closeIconCls: string;
const closed: boolean;
const collapseIconCls: string;
const collapsed: boolean;
const collapsible: boolean;
const expandIconCls: string;
const showFooter: boolean;
const showHeader: boolean;
function onCollapse(): void;
function onExpand(): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapseIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsible(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expandIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onCollapse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onExpand(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.Panel.propTypes.animate
const isRequired: any;
}
namespace bodyCls {
// Circular reference from rc_easyui.Panel.propTypes.bodyCls
const isRequired: any;
}
namespace bodyStyle {
// Circular reference from rc_easyui.Panel.propTypes.bodyStyle
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.Panel.propTypes.border
const isRequired: any;
}
namespace closable {
// Circular reference from rc_easyui.Panel.propTypes.closable
const isRequired: any;
}
namespace closeIconCls {
// Circular reference from rc_easyui.Panel.propTypes.closeIconCls
const isRequired: any;
}
namespace closed {
// Circular reference from rc_easyui.Panel.propTypes.closed
const isRequired: any;
}
namespace collapseIconCls {
// Circular reference from rc_easyui.Panel.propTypes.collapseIconCls
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.Panel.propTypes.collapsed
const isRequired: any;
}
namespace collapsible {
// Circular reference from rc_easyui.Panel.propTypes.collapsible
const isRequired: any;
}
namespace expandIconCls {
// Circular reference from rc_easyui.Panel.propTypes.expandIconCls
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.Panel.propTypes.footer
const isRequired: any;
}
namespace footerCls {
// Circular reference from rc_easyui.Panel.propTypes.footerCls
const isRequired: any;
}
namespace footerStyle {
// Circular reference from rc_easyui.Panel.propTypes.footerStyle
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.Panel.propTypes.header
const isRequired: any;
}
namespace headerCls {
// Circular reference from rc_easyui.Panel.propTypes.headerCls
const isRequired: any;
}
namespace headerStyle {
// Circular reference from rc_easyui.Panel.propTypes.headerStyle
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.Panel.propTypes.iconCls
const isRequired: any;
}
namespace onCollapse {
// Circular reference from rc_easyui.Panel.propTypes.onCollapse
const isRequired: any;
}
namespace onExpand {
// Circular reference from rc_easyui.Panel.propTypes.onExpand
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.Panel.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.Panel.propTypes.showHeader
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.Panel.propTypes.title
const isRequired: any;
}
}
}
export namespace PasswordBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.PasswordBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.PasswordBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.PasswordBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const checkInterval: number;
const disabled: boolean;
const editable: boolean;
const eyeAlign: string;
const iconAlign: string;
const invalid: boolean;
const lastDelay: number;
const multiline: boolean;
const passwordChar: string;
const readOnly: boolean;
const revealed: boolean;
const showEye: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function checkInterval(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function eyeAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lastDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function passwordChar(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function revealed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showEye(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.PasswordBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.PasswordBox.propTypes.addonRight
const isRequired: any;
}
namespace checkInterval {
// Circular reference from rc_easyui.PasswordBox.propTypes.checkInterval
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.PasswordBox.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.PasswordBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.PasswordBox.propTypes.editable
const isRequired: any;
}
namespace eyeAlign {
// Circular reference from rc_easyui.PasswordBox.propTypes.eyeAlign
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.PasswordBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.PasswordBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.PasswordBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.PasswordBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.PasswordBox.propTypes.inputStyle
const isRequired: any;
}
namespace lastDelay {
// Circular reference from rc_easyui.PasswordBox.propTypes.lastDelay
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.PasswordBox.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.PasswordBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.PasswordBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.PasswordBox.propTypes.onFocus
const isRequired: any;
}
namespace passwordChar {
// Circular reference from rc_easyui.PasswordBox.propTypes.passwordChar
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.PasswordBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.PasswordBox.propTypes.readOnly
const isRequired: any;
}
namespace revealed {
// Circular reference from rc_easyui.PasswordBox.propTypes.revealed
const isRequired: any;
}
namespace showEye {
// Circular reference from rc_easyui.PasswordBox.propTypes.showEye
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.PasswordBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.PasswordBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.PasswordBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.PasswordBox.propTypes.value
const isRequired: any;
}
}
}
export namespace ProgressBar {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.ProgressBar.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.ProgressBar.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function barCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function barStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showValue(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace barCls {
// Circular reference from rc_easyui.ProgressBar.propTypes.barCls
const isRequired: any;
}
namespace barStyle {
// Circular reference from rc_easyui.ProgressBar.propTypes.barStyle
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.ProgressBar.propTypes.className
const isRequired: any;
}
namespace showValue {
// Circular reference from rc_easyui.ProgressBar.propTypes.showValue
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.ProgressBar.propTypes.style
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.ProgressBar.propTypes.value
const isRequired: any;
}
}
}
export namespace RadioButton {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.RadioButton.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.RadioButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.RadioButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
function onChange(e: any): void;
}
namespace propTypes {
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function groupValue(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace disabled {
// Circular reference from rc_easyui.RadioButton.propTypes.disabled
const isRequired: any;
}
namespace groupValue {
// Circular reference from rc_easyui.RadioButton.propTypes.groupValue
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.RadioButton.propTypes.inputId
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.RadioButton.propTypes.onChange
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.RadioButton.propTypes.value
const isRequired: any;
}
}
}
export namespace Resizable {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Resizable.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Resizable.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const edge: number;
const handles: string;
const maxHeight: number;
const maxWidth: number;
const minHeight: number;
const minWidth: number;
function onResizeStart(e: any): void;
function onResizeStop(e: any): void;
function onResizing(e: any): void;
}
namespace propTypes {
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function edge(e: any, t: any, n: any, r: any, i: any, a: any): void;
function handles(e: any, t: any, n: any, r: any, i: any, a: any): void;
function maxHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function maxWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function minHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function minWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onResizeStart(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onResizeStop(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onResizing(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace disabled {
// Circular reference from rc_easyui.Resizable.propTypes.disabled
const isRequired: any;
}
namespace edge {
// Circular reference from rc_easyui.Resizable.propTypes.edge
const isRequired: any;
}
namespace handles {
// Circular reference from rc_easyui.Resizable.propTypes.handles
const isRequired: any;
}
namespace maxHeight {
// Circular reference from rc_easyui.Resizable.propTypes.maxHeight
const isRequired: any;
}
namespace maxWidth {
// Circular reference from rc_easyui.Resizable.propTypes.maxWidth
const isRequired: any;
}
namespace minHeight {
// Circular reference from rc_easyui.Resizable.propTypes.minHeight
const isRequired: any;
}
namespace minWidth {
// Circular reference from rc_easyui.Resizable.propTypes.minWidth
const isRequired: any;
}
namespace onResizeStart {
// Circular reference from rc_easyui.Resizable.propTypes.onResizeStart
const isRequired: any;
}
namespace onResizeStop {
// Circular reference from rc_easyui.Resizable.propTypes.onResizeStop
const isRequired: any;
}
namespace onResizing {
// Circular reference from rc_easyui.Resizable.propTypes.onResizing
const isRequired: any;
}
}
}
export namespace SearchBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.SearchBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.SearchBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.SearchBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const buttonAlign: string;
const buttonIconCls: string;
const categories: any[];
const disabled: boolean;
const editable: boolean;
const iconAlign: string;
const invalid: boolean;
const menuAlign: string;
const multiline: boolean;
const readOnly: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function onSearch(e: any): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function buttonAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function buttonIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function categories(e: any, t: any, n: any, r: any, i: any, a: any): void;
function category(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onSearch(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.SearchBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.SearchBox.propTypes.addonRight
const isRequired: any;
}
namespace buttonAlign {
// Circular reference from rc_easyui.SearchBox.propTypes.buttonAlign
const isRequired: any;
}
namespace buttonIconCls {
// Circular reference from rc_easyui.SearchBox.propTypes.buttonIconCls
const isRequired: any;
}
namespace categories {
// Circular reference from rc_easyui.SearchBox.propTypes.categories
const isRequired: any;
}
namespace category {
// Circular reference from rc_easyui.SearchBox.propTypes.category
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.SearchBox.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.SearchBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.SearchBox.propTypes.editable
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.SearchBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.SearchBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.SearchBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.SearchBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.SearchBox.propTypes.inputStyle
const isRequired: any;
}
namespace menuAlign {
// Circular reference from rc_easyui.SearchBox.propTypes.menuAlign
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.SearchBox.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.SearchBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.SearchBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.SearchBox.propTypes.onFocus
const isRequired: any;
}
namespace onSearch {
// Circular reference from rc_easyui.SearchBox.propTypes.onSearch
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.SearchBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.SearchBox.propTypes.readOnly
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.SearchBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.SearchBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.SearchBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.SearchBox.propTypes.value
const isRequired: any;
}
}
}
export namespace SideMenu {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.SideMenu.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.SideMenu.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const collapsed: boolean;
const floatMenuPosition: string;
const floatMenuWidth: number;
const multiple: boolean;
const showCollapsedText: boolean;
function onItemClick(e: any): void;
function onSelectionChange(e: any): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsedCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function floatMenuPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function floatMenuWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showCollapsedText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.SideMenu.propTypes.animate
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.SideMenu.propTypes.border
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.SideMenu.propTypes.className
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.SideMenu.propTypes.collapsed
const isRequired: any;
}
namespace collapsedCls {
// Circular reference from rc_easyui.SideMenu.propTypes.collapsedCls
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.SideMenu.propTypes.data
const isRequired: any;
}
namespace floatMenuPosition {
// Circular reference from rc_easyui.SideMenu.propTypes.floatMenuPosition
const isRequired: any;
}
namespace floatMenuWidth {
// Circular reference from rc_easyui.SideMenu.propTypes.floatMenuWidth
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.SideMenu.propTypes.multiple
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.SideMenu.propTypes.selection
const isRequired: any;
}
namespace showCollapsedText {
// Circular reference from rc_easyui.SideMenu.propTypes.showCollapsedText
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.SideMenu.propTypes.style
const isRequired: any;
}
}
}
export namespace Slider {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.Slider.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.Slider.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.Slider.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.Slider.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.Slider.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.Slider.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.Slider.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Slider.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const invalid: boolean;
const max: number;
const min: number;
const mode: string;
const range: boolean;
const reversed: boolean;
const rule: any[];
const showTip: boolean;
const step: number;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
function onChange(e: any): void;
}
namespace propTypes {
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function invalid(e: any, t: any, n: any, r: any, i: any, a: any): void;
function max(e: any, t: any, n: any, r: any, i: any, a: any): void;
function min(e: any, t: any, n: any, r: any, i: any, a: any): void;
function mode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function name(e: any, t: any, n: any, r: any, i: any, a: any): void;
function range(e: any, t: any, n: any, r: any, i: any, a: any): void;
function reversed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rule(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showTip(e: any, t: any, n: any, r: any, i: any, a: any): void;
function step(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnCreate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace disabled {
// Circular reference from rc_easyui.Slider.propTypes.disabled
const isRequired: any;
}
namespace invalid {
// Circular reference from rc_easyui.Slider.propTypes.invalid
const isRequired: any;
}
namespace max {
// Circular reference from rc_easyui.Slider.propTypes.max
const isRequired: any;
}
namespace min {
// Circular reference from rc_easyui.Slider.propTypes.min
const isRequired: any;
}
namespace mode {
// Circular reference from rc_easyui.Slider.propTypes.mode
const isRequired: any;
}
namespace name {
// Circular reference from rc_easyui.Slider.propTypes.name
const isRequired: any;
}
namespace range {
// Circular reference from rc_easyui.Slider.propTypes.range
const isRequired: any;
}
namespace reversed {
// Circular reference from rc_easyui.Slider.propTypes.reversed
const isRequired: any;
}
namespace rule {
// Circular reference from rc_easyui.Slider.propTypes.rule
const isRequired: any;
}
namespace showTip {
// Circular reference from rc_easyui.Slider.propTypes.showTip
const isRequired: any;
}
namespace step {
// Circular reference from rc_easyui.Slider.propTypes.step
const isRequired: any;
}
namespace validateOnBlur {
// Circular reference from rc_easyui.Slider.propTypes.validateOnBlur
const isRequired: any;
}
namespace validateOnChange {
// Circular reference from rc_easyui.Slider.propTypes.validateOnChange
const isRequired: any;
}
namespace validateOnCreate {
// Circular reference from rc_easyui.Slider.propTypes.validateOnCreate
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.Slider.propTypes.value
const isRequired: any;
}
}
}
export namespace SplitButton {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.SplitButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.SplitButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const duration: number;
const iconAlign: string;
const menuAlign: string;
const outline: boolean;
const plain: boolean;
const selected: boolean;
const size: string;
const toggle: boolean;
function onClick(): void;
function onMenuHide(): void;
function onMenuItemClick(e: any): void;
function onMenuShow(): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function duration(e: any, t: any, n: any, r: any, i: any, a: any): void;
function href(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menu(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onClick(e: any, t: any, n: any, r: any, i: any, a: any): void;
function outline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function plain(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selected(e: any, t: any, n: any, r: any, i: any, a: any): void;
function size(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function text(e: any, t: any, n: any, r: any, i: any, a: any): void;
function toggle(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.SplitButton.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.SplitButton.propTypes.disabled
const isRequired: any;
}
namespace duration {
// Circular reference from rc_easyui.SplitButton.propTypes.duration
const isRequired: any;
}
namespace href {
// Circular reference from rc_easyui.SplitButton.propTypes.href
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.SplitButton.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.SplitButton.propTypes.iconCls
const isRequired: any;
}
namespace menu {
// Circular reference from rc_easyui.SplitButton.propTypes.menu
const isRequired: any;
}
namespace menuAlign {
// Circular reference from rc_easyui.SplitButton.propTypes.menuAlign
const isRequired: any;
}
namespace onClick {
// Circular reference from rc_easyui.SplitButton.propTypes.onClick
const isRequired: any;
}
namespace outline {
// Circular reference from rc_easyui.SplitButton.propTypes.outline
const isRequired: any;
}
namespace plain {
// Circular reference from rc_easyui.SplitButton.propTypes.plain
const isRequired: any;
}
namespace selected {
// Circular reference from rc_easyui.SplitButton.propTypes.selected
const isRequired: any;
}
namespace size {
// Circular reference from rc_easyui.SplitButton.propTypes.size
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.SplitButton.propTypes.style
const isRequired: any;
}
namespace text {
// Circular reference from rc_easyui.SplitButton.propTypes.text
const isRequired: any;
}
namespace toggle {
// Circular reference from rc_easyui.SplitButton.propTypes.toggle
const isRequired: any;
}
}
}
export namespace SubMenu {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.SubMenu.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.SubMenu.contextTypes.t
const isRequired: any;
}
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function menuWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.SubMenu.propTypes.className
const isRequired: any;
}
namespace menuCls {
// Circular reference from rc_easyui.SubMenu.propTypes.menuCls
const isRequired: any;
}
namespace menuStyle {
// Circular reference from rc_easyui.SubMenu.propTypes.menuStyle
const isRequired: any;
}
namespace menuWidth {
// Circular reference from rc_easyui.SubMenu.propTypes.menuWidth
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.SubMenu.propTypes.style
const isRequired: any;
}
}
}
export namespace SwitchButton {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.SwitchButton.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.SwitchButton.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.SwitchButton.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const invalid: boolean;
const offText: string;
const onText: string;
const readonly: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
function onChange(e: any): void;
}
namespace propTypes {
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function handleText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function invalid(e: any, t: any, n: any, r: any, i: any, a: any): void;
function name(e: any, t: any, n: any, r: any, i: any, a: any): void;
function offText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onText(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readonly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnCreate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace disabled {
// Circular reference from rc_easyui.SwitchButton.propTypes.disabled
const isRequired: any;
}
namespace handleText {
// Circular reference from rc_easyui.SwitchButton.propTypes.handleText
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.SwitchButton.propTypes.inputId
const isRequired: any;
}
namespace invalid {
// Circular reference from rc_easyui.SwitchButton.propTypes.invalid
const isRequired: any;
}
namespace name {
// Circular reference from rc_easyui.SwitchButton.propTypes.name
const isRequired: any;
}
namespace offText {
// Circular reference from rc_easyui.SwitchButton.propTypes.offText
const isRequired: any;
}
namespace onText {
// Circular reference from rc_easyui.SwitchButton.propTypes.onText
const isRequired: any;
}
namespace readonly {
// Circular reference from rc_easyui.SwitchButton.propTypes.readonly
const isRequired: any;
}
namespace validateOnBlur {
// Circular reference from rc_easyui.SwitchButton.propTypes.validateOnBlur
const isRequired: any;
}
namespace validateOnChange {
// Circular reference from rc_easyui.SwitchButton.propTypes.validateOnChange
const isRequired: any;
}
namespace validateOnCreate {
// Circular reference from rc_easyui.SwitchButton.propTypes.validateOnCreate
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.SwitchButton.propTypes.value
const isRequired: any;
}
}
}
export namespace TabPanel {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.TabPanel.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TabPanel.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const closable: boolean;
const closeIconCls: string;
const closed: boolean;
const collapseIconCls: string;
const collapsed: boolean;
const collapsible: boolean;
const disabled: boolean;
const expandIconCls: string;
const selected: boolean;
const showFooter: boolean;
const showHeader: boolean;
function onCollapse(): void;
function onExpand(): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function bodyStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closeIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function closed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapseIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function collapsible(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function expandIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footer(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function header(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onCollapse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onExpand(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selected(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function title(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.TabPanel.propTypes.animate
const isRequired: any;
}
namespace bodyCls {
// Circular reference from rc_easyui.TabPanel.propTypes.bodyCls
const isRequired: any;
}
namespace bodyStyle {
// Circular reference from rc_easyui.TabPanel.propTypes.bodyStyle
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.TabPanel.propTypes.border
const isRequired: any;
}
namespace closable {
// Circular reference from rc_easyui.TabPanel.propTypes.closable
const isRequired: any;
}
namespace closeIconCls {
// Circular reference from rc_easyui.TabPanel.propTypes.closeIconCls
const isRequired: any;
}
namespace closed {
// Circular reference from rc_easyui.TabPanel.propTypes.closed
const isRequired: any;
}
namespace collapseIconCls {
// Circular reference from rc_easyui.TabPanel.propTypes.collapseIconCls
const isRequired: any;
}
namespace collapsed {
// Circular reference from rc_easyui.TabPanel.propTypes.collapsed
const isRequired: any;
}
namespace collapsible {
// Circular reference from rc_easyui.TabPanel.propTypes.collapsible
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.TabPanel.propTypes.disabled
const isRequired: any;
}
namespace expandIconCls {
// Circular reference from rc_easyui.TabPanel.propTypes.expandIconCls
const isRequired: any;
}
namespace footer {
// Circular reference from rc_easyui.TabPanel.propTypes.footer
const isRequired: any;
}
namespace footerCls {
// Circular reference from rc_easyui.TabPanel.propTypes.footerCls
const isRequired: any;
}
namespace footerStyle {
// Circular reference from rc_easyui.TabPanel.propTypes.footerStyle
const isRequired: any;
}
namespace header {
// Circular reference from rc_easyui.TabPanel.propTypes.header
const isRequired: any;
}
namespace headerCls {
// Circular reference from rc_easyui.TabPanel.propTypes.headerCls
const isRequired: any;
}
namespace headerStyle {
// Circular reference from rc_easyui.TabPanel.propTypes.headerStyle
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.TabPanel.propTypes.iconCls
const isRequired: any;
}
namespace onCollapse {
// Circular reference from rc_easyui.TabPanel.propTypes.onCollapse
const isRequired: any;
}
namespace onExpand {
// Circular reference from rc_easyui.TabPanel.propTypes.onExpand
const isRequired: any;
}
namespace selected {
// Circular reference from rc_easyui.TabPanel.propTypes.selected
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.TabPanel.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.TabPanel.propTypes.showHeader
const isRequired: any;
}
namespace title {
// Circular reference from rc_easyui.TabPanel.propTypes.title
const isRequired: any;
}
}
}
export namespace Tabs {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Tabs.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Tabs.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const border: boolean;
const headerHeight: number;
const headerWidth: number;
const justified: boolean;
const narrow: boolean;
const plain: boolean;
const scrollIncrement: number;
const scrollable: boolean;
const selectedIndex: number;
const tabHeight: number;
const tabPosition: string;
function onTabClose(e: any): void;
function onTabSelect(e: any): void;
function onTabUnselect(e: any): void;
}
namespace propTypes {
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function headerWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function justified(e: any, t: any, n: any, r: any, i: any, a: any): void;
function narrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function plain(e: any, t: any, n: any, r: any, i: any, a: any): void;
function scrollIncrement(e: any, t: any, n: any, r: any, i: any, a: any): void;
function scrollable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectedIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace border {
// Circular reference from rc_easyui.Tabs.propTypes.border
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.Tabs.propTypes.className
const isRequired: any;
}
namespace headerHeight {
// Circular reference from rc_easyui.Tabs.propTypes.headerHeight
const isRequired: any;
}
namespace headerWidth {
// Circular reference from rc_easyui.Tabs.propTypes.headerWidth
const isRequired: any;
}
namespace justified {
// Circular reference from rc_easyui.Tabs.propTypes.justified
const isRequired: any;
}
namespace narrow {
// Circular reference from rc_easyui.Tabs.propTypes.narrow
const isRequired: any;
}
namespace plain {
// Circular reference from rc_easyui.Tabs.propTypes.plain
const isRequired: any;
}
namespace scrollIncrement {
// Circular reference from rc_easyui.Tabs.propTypes.scrollIncrement
const isRequired: any;
}
namespace scrollable {
// Circular reference from rc_easyui.Tabs.propTypes.scrollable
const isRequired: any;
}
namespace selectedIndex {
// Circular reference from rc_easyui.Tabs.propTypes.selectedIndex
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Tabs.propTypes.style
const isRequired: any;
}
namespace tabHeight {
// Circular reference from rc_easyui.Tabs.propTypes.tabHeight
const isRequired: any;
}
namespace tabPosition {
// Circular reference from rc_easyui.Tabs.propTypes.tabPosition
const isRequired: any;
}
namespace tabWidth {
// Circular reference from rc_easyui.Tabs.propTypes.tabWidth
const isRequired: any;
}
}
}
export namespace TagBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.TagBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.TagBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TagBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const arrowAlign: string;
const arrowIconCls: string;
const data: any[];
const delay: number;
const disabled: boolean;
const editable: boolean;
const hasDownArrow: boolean;
const iconAlign: string;
const invalid: boolean;
const lazy: boolean;
const limitToList: boolean;
const multiline: boolean;
const multiple: boolean;
const pageNumber: number;
const pageSize: number;
const panelAlign: string;
const readOnly: boolean;
const rowHeight: number;
const separator: string;
const textField: string;
const total: number;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
const valueField: string;
const virtualScroll: boolean;
function filter(e: any, t: any): any;
function onBlur(): void;
function onChange(e: any): void;
function onFilterChange(e: any): void;
function onFocus(): void;
function onSelectionChange(e: any): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function groupField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function limitToList(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderItem(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tagCss(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
function valueField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.TagBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.TagBox.propTypes.addonRight
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.TagBox.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.TagBox.propTypes.arrowIconCls
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.TagBox.propTypes.className
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.TagBox.propTypes.data
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.TagBox.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.TagBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.TagBox.propTypes.editable
const isRequired: any;
}
namespace filter {
// Circular reference from rc_easyui.TagBox.propTypes.filter
const isRequired: any;
}
namespace groupField {
// Circular reference from rc_easyui.TagBox.propTypes.groupField
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.TagBox.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.TagBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.TagBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.TagBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.TagBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.TagBox.propTypes.inputStyle
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.TagBox.propTypes.lazy
const isRequired: any;
}
namespace limitToList {
// Circular reference from rc_easyui.TagBox.propTypes.limitToList
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.TagBox.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.TagBox.propTypes.multiple
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.TagBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.TagBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.TagBox.propTypes.onFocus
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.TagBox.propTypes.pageNumber
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.TagBox.propTypes.pageSize
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.TagBox.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.TagBox.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.TagBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.TagBox.propTypes.readOnly
const isRequired: any;
}
namespace renderItem {
// Circular reference from rc_easyui.TagBox.propTypes.renderItem
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.TagBox.propTypes.rowHeight
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.TagBox.propTypes.separator
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.TagBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.TagBox.propTypes.tabIndex
const isRequired: any;
}
namespace tagCss {
// Circular reference from rc_easyui.TagBox.propTypes.tagCss
const isRequired: any;
}
namespace textField {
// Circular reference from rc_easyui.TagBox.propTypes.textField
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.TagBox.propTypes.textFormatter
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.TagBox.propTypes.total
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.TagBox.propTypes.value
const isRequired: any;
}
namespace valueField {
// Circular reference from rc_easyui.TagBox.propTypes.valueField
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.TagBox.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace TextBox {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.TextBox.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.TextBox.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TextBox.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const disabled: boolean;
const editable: boolean;
const iconAlign: string;
const invalid: boolean;
const multiline: boolean;
const readOnly: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.TextBox.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.TextBox.propTypes.addonRight
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.TextBox.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.TextBox.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.TextBox.propTypes.editable
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.TextBox.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.TextBox.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.TextBox.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.TextBox.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.TextBox.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.TextBox.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.TextBox.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.TextBox.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.TextBox.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.TextBox.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.TextBox.propTypes.readOnly
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.TextBox.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.TextBox.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.TextBox.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.TextBox.propTypes.value
const isRequired: any;
}
}
}
export namespace TextEditor {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.TextEditor.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.TextEditor.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TextEditor.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
}
namespace propTypes {
function invalid(e: any, t: any, n: any, r: any, i: any, a: any): void;
function name(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateOnCreate(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace invalid {
// Circular reference from rc_easyui.TextEditor.propTypes.invalid
const isRequired: any;
}
namespace name {
// Circular reference from rc_easyui.TextEditor.propTypes.name
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.TextEditor.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.TextEditor.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.TextEditor.propTypes.onFocus
const isRequired: any;
}
namespace validateOnBlur {
// Circular reference from rc_easyui.TextEditor.propTypes.validateOnBlur
const isRequired: any;
}
namespace validateOnChange {
// Circular reference from rc_easyui.TextEditor.propTypes.validateOnChange
const isRequired: any;
}
namespace validateOnCreate {
// Circular reference from rc_easyui.TextEditor.propTypes.validateOnCreate
const isRequired: any;
}
}
}
export namespace TimePicker {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.TimePicker.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.TimePicker.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TimePicker.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const ampm: string[];
const arrowAlign: string;
const arrowIconCls: string;
const defaultCloseText: string;
const defaultOkText: string;
const delay: number;
const disabled: boolean;
const editable: boolean;
const hasDownArrow: boolean;
const iconAlign: string;
const invalid: boolean;
const multiline: boolean;
const multiple: boolean;
const panelAlign: string;
const readOnly: boolean;
const separator: string;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function ampm(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function arrowIconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hasDownArrow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiple(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function panelStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function separator(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.TimePicker.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.TimePicker.propTypes.addonRight
const isRequired: any;
}
namespace ampm {
// Circular reference from rc_easyui.TimePicker.propTypes.ampm
const isRequired: any;
}
namespace arrowAlign {
// Circular reference from rc_easyui.TimePicker.propTypes.arrowAlign
const isRequired: any;
}
namespace arrowIconCls {
// Circular reference from rc_easyui.TimePicker.propTypes.arrowIconCls
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.TimePicker.propTypes.className
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.TimePicker.propTypes.delay
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.TimePicker.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.TimePicker.propTypes.editable
const isRequired: any;
}
namespace hasDownArrow {
// Circular reference from rc_easyui.TimePicker.propTypes.hasDownArrow
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.TimePicker.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.TimePicker.propTypes.iconCls
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.TimePicker.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.TimePicker.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.TimePicker.propTypes.inputStyle
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.TimePicker.propTypes.multiline
const isRequired: any;
}
namespace multiple {
// Circular reference from rc_easyui.TimePicker.propTypes.multiple
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.TimePicker.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.TimePicker.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.TimePicker.propTypes.onFocus
const isRequired: any;
}
namespace panelAlign {
// Circular reference from rc_easyui.TimePicker.propTypes.panelAlign
const isRequired: any;
}
namespace panelStyle {
// Circular reference from rc_easyui.TimePicker.propTypes.panelStyle
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.TimePicker.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.TimePicker.propTypes.readOnly
const isRequired: any;
}
namespace separator {
// Circular reference from rc_easyui.TimePicker.propTypes.separator
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.TimePicker.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.TimePicker.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.TimePicker.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.TimePicker.propTypes.value
const isRequired: any;
}
}
}
export namespace TimeSpinner {
namespace contextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.fieldRemove
const isRequired: any;
}
namespace locale {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TimeSpinner.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const ampm: string[];
const disabled: boolean;
const editable: boolean;
const format: string;
const highlight: number;
const iconAlign: string;
const increment: number;
const invalid: boolean;
const multiline: boolean;
const readOnly: boolean;
const reversed: boolean;
const selections: Array<(number[])>;
const spinAlign: string;
const spinners: boolean;
const validateOnBlur: boolean;
const validateOnChange: boolean;
const validateOnCreate: boolean;
const value: any;
function onBlur(): void;
function onChange(e: any): void;
function onFocus(): void;
function textFormatter(e: any): any;
}
namespace propTypes {
function addonLeft(e: any, t: any, n: any, r: any, i: any, a: any): void;
function addonRight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function ampm(e: any, t: any, n: any, r: any, i: any, a: any): void;
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function format(e: any, t: any, n: any, r: any, i: any, a: any): void;
function highlight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function iconCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function increment(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputId(e: any, t: any, n: any, r: any, i: any, a: any): void;
function inputStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function max(e: any, t: any, n: any, r: any, i: any, a: any): void;
function min(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiline(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function placeholder(e: any, t: any, n: any, r: any, i: any, a: any): void;
function readOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function reversed(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selections(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function spinners(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tabIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
function textFormatter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function value(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace addonLeft {
// Circular reference from rc_easyui.TimeSpinner.propTypes.addonLeft
const isRequired: any;
}
namespace addonRight {
// Circular reference from rc_easyui.TimeSpinner.propTypes.addonRight
const isRequired: any;
}
namespace ampm {
// Circular reference from rc_easyui.TimeSpinner.propTypes.ampm
const isRequired: any;
}
namespace className {
// Circular reference from rc_easyui.TimeSpinner.propTypes.className
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.TimeSpinner.propTypes.disabled
const isRequired: any;
}
namespace editable {
// Circular reference from rc_easyui.TimeSpinner.propTypes.editable
const isRequired: any;
}
namespace format {
// Circular reference from rc_easyui.TimeSpinner.propTypes.format
const isRequired: any;
}
namespace highlight {
// Circular reference from rc_easyui.TimeSpinner.propTypes.highlight
const isRequired: any;
}
namespace iconAlign {
// Circular reference from rc_easyui.TimeSpinner.propTypes.iconAlign
const isRequired: any;
}
namespace iconCls {
// Circular reference from rc_easyui.TimeSpinner.propTypes.iconCls
const isRequired: any;
}
namespace increment {
// Circular reference from rc_easyui.TimeSpinner.propTypes.increment
const isRequired: any;
}
namespace inputCls {
// Circular reference from rc_easyui.TimeSpinner.propTypes.inputCls
const isRequired: any;
}
namespace inputId {
// Circular reference from rc_easyui.TimeSpinner.propTypes.inputId
const isRequired: any;
}
namespace inputStyle {
// Circular reference from rc_easyui.TimeSpinner.propTypes.inputStyle
const isRequired: any;
}
namespace max {
// Circular reference from rc_easyui.TimeSpinner.propTypes.max
const isRequired: any;
}
namespace min {
// Circular reference from rc_easyui.TimeSpinner.propTypes.min
const isRequired: any;
}
namespace multiline {
// Circular reference from rc_easyui.TimeSpinner.propTypes.multiline
const isRequired: any;
}
namespace onBlur {
// Circular reference from rc_easyui.TimeSpinner.propTypes.onBlur
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.TimeSpinner.propTypes.onChange
const isRequired: any;
}
namespace onFocus {
// Circular reference from rc_easyui.TimeSpinner.propTypes.onFocus
const isRequired: any;
}
namespace placeholder {
// Circular reference from rc_easyui.TimeSpinner.propTypes.placeholder
const isRequired: any;
}
namespace readOnly {
// Circular reference from rc_easyui.TimeSpinner.propTypes.readOnly
const isRequired: any;
}
namespace reversed {
// Circular reference from rc_easyui.TimeSpinner.propTypes.reversed
const isRequired: any;
}
namespace selections {
// Circular reference from rc_easyui.TimeSpinner.propTypes.selections
const isRequired: any;
}
namespace spinAlign {
// Circular reference from rc_easyui.TimeSpinner.propTypes.spinAlign
const isRequired: any;
}
namespace spinners {
// Circular reference from rc_easyui.TimeSpinner.propTypes.spinners
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.TimeSpinner.propTypes.style
const isRequired: any;
}
namespace tabIndex {
// Circular reference from rc_easyui.TimeSpinner.propTypes.tabIndex
const isRequired: any;
}
namespace textFormatter {
// Circular reference from rc_easyui.TimeSpinner.propTypes.textFormatter
const isRequired: any;
}
namespace value {
// Circular reference from rc_easyui.TimeSpinner.propTypes.value
const isRequired: any;
}
}
}
export namespace Tooltip {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Tooltip.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Tooltip.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const deltaX: number;
const deltaY: number;
const disabled: boolean;
const hideDelay: number;
const hideEvent: string;
const position: string;
const showDelay: number;
const showEvent: string;
const trackMouse: boolean;
const tracking: boolean;
const valign: string;
const zIndex: number;
function onHide(): void;
function onPosition(e: any): void;
function onShow(): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function content(e: any, t: any, n: any, r: any, i: any, a: any): void;
function deltaX(e: any, t: any, n: any, r: any, i: any, a: any): void;
function deltaY(e: any, t: any, n: any, r: any, i: any, a: any): void;
function disabled(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hideDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function hideEvent(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onHide(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onShow(e: any, t: any, n: any, r: any, i: any, a: any): void;
function position(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showEvent(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function target(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tooltipCls(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tooltipStyle(e: any, t: any, n: any, r: any, i: any, a: any): void;
function trackMouse(e: any, t: any, n: any, r: any, i: any, a: any): void;
function tracking(e: any, t: any, n: any, r: any, i: any, a: any): void;
function valign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function zIndex(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.Tooltip.propTypes.className
const isRequired: any;
}
namespace content {
// Circular reference from rc_easyui.Tooltip.propTypes.content
const isRequired: any;
}
namespace deltaX {
// Circular reference from rc_easyui.Tooltip.propTypes.deltaX
const isRequired: any;
}
namespace deltaY {
// Circular reference from rc_easyui.Tooltip.propTypes.deltaY
const isRequired: any;
}
namespace disabled {
// Circular reference from rc_easyui.Tooltip.propTypes.disabled
const isRequired: any;
}
namespace hideDelay {
// Circular reference from rc_easyui.Tooltip.propTypes.hideDelay
const isRequired: any;
}
namespace hideEvent {
// Circular reference from rc_easyui.Tooltip.propTypes.hideEvent
const isRequired: any;
}
namespace onHide {
// Circular reference from rc_easyui.Tooltip.propTypes.onHide
const isRequired: any;
}
namespace onPosition {
// Circular reference from rc_easyui.Tooltip.propTypes.onPosition
const isRequired: any;
}
namespace onShow {
// Circular reference from rc_easyui.Tooltip.propTypes.onShow
const isRequired: any;
}
namespace position {
// Circular reference from rc_easyui.Tooltip.propTypes.position
const isRequired: any;
}
namespace showDelay {
// Circular reference from rc_easyui.Tooltip.propTypes.showDelay
const isRequired: any;
}
namespace showEvent {
// Circular reference from rc_easyui.Tooltip.propTypes.showEvent
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Tooltip.propTypes.style
const isRequired: any;
}
namespace target {
// Circular reference from rc_easyui.Tooltip.propTypes.target
const isRequired: any;
}
namespace tooltipCls {
// Circular reference from rc_easyui.Tooltip.propTypes.tooltipCls
const isRequired: any;
}
namespace tooltipStyle {
// Circular reference from rc_easyui.Tooltip.propTypes.tooltipStyle
const isRequired: any;
}
namespace trackMouse {
// Circular reference from rc_easyui.Tooltip.propTypes.trackMouse
const isRequired: any;
}
namespace tracking {
// Circular reference from rc_easyui.Tooltip.propTypes.tracking
const isRequired: any;
}
namespace valign {
// Circular reference from rc_easyui.Tooltip.propTypes.valign
const isRequired: any;
}
namespace zIndex {
// Circular reference from rc_easyui.Tooltip.propTypes.zIndex
const isRequired: any;
}
}
}
export namespace Tree {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Tree.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Tree.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const cascadeCheck: boolean;
const checkbox: boolean;
const clickToEdit: boolean;
const data: any[];
const dblclickToEdit: boolean;
const filterIncludingChild: boolean;
const selectLeafOnly: boolean;
function filter(e: any, t: any): any;
function onCheckChange(e: any): void;
function onEditBegin(e: any): void;
function onEditCancel(e: any): void;
function onEditEnd(e: any): void;
function onNodeCheck(e: any): void;
function onNodeClick(e: any): void;
function onNodeCollapse(e: any): void;
function onNodeContextMenu(e: any): void;
function onNodeDblClick(e: any): void;
function onNodeExpand(e: any): void;
function onNodeUncheck(e: any): void;
function onSelectionChange(e: any): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function cascadeCheck(e: any, t: any, n: any, r: any, i: any, a: any): void;
function checkbox(e: any, t: any, n: any, r: any, i: any, a: any): void;
function clickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function dblclickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editor(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterIncludingChild(e: any, t: any, n: any, r: any, i: any, a: any): void;
function render(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectLeafOnly(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.Tree.propTypes.animate
const isRequired: any;
}
namespace cascadeCheck {
// Circular reference from rc_easyui.Tree.propTypes.cascadeCheck
const isRequired: any;
}
namespace checkbox {
// Circular reference from rc_easyui.Tree.propTypes.checkbox
const isRequired: any;
}
namespace clickToEdit {
// Circular reference from rc_easyui.Tree.propTypes.clickToEdit
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.Tree.propTypes.data
const isRequired: any;
}
namespace dblclickToEdit {
// Circular reference from rc_easyui.Tree.propTypes.dblclickToEdit
const isRequired: any;
}
namespace editor {
// Circular reference from rc_easyui.Tree.propTypes.editor
const isRequired: any;
}
namespace filter {
// Circular reference from rc_easyui.Tree.propTypes.filter
const isRequired: any;
}
namespace filterIncludingChild {
// Circular reference from rc_easyui.Tree.propTypes.filterIncludingChild
const isRequired: any;
}
namespace render {
// Circular reference from rc_easyui.Tree.propTypes.render
const isRequired: any;
}
namespace selectLeafOnly {
// Circular reference from rc_easyui.Tree.propTypes.selectLeafOnly
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.Tree.propTypes.selection
const isRequired: any;
}
}
}
export namespace TreeGrid {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.TreeGrid.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.TreeGrid.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const animate: boolean;
const border: boolean;
const cascadeCheck: boolean;
const checkbox: boolean;
const clickToEdit: boolean;
const columnMoving: boolean;
const columnResizing: boolean;
const data: any[];
const dblclickToEdit: boolean;
const defaultLoadMsg: string;
const filterBtnPosition: string;
const filterDelay: number;
const filterIncludingChild: boolean;
const filterMatchingType: string;
const filterOperators: {
beginwith: {
isMatch: any;
text: string;
};
contains: {
isMatch: any;
text: string;
};
endwith: {
isMatch: any;
text: string;
};
equal: {
isMatch: any;
text: string;
};
greater: {
isMatch: any;
text: string;
};
greaterorequal: {
isMatch: any;
text: string;
};
less: {
isMatch: any;
text: string;
};
lessorequal: {
isMatch: any;
text: string;
};
nofilter: {
isMatch: any;
text: string;
};
notequal: {
isMatch: any;
text: string;
}; };
const filterPosition: string;
const filterRules: any[];
const filterable: boolean;
const footerData: any[];
const frozenAlign: string;
const frozenWidth: string;
const lazy: boolean;
const loading: boolean;
const multiSort: boolean;
const pageNumber: number;
const pagePosition: string;
const pageSize: number;
const pagination: boolean;
const rowHeight: number;
const selectionMode: string;
const showFooter: boolean;
const showHeader: boolean;
const sorts: any[];
const striped: boolean;
const total: number;
const virtualScroll: boolean;
function filter(e: any, t: any, n: any): any;
function onCellClick(): void;
function onCellContextMenu(e: any): void;
function onCellDblClick(): void;
function onCellSelect(): void;
function onCellUnselect(): void;
function onCheckChange(e: any): void;
function onColumnMove(e: any): void;
function onColumnResize(e: any): void;
function onEditBegin(e: any): void;
function onEditCancel(e: any): void;
function onEditEnd(e: any): void;
function onEditValidate(e: any): void;
function onFilterChange(): void;
function onPageChange(): void;
function onRowCheck(e: any): void;
function onRowClick(e: any): void;
function onRowCollapse(e: any): void;
function onRowContextMenu(e: any): void;
function onRowDblClick(e: any): void;
function onRowExpand(e: any): void;
function onRowSelect(): void;
function onRowUncheck(e: any): void;
function onRowUnselect(): void;
function onSelectionChange(): void;
function onSortChange(): void;
}
namespace propTypes {
function animate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function border(e: any, t: any, n: any, r: any, i: any, a: any): void;
function cascadeCheck(e: any, t: any, n: any, r: any, i: any, a: any): void;
function checkbox(e: any, t: any, n: any, r: any, i: any, a: any): void;
function clickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function columnMoving(e: any, t: any, n: any, r: any, i: any, a: any): void;
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function dblclickToEdit(e: any, t: any, n: any, r: any, i: any, a: any): void;
function editMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterBtnPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterDelay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterIncludingChild(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterMatchingType(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterOperators(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterPosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function filterable(e: any, t: any, n: any, r: any, i: any, a: any): void;
function footerData(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenAlign(e: any, t: any, n: any, r: any, i: any, a: any): void;
function frozenWidth(e: any, t: any, n: any, r: any, i: any, a: any): void;
function idField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loadMsg(e: any, t: any, n: any, r: any, i: any, a: any): void;
function loading(e: any, t: any, n: any, r: any, i: any, a: any): void;
function multiSort(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageOptions(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagePosition(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pagination(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowCss(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selection(e: any, t: any, n: any, r: any, i: any, a: any): void;
function selectionMode(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showFooter(e: any, t: any, n: any, r: any, i: any, a: any): void;
function showHeader(e: any, t: any, n: any, r: any, i: any, a: any): void;
function sorts(e: any, t: any, n: any, r: any, i: any, a: any): void;
function striped(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
function treeField(e: any, t: any, n: any, r: any, i: any, a: any): void;
function virtualScroll(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace animate {
// Circular reference from rc_easyui.TreeGrid.propTypes.animate
const isRequired: any;
}
namespace border {
// Circular reference from rc_easyui.TreeGrid.propTypes.border
const isRequired: any;
}
namespace cascadeCheck {
// Circular reference from rc_easyui.TreeGrid.propTypes.cascadeCheck
const isRequired: any;
}
namespace checkbox {
// Circular reference from rc_easyui.TreeGrid.propTypes.checkbox
const isRequired: any;
}
namespace clickToEdit {
// Circular reference from rc_easyui.TreeGrid.propTypes.clickToEdit
const isRequired: any;
}
namespace columnMoving {
// Circular reference from rc_easyui.TreeGrid.propTypes.columnMoving
const isRequired: any;
}
namespace data {
// Circular reference from rc_easyui.TreeGrid.propTypes.data
const isRequired: any;
}
namespace dblclickToEdit {
// Circular reference from rc_easyui.TreeGrid.propTypes.dblclickToEdit
const isRequired: any;
}
namespace editMode {
// Circular reference from rc_easyui.TreeGrid.propTypes.editMode
const isRequired: any;
}
namespace filter {
// Circular reference from rc_easyui.TreeGrid.propTypes.filter
const isRequired: any;
}
namespace filterBtnPosition {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterBtnPosition
const isRequired: any;
}
namespace filterDelay {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterDelay
const isRequired: any;
}
namespace filterIncludingChild {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterIncludingChild
const isRequired: any;
}
namespace filterMatchingType {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterMatchingType
const isRequired: any;
}
namespace filterOperators {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterOperators
const isRequired: any;
}
namespace filterPosition {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterPosition
const isRequired: any;
}
namespace filterRules {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterRules
const isRequired: any;
}
namespace filterable {
// Circular reference from rc_easyui.TreeGrid.propTypes.filterable
const isRequired: any;
}
namespace footerData {
// Circular reference from rc_easyui.TreeGrid.propTypes.footerData
const isRequired: any;
}
namespace frozenAlign {
// Circular reference from rc_easyui.TreeGrid.propTypes.frozenAlign
const isRequired: any;
}
namespace frozenWidth {
// Circular reference from rc_easyui.TreeGrid.propTypes.frozenWidth
const isRequired: any;
}
namespace idField {
// Circular reference from rc_easyui.TreeGrid.propTypes.idField
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.TreeGrid.propTypes.lazy
const isRequired: any;
}
namespace loadMsg {
// Circular reference from rc_easyui.TreeGrid.propTypes.loadMsg
const isRequired: any;
}
namespace loading {
// Circular reference from rc_easyui.TreeGrid.propTypes.loading
const isRequired: any;
}
namespace multiSort {
// Circular reference from rc_easyui.TreeGrid.propTypes.multiSort
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.TreeGrid.propTypes.pageNumber
const isRequired: any;
}
namespace pageOptions {
// Circular reference from rc_easyui.TreeGrid.propTypes.pageOptions
const isRequired: any;
}
namespace pagePosition {
// Circular reference from rc_easyui.TreeGrid.propTypes.pagePosition
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.TreeGrid.propTypes.pageSize
const isRequired: any;
}
namespace pagination {
// Circular reference from rc_easyui.TreeGrid.propTypes.pagination
const isRequired: any;
}
namespace rowCss {
// Circular reference from rc_easyui.TreeGrid.propTypes.rowCss
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.TreeGrid.propTypes.rowHeight
const isRequired: any;
}
namespace selection {
// Circular reference from rc_easyui.TreeGrid.propTypes.selection
const isRequired: any;
}
namespace selectionMode {
// Circular reference from rc_easyui.TreeGrid.propTypes.selectionMode
const isRequired: any;
}
namespace showFooter {
// Circular reference from rc_easyui.TreeGrid.propTypes.showFooter
const isRequired: any;
}
namespace showHeader {
// Circular reference from rc_easyui.TreeGrid.propTypes.showHeader
const isRequired: any;
}
namespace sorts {
// Circular reference from rc_easyui.TreeGrid.propTypes.sorts
const isRequired: any;
}
namespace striped {
// Circular reference from rc_easyui.TreeGrid.propTypes.striped
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.TreeGrid.propTypes.total
const isRequired: any;
}
namespace treeField {
// Circular reference from rc_easyui.TreeGrid.propTypes.treeField
const isRequired: any;
}
namespace virtualScroll {
// Circular reference from rc_easyui.TreeGrid.propTypes.virtualScroll
const isRequired: any;
}
}
}
export namespace Validation {
namespace childContextTypes {
function fieldAdd(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldBlur(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldFocus(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldName(e: any, t: any, n: any, r: any, i: any, a: any): void;
function fieldRemove(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace fieldAdd {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldAdd
const isRequired: any;
}
namespace fieldBlur {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldBlur
const isRequired: any;
}
namespace fieldChange {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldChange
const isRequired: any;
}
namespace fieldFocus {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldFocus
const isRequired: any;
}
namespace fieldName {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldName
const isRequired: any;
}
namespace fieldRemove {
// Circular reference from rc_easyui.Validation.childContextTypes.fieldRemove
const isRequired: any;
}
}
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.Validation.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.Validation.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const delay: number;
function onChange(e: any, t: any): void;
function onValidate(e: any): void;
}
namespace propTypes {
function className(e: any, t: any, n: any, r: any, i: any, a: any): void;
function delay(e: any, t: any, n: any, r: any, i: any, a: any): void;
function model(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onValidate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rules(e: any, t: any, n: any, r: any, i: any, a: any): void;
function style(e: any, t: any, n: any, r: any, i: any, a: any): void;
function validateRules(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace className {
// Circular reference from rc_easyui.Validation.propTypes.className
const isRequired: any;
}
namespace delay {
// Circular reference from rc_easyui.Validation.propTypes.delay
const isRequired: any;
}
namespace model {
// Circular reference from rc_easyui.Validation.propTypes.model
const isRequired: any;
}
namespace onChange {
// Circular reference from rc_easyui.Validation.propTypes.onChange
const isRequired: any;
}
namespace onValidate {
// Circular reference from rc_easyui.Validation.propTypes.onValidate
const isRequired: any;
}
namespace rules {
// Circular reference from rc_easyui.Validation.propTypes.rules
const isRequired: any;
}
namespace style {
// Circular reference from rc_easyui.Validation.propTypes.style
const isRequired: any;
}
namespace validateRules {
// Circular reference from rc_easyui.Validation.propTypes.validateRules
const isRequired: any;
}
}
}
export namespace VirtualScroll {
namespace contextTypes {
function locale(e: any, t: any, n: any, r: any, i: any, a: any): void;
function t(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace locale {
// Circular reference from rc_easyui.VirtualScroll.contextTypes.locale
const isRequired: any;
}
namespace t {
// Circular reference from rc_easyui.VirtualScroll.contextTypes.t
const isRequired: any;
}
}
namespace defaultProps {
const data: any[];
const lazy: boolean;
const maxDivHeight: number;
const maxVisibleHeight: number;
const pageNumber: number;
const pageSize: number;
const rowHeight: number;
const total: number;
function onBodyScroll(e: any): void;
function onPageChange(e: any): void;
function onUpdate(e: any): void;
}
namespace propTypes {
function data(e: any, t: any, n: any, r: any, i: any, a: any): void;
function lazy(e: any, t: any, n: any, r: any, i: any, a: any): void;
function maxDivHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function maxVisibleHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onPageChange(e: any, t: any, n: any, r: any, i: any, a: any): void;
function onUpdate(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageNumber(e: any, t: any, n: any, r: any, i: any, a: any): void;
function pageSize(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderItem(e: any, t: any, n: any, r: any, i: any, a: any): void;
function renderItems(e: any, t: any, n: any, r: any, i: any, a: any): void;
function reset(e: any, t: any, n: any, r: any, i: any, a: any): void;
function rowHeight(e: any, t: any, n: any, r: any, i: any, a: any): void;
function total(e: any, t: any, n: any, r: any, i: any, a: any): void;
namespace data {
// Circular reference from rc_easyui.VirtualScroll.propTypes.data
const isRequired: any;
}
namespace lazy {
// Circular reference from rc_easyui.VirtualScroll.propTypes.lazy
const isRequired: any;
}
namespace maxDivHeight {
// Circular reference from rc_easyui.VirtualScroll.propTypes.maxDivHeight
const isRequired: any;
}
namespace maxVisibleHeight {
// Circular reference from rc_easyui.VirtualScroll.propTypes.maxVisibleHeight
const isRequired: any;
}
namespace onPageChange {
// Circular reference from rc_easyui.VirtualScroll.propTypes.onPageChange
const isRequired: any;
}
namespace onUpdate {
// Circular reference from rc_easyui.VirtualScroll.propTypes.onUpdate
const isRequired: any;
}
namespace pageNumber {
// Circular reference from rc_easyui.VirtualScroll.propTypes.pageNumber
const isRequired: any;
}
namespace pageSize {
// Circular reference from rc_easyui.VirtualScroll.propTypes.pageSize
const isRequired: any;
}
namespace renderItem {
// Circular reference from rc_easyui.VirtualScroll.propTypes.renderItem
const isRequired: any;
}
namespace renderItems {
// Circular reference from rc_easyui.VirtualScroll.propTypes.renderItems
const isRequired: any;
}
namespace reset {
// Circular reference from rc_easyui.VirtualScroll.propTypes.reset
const isRequired: any;
}
namespace rowHeight {
// Circular reference from rc_easyui.VirtualScroll.propTypes.rowHeight
const isRequired: any;
}
namespace total {
// Circular reference from rc_easyui.VirtualScroll.propTypes.total
const isRequired: any;
}
}
}
export namespace classHelper {
function classNames(...args: any[]): any;
}
export namespace dateHelper {
const ampm: string[];
function formatDate(e: any, t: any): any;
function parseDate(e: any, t: any): any;
function parseSelections(e: any): any;
function setAmPm(e: any): void;
}
export namespace domHelper {
function addClass(e: any, t: any): void;
function bind(e: any, t: any, n: any): void;
function closest(e: any, t: any): any;
function getElement(e: any): any;
function getScrollLeft(): any;
function getScrollTop(): any;
function getViewport(): any;
function hasClass(e: any, t: any): any;
function isAutoSize(e: any): any;
function isChild(e: any, t: any): any;
function nextGuid(): any;
function offset(e: any): any;
function outerHeight(e: any, t: any): any;
function outerWidth(e: any, t: any): any;
function position(e: any): any;
function removeClass(e: any, t: any): void;
function scrollTo(e: any, t: any): void;
function slideDown(e: any): void;
function slideUp(e: any): void;
function toStyleValue(e: any): any;
function unbind(e: any, t: any, n: any): void;
}
export namespace treeHelper {
const cascadeCheck: boolean;
function adjustCheck(e: any): void;
function calcNodeState(e: any): any;
function checkNode(e: any, t: any): void;
function findNode(e: any, t: any, n: any): any;
function forNodes(e: any, t: any): void;
function setCheckState(e: any, t: any): void;
function setChildCheckbox(e: any, t: any): void;
function setParentCheckbox(e: any): void;
function uncheckAllNodes(e: any, t: any): void;
function uncheckNode(e: any, t: any): void;
} | the_stack |
import { UIEvent } from 'jui-core';
export interface UIAccordion extends UIEvent {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Integer} [index=null]
* Sets an enabled node
*/
index?: number,
/**
* @cfg {Boolean} [autoFold=false]
* When you click on a node, the node folding
*/
autoFold?: boolean,
/**
* @cfg {Boolean} [multipanel=false]
*/
multipanel?: boolean
}): this;
/**
* Gets the index of the currently enabled node
*
* @return Index
*/
activeIndex(): number;
}
export interface UIAutoComplete {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {String/DOMElement} [target=null]
* Designates a target selector when an autofill route is not a target
*/
target?: any,
/**
* @cfg {Array} words
* Designates words subject to autofill
*/
words?: string[]
}): this;
/**
* Updates words subject to autofill
*
*
*/
update(newWords: string[]): void;
close(): void;
/**
* Gets filtered words subject to autofill
*
* @return words
*/
list(): string[];
}
export interface UIColorPicker {
(selector: any, options?: {
tpl?: any,
event?: any,
type?: string,
color?: string
}): this;
getColor(type: string): string | {};
setColor(value: string | {}): void;
}
export interface UICombo {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Integer} [index=0]
* Determines an initial selection button with a specified index
*/
index?: number,
/**
* @cfg {String} [value=0]
* Determines an initial selection button with a specified value
*/
value?: string,
/**
* @cfg {Integer} [width=0]
* Determines the horizontal size of a combo box
*/
width?: number,
/**
* @cfg {Integer} [height=100]
* Determines an initial selection button with a specified value
*/
height?: number,
/**
* @cfg {Boolean} [keydown=false]
* It is possible to select a node using the keyboard
*/
keydown?: boolean,
/**
* @cfg {"top"/"bottom"} [position="bottom"]
* It is possible to determine an initial selection button with a specified value
*/
position?: "top" | "bottom",
/**
* @cfg {Boolean} [flex=true]
* Drop-down menu is varied by changing the width function
*/
flex?: boolean
}): this;
/**
* Selects a button of a specified index
*
*/
setIndex(index: number): void;
/**
* Selects a button having a specified value
*
*/
setValue(value: any): void;
/**
* Gets the data of the button currently selected
*
*/
getData(): {};
/**
* Gets the value of the button currently selected
*
*/
getValue(): any;
/**
* Gets the markup text of the button currently selected
*
*/
getText(): string;
open(e: any): void;
fold(): void;
reload(): void;
}
export interface UIDatePicker {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {"daily"/"monthly"/"yearly"} [type="daily"]
* Determines the type of a calendar
*/
type?: "daily" | "monthly" | "yearly",
/**
* @cfg {String} [titleFormat="yyyy.MM"]
* Title format of a calendar
*/
titleFormat?: string,
/**
* @cfg {String} [format="yyyy-MM-dd"]
* Format of the date handed over when selecting a specific date
*/
format?: string,
/**
* @cfg {Date} [date="now"]
* Selects a specific date as a basic
*/
date?: "now" | Date,
/**
* @cfg {Date} [minDate="null"]
* Selects a specific minimum date
*/
minDate?: Date,
/**
* @cfg {Date} [maxDate="null"]
* Selects a specific maximum date
*/
maxDate?: Date
}): this;
/**
* Outputs a calendar that fits the year/month entered
*
*/
page(y: number, m: number): void;
prev(e: any, moveYear?: boolean): void;
next(e: any, moveYear?: boolean): void;
/**
* Selects today if there is no value, or selects a date applicable to a timestamp or year/month/date
*
* @param "year"/"month"/"date"/"timestamp"/"Date"
*/
select(...args: any[]): void;
/**
* Selects a date corresponding to the time added to the currently selected date
*
* @param time Timestamp or Date
*/
addTime(time: number | Date): void;
/**
* Gets the value of the date currently selected
*
* @return Date object
*/
getDate(): Date;
/**
* Gets the timestamp value of the date currently selected
*
* @return Timestamp
*/
getTime(): number;
/**
* Gets a date string that fits the format entered
*
* @return format Formatted date string
*/
getFormat(format: string): string;
reload(): void;
}
export interface UIDropdown {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Boolean} [close=true]
* Closes the Auto when clicking on the dropdown list
*/
close?: boolean,
/**
* @cfg {Boolean} [keydown=false]
* It is possible to choose anything on the dropdown list with the arrow keys on the keyboard
*/
keydown?: boolean,
/**
* @cfg {Integer} [left=0]
* Sets the X coordinate of the dropdown list
*/
left?: number,
/**
* @cfg {Integer} [top=0]
* Sets the Y coordinate of the dropdown list
*/
top?: number,
/**
* @cfg {Integer} [width=0]
* Determines the horizontal size of a dropdown list
*/
width?: number,
/**
* @cfg {Integer} [height=0]
* Determines the vertical size of a dropdown list
*/
height?: number,
/**
* @cfg {Array} nodes
* Sets a dropdown list to data rather than markup
*/
nodes?: any[]
}): this;
/**
* Changes the dropdown list
*
* @param nodes Dropdown list
*/
update(nodes: any[]): void;
hide(): void;
/**
* Shows a dropdown at the specified coordinates
*
*/
show(x: number, y: number): void;
/**
* Moves a dropdown to the specified coordinates
*
*/
move(x: number, y: number): void;
reload(): void;
}
export interface UIModal {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {"black"/"gray"} [color="black"]
* Determines the color of a modal
*/
color?: "black" | "gray",
/**
* @cfg {Float} [opacity=0.4]
* Sets the transparency of a modal
*/
opacity?: number,
/**
* @cfg {String/DOMElement} [target="body"]
* Sets a selector on which a modal is shown
*/
target?: string | any,
/**
* @cfg {Integer} [index=0]
* Determines the sequence (index) of a modal
*/
index?: number,
/**
* @cfg {Boolean} [clone=false]
* Copies an existing modal and shows it
*/
clone?: boolean,
/**
* @cfg {Boolean} [autoHide=true]
* Automatically hides a modal when clicking on it
*/
autoHide?: boolean
}): this;
hide(): void;
show(): void;
resize(): void;
}
export interface UINotify {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {"top"/"top-lefet"/"top-right"/"bottom"/"bottom-left"/"bottom-right"} [position="top-right"]
* Designates the location where a notice message is added
*/
position?: "top" | "top-lefet" | "top-right" | "bottom" | "bottom-left" | "bottom-right",
/**
* @cfg {Integer} [padding=12]
* Determines the margin value of a notice message (the margin value may be in object form rather than a numeric value)
*/
padding?: number,
/**
* @cfg {Integer} [distance=5]
* Determines each margin value when there are multiple notice messages
*/
distance?: number,
/**
* @cfg {Integer} [timeout=3000]
* Determines the duration for which a notice message is displayed (the message does not disappear when the value is 0)
*/
timeout?: number,
/**
* @cfg {Integer} [showDuration=500]
* Determines the duration of an effect when a notice message is shown
*/
showDuration?: number,
/**
* @cfg {Integer} [hideDuration=500]
* Determines the duration of an effect when a notice message disappears
*/
hideDuration?: number,
/**
* @cfg {String} [showEasing="swing"]
* Determines an effect when a notice message is shown (see CSS3 specifications)
*/
showEasing?: string,
/**
* @cfg {String} [hideEasing="linear"]
* Determines an effect when a notice message disappears (see CSS3 specifications)
*/
hideEasing?: string
}): this;
/**
* Adds a notice message. The value passed is the data object shown by the notice template
*
*/
add(data: {}, timeout: number): void;
reset(): void;
}
export interface UIPaging {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Integer} [count=0]
* Total number of data records subject to paging)
*/
count?: number,
/**
* @cfg {Integer} [pageCount=10]
* Number of data records per page
*/
pageCount?: number,
/**
* @cfg {Integer} [screenCount=5]
* Number of pages shown on the paging screen
*/
screenCount?: number
}): this;
/**
* Reloads the number of specified data records, or reloads the initially configured number of data records if there is no parameter
*
* @param count Data total count
*/
reload(count: number): void;
/**
* Changes to a specified page number, and gets the currently enabled page number if there is no parameter
*
* @param pNo Page number
*/
page(pNo: number): void;
next(): void;
prev(): void;
first(): void;
last(): void;
}
export interface UIProgress {
(selector: any, options?: {
tpl?: any,
event?: any,
type?: "simple" | "flat", // simple or flat
orient?: "horizontal" | "vertical", // or vertical,
min?: number,
max?: number,
value?: number,
striped?: boolean, // or true
animated?: boolean // or true
}): this;
setAnimated(isAnimated: boolean): void;
setStriped(isStriped: boolean): void;
setValue(v: number): void;
getValue(): number;
}
export interface UIProperty {
(selector: any, options?: {
tpl?: any,
event?: any,
sort?: string, // name, group, type
viewport?: string,
items?: any[]
}): this;
loadItems(newItems: any[]): void;
addItem(item: {} | any[]): void;
// remove item by key or title
removeItem(item: {}): void;
getGroupList(): any[];
/**
*
* collapse group's children
*
*/
collapsed(id: string): void;
/**
*
* expand group's children
*
*/
expanded(id: string): void;
/**
*
* get a list of property's value
*
* @param [key=null] if key is null, value is all properties.
*/
getValue(key?: string): {} | any[];
getDefaultValue(): any[];
initValue(obj: {}): void;
/**
*
* set a list of property's value
*
*/
setValue(obj: {}): void;
findRender(key: string): any;
findItem(key: string): any;
updateValue(key: string, value: any): void;
getAllValue(key: string): any;
refreshValue($dom: any, newValue: any): void;
}
export interface UISelect {
(selector: any, options?: {
tpl?: any,
event?: any,
items?: any[],
placeholder?: string,
align?: 'left' | 'right',
valign?: 'top' | 'bottom',
multi?: boolean
}): this;
setValue(value: any | any[]): void;
getValue(): any | any[];
setSelectedIndex(index: number): void;
getSelectedIndex(): number;
update(data: any[]): void;
}
export interface UISlider {
(selector: any, options?: {
tpl?: any,
event?: any,
type?: "single" | "double", // or double
orient?: "horizontal" | "vertical", // or vertical,
min?: number,
max?: number,
step?: number,
from?: number,
to?: number,
tooltip?: boolean,
format?: string,
progress?: boolean
}): this;
/**
* set FromHandle's value
*/
setFromValue(value: number): void;
/**
* set ToHandle's value
*/
setToValue(value: number): void;
/**
* get FromHandle's value
*
* @return value
*/
getFromValue(): number;
/**
* get ToHandle's value
*
* @return value
*/
getToValue(): number;
}
export interface UISplitter {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {String} [splitterClass='ui-splitter']
* set splitter's class for design
*/
splitterClass?: string,
/**
* @cfg {String} [hideClass='hide']
* set splitter's hide class for design
*/
hideClass?: string,
/**
* @cfg {Number} [barSize=4]
* set splitter's bar size
*/
barSize?: number,
/**
* @cfg {Object} [barStyle={}]
* set custom splitter bar style
*/
barStyle?: {},
/**
* @cfg {"vertical"/"horizontal"} [direction='vertical']
* set bar's direction
*/
direction?: 'vertical' | 'horizontal',
/**
* @cfg {String/Number} [initSize='50%']
* set first panel's default width or height
*/
initSize?: string | number,
/**
* @cfg {Number/Array} [minSize=30]
* set panel's minimum width or height
*
* if minSize is number , minSize is conver to array
*
* minSize[0] is first panel's minimum size
* minSize[1] is second panel's minimum size
*
*/
minSize?: number | number[],
/**
* @cfg {String} [items=[]]
*
* set items to placed in vertical or horizontal
*
* support max two times
*
*/
items?: any[],
/**
* @cfg {Boolean} [fixed=false]
*
* if fixed is true, panels can not resize.
*
*/
fixed?: boolean
}): this;
setDirection(d: 'horizontal' | 'vertical'): void;
setInitSize(size: number): void;
setHide(index: number): void;
setShow(index: number): void;
toggle(index: number): void;
}
export interface UISwitch {
(selector: any, options?: {
tpl?: any,
event?: any,
checked?: boolean,
toggleEvent?: string
}): this;
getValue(): boolean;
setValue(value: boolean): void;
toggle(): void;
}
export interface UITab {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {String/DOMElement} [target=""]
* Determines a selector in the area to become the content of a tab
*/
target?: string | any,
/**
* @cfg {Integer} [index=0]
* Sets an enabled tab
*/
index?: number,
/**
* @cfg {Boolean} [drag=false]
* Changes the tab location through dragging
*/
drag?: boolean,
/**
* @cfg {Array} nodes
* Sets a tab list to data rather than markup
*/
nodes?: any[]
}): this;
/**
* Changes the tab list
*
*/
update(nodes: any[]): void;
/**
* Adds a tab at a specified index
*
*/
insert(index: number, node: {}): void;
/**
* Adds a tab to the last node
*
*/
append(node: {}): void;
/**
* Adds a tab to the first node
*
*/
prepend(node: {}): void;
/**
* Removes a tab at a specified index
*
*/
remove(index: number): void;
/**
* Changes a specified tab to a tab at a target index
*
*/
move(index: number, targetIndex: number): void;
/**
* Enables the tab at a specified index
*
*/
show(index: number): void;
/**
* Enables the tab at a specified index
*
*/
enable(index: number): void;
/**
* Disables the tab at a specified index
*
*/
disable(index: number): void;
/**
* Gets the index of the currently enabled tab
*
*/
activeIndex(): number;
}
export interface UITooltip {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {String} [color="black"]
* Determines the color of a tooltip
*/
color?: string,
/**
* @cfg {"top"/"bottom"/"left"/"right"} [position="top"]
* Determines the location where a tooltip is shown
*/
position?: "top" | "bottom" | "left" | "right",
/**
* @cfg {Integer} [width=150]
* Determines the horizontal size of a tooltip
*/
width?: number,
/**
* @cfg {"left"/"right"/"center"} [align="left"]
* Determines the alignment state inside a tooltip
*/
align?: "left" | "right" | "center",
/**
* @cfg {Integer} [delay=0]
* Determines the event time when a tooltip is shown
*/
delay?: number,
/**
* @cfg {String} [showType="mouseover"]
* Determines the type of event that triggers a tooltip
*/
showType?: string,
/**
* @cfg {String} [hideType="mouseout"]
* Determines the type of event that hides a tooltip
*/
hideType?: string,
/**
* @cfg {String} [title=""]
* Sets the content of a tooltip (referring to the title properties in markup)
*/
title?: string,
}): this;
/**
* Changes the content of a tooltip
*
*/
update(newTitle: string): void;
}
export interface UITreeNode {
/** Data of a specified node */
data?: any[];
/** LI element of a specified node */
element?: any;
/** Index of a specified node */
index?: number;
/** Unique number of a specifiede node at the current depth */
nodenum?: number;
/** Variable that refers to the parent of the current node */
parent?: UITreeNode;
/** List of child nodes of a specified node */
children?: UITreeNode[];
/** Depth of a specified node */
depth?: number;
/** State value that indicates whether a child node is shown or hidden */
type?: string;
}
export interface UITreeBase {
appendNode(...args: any[]): UITreeNode;
insertNode(index: string, data: any): UITreeNode;
updateNode(index: string, data: any): UITreeNode;
removeNode(index: string): void;
removeNodes(): void;
openNode(index: string): void;
foldNode(index: string): void;
openNodeAll(index: string): void;
foldNodeAll(index: string): void;
moveNode(index: string, targetIndex: number): void;
getNode(index: string): UITreeNode;
getNodeAll(index: string): UITreeNode[];
getNodeParent(index: string): UITreeNode;
getRoot(): UITreeNode;
}
export interface UITree {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {NodeObject} [root=null]
* Adds a root node (required).
*/
root?: UITreeNode,
/**
* @cfg {Boolean} [rootHide=false]
* Hides a root node.
*/
rootHide?: boolean,
/**
* @cfg {Boolean} [rootFold=false]
* Folds up a root node.
*/
rootFold?: boolean,
/**
* @cfg {Boolean} [drag=false]
* It is possible to drag the movement of a node.
*/
drag?: boolean,
/**
* @cfg {Boolean} [dragChild=true]
* It is possible to drag the node movement but the node is not changed to a child node of the target node.
*/
dragChild?: boolean
}): this;
/**
* Changes to the node at a specified index.
*
*/
update(index: string, data: any[]): void;
/**
* Adds to a child node at a specified index.
*
* @param param1 index or data (Array/String)
* @param param2 null or data
*/
append(...args: any[]): void;
/**
* Adds a node at a specified index.
*
*/
insert(index: string, data: any[]): void;
/**
* Adds a node at a specified index.
*
* @return node
*/
select(index: string): UITreeNode;
unselect(): void;
/**
* Deletes a node at a specified index.
*
*/
remove(index: string): void;
reset(): void;
/**
* Moves a node at a specified index to the target index.
*
*/
move(index: string, targetIndex: string): void;
/**
* Shows a child node at a specified index.
*
*/
open(index: string, e: any): void;
/**
* Folds up a child node at a specified index.
*
*/
fold(index: string, e: any): void;
/**
* Shows all child nodes at a specified index.
*
*/
openAll(index: string): void;
/**
* Folds up all child nodes at a specified index.
*
*/
foldAll(index: string): void;
/**
* Return all nodes of the root.
*
* @return nodes
*/
list(): UITreeNode[];
/**
* Returns all child nodes.
*
* @return nodes
*/
listAll(): UITreeNode[];
/**
* Returns all parent nodes at a specified index.
*
* @return nodes
*/
listParents(index: string): UITreeNode[];
/**
* Gets a node at a specified index
*
* @return node
*/
get(index: string): UITreeNode;
/**
* Gets all nodes at a specified index including child nodes.
*
* @return nodes
*/
getAll(index: string): UITreeNode[];
/**
* Gets the index of a node that is activated in an active state.
*
* @return index
*/
activeIndex(): number;
}
export interface UIWindow {
(selector: any, options?: {
tpl?: any,
event?: any,
/**
* @cfg {Integer} [width=400]
* Determines the horizontal size of a window
*/
width?: number,
/**
* @cfg {Integer} [height=300]
* Determines the height of a window
*/
height?: number,
/**
* @cfg {String/Integer} [left="auto"]
* Determines the X coordinate of a window
*/
left?: string | number,
/**
* @cfg {String/Integer} [top="auto"]
* Determines the Y coordinate of a window
*/
top?: string | number,
/**
* @cfg {String/Integer} [right="auto"]
* Determines the X coordinate based on the right side of a window
*/
right?: string | number,
/**
* @cfg {String/Integer} [bottom="auto"]
* Determines the Y coordinate based on the bottom side of a window
*/
bottom?: string | number,
/**
* @cfg {Boolean} [modal=false]
* Applies a modal UI to a window
*/
modal?: boolean,
/**
* @cfg {Boolean} [move=true]
* It is possible to move a window
*/
move?: boolean,
/**
* @cfg {Boolean} [resize=true]
* It is possible to resize a window
*/
resize?: boolean,
/**
* @cfg {Integer} [modalIndex=0]
* Determines the z-index property of a modal UI
*/
modalIndex?: number
}): this;
hide(): void;
/**
* Shows a window at specified coordinates
*
*/
show(x: number, y: number): void;
/**
* Moves a window at specified coordinates
*
*/
move(x: number, y: number): void;
/**
* Changes the markup in the body area of a window
*
*/
update(html: string): void;
/**
* Changes the markup of the title tag in the head area of a window
*
*/
setTitle(html: string): void;
/**
* Changes the horizontal/vertical size of a window
*
*/
setSize(w: number, h: number): void;
resize(): void;
resizeModal(): void;
} | the_stack |
// Licensed under the Apache License, Version 2.0(the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Resolver, parse } from '../resolver'
describe('resolver', () => {
describe('parse()', () => {
it('returns parts', () => {
expect(parse('did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX')).toEqual({
method: 'uport',
id: '2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
did: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
didUrl: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
})
expect(parse('did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX/some/path')).toEqual({
method: 'uport',
id: '2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
did: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
didUrl: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX/some/path',
path: '/some/path',
})
expect(parse('did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX#fragment=123')).toEqual({
method: 'uport',
id: '2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
did: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
didUrl: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX#fragment=123',
fragment: 'fragment=123',
})
expect(parse('did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX/some/path#fragment=123')).toEqual({
method: 'uport',
id: '2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
did: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX',
didUrl: 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX/some/path#fragment=123',
path: '/some/path',
fragment: 'fragment=123',
})
expect(parse('did:nacl:Md8JiMIwsapml_FtQ2ngnGftNP5UmVCAUuhnLyAsPxI')).toEqual({
method: 'nacl',
id: 'Md8JiMIwsapml_FtQ2ngnGftNP5UmVCAUuhnLyAsPxI',
did: 'did:nacl:Md8JiMIwsapml_FtQ2ngnGftNP5UmVCAUuhnLyAsPxI',
didUrl: 'did:nacl:Md8JiMIwsapml_FtQ2ngnGftNP5UmVCAUuhnLyAsPxI',
})
expect(parse('did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high')).toEqual({
method: 'example',
id: '21tDAKCERh95uGgKbJNHYp',
did: 'did:example:21tDAKCERh95uGgKbJNHYp',
didUrl: 'did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high',
params: {
service: 'agent',
'foo:bar': 'high',
},
})
expect(parse('did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high?foo=bar')).toEqual({
method: 'example',
id: '21tDAKCERh95uGgKbJNHYp',
didUrl: 'did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high?foo=bar',
did: 'did:example:21tDAKCERh95uGgKbJNHYp',
query: 'foo=bar',
params: {
service: 'agent',
'foo:bar': 'high',
},
})
expect(parse('did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high/some/path?foo=bar#key1')).toEqual({
method: 'example',
id: '21tDAKCERh95uGgKbJNHYp',
didUrl: 'did:example:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high/some/path?foo=bar#key1',
did: 'did:example:21tDAKCERh95uGgKbJNHYp',
query: 'foo=bar',
path: '/some/path',
fragment: 'key1',
params: {
service: 'agent',
'foo:bar': 'high',
},
})
expect(parse('did:web:example.com%3A8443')).toEqual({
method: 'web',
id: 'example.com%3A8443',
didUrl: 'did:web:example.com%3A8443',
did: 'did:web:example.com%3A8443',
})
expect(parse('did:web:example.com:path:some%2Bsubpath')).toEqual({
method: 'web',
id: 'example.com:path:some%2Bsubpath',
didUrl: 'did:web:example.com:path:some%2Bsubpath',
did: 'did:web:example.com:path:some%2Bsubpath',
})
expect(
parse('did:example:test:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high/some/path?foo=bar#key1')
).toEqual({
method: 'example',
id: 'test:21tDAKCERh95uGgKbJNHYp',
didUrl: 'did:example:test:21tDAKCERh95uGgKbJNHYp;service=agent;foo:bar=high/some/path?foo=bar#key1',
did: 'did:example:test:21tDAKCERh95uGgKbJNHYp',
query: 'foo=bar',
path: '/some/path',
fragment: 'key1',
params: {
service: 'agent',
'foo:bar': 'high',
},
})
expect(parse('did:123:test::test2')).toEqual({
method: '123',
id: 'test::test2',
didUrl: 'did:123:test::test2',
did: 'did:123:test::test2',
})
expect(parse('did:method:%12%AF')).toEqual({
method: 'method',
id: '%12%AF',
didUrl: 'did:method:%12%AF',
did: 'did:method:%12%AF',
})
})
it('returns null if non compliant', () => {
expect(parse('')).toEqual(null)
expect(parse('did:')).toEqual(null)
expect(parse('did:uport')).toEqual(null)
expect(parse('did:uport:')).toEqual(null)
expect(parse('did:uport:1234_12313***')).toEqual(null)
expect(parse('2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX')).toEqual(null)
expect(parse('did:method:%12%1')).toEqual(null)
expect(parse('did:method:%1233%Ay')).toEqual(null)
expect(parse('did:CAP:id')).toEqual(null)
expect(parse('did:method:id::anotherid%r9')).toEqual(null)
})
})
describe('resolve', () => {
let resolver: Resolver
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let mockmethod: any
const mockReturn = Promise.resolve({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
beforeAll(() => {
mockmethod = jest.fn().mockReturnValue(mockReturn)
resolver = new Resolver({
example: async (did: string) => ({
didResolutionMetadata: { contentType: 'application/did+ld+json' },
didDocument: {
'@context': 'https://w3id.org/did/v1',
id: did,
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
}),
mock: mockmethod,
})
})
it('fails on unhandled methods', async () => {
await expect(resolver.resolve('did:borg:2nQtiQG6Cgm1GY')).resolves.toEqual({
didResolutionMetadata: { error: 'unsupportedDidMethod' },
didDocument: null,
didDocumentMetadata: {},
})
})
it('fails on parse error', async () => {
await expect(resolver.resolve('did:borg:')).resolves.toEqual({
didResolutionMetadata: { error: 'invalidDid' },
didDocument: null,
didDocumentMetadata: {},
})
})
it('resolves did document', async () => {
await expect(resolver.resolve('did:example:123456789')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+ld+json' },
didDocument: {
'@context': 'https://w3id.org/did/v1',
id: 'did:example:123456789',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
})
it('resolves did document with legacy resolver', async () => {
const resolverWithLegacy = new Resolver(
{},
{
legacyResolvers: {
legacy: async (did: string) => ({
'@context': 'https://w3id.org/did/v1',
id: did,
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
}),
},
}
)
await expect(resolverWithLegacy.resolve('did:legacy:123456789')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+ld+json' },
didDocument: {
'@context': 'https://w3id.org/did/v1',
id: 'did:legacy:123456789',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
})
it('throws on null document', async () => {
mockmethod = jest.fn().mockReturnValue(
Promise.resolve({
didResolutionMetadata: { error: 'notFound' },
didDocument: null,
didDocumentMetadata: {},
})
)
const nullRes = new Resolver({
nuller: mockmethod,
})
await expect(nullRes.resolve('did:nuller:asdfghjk')).resolves.toEqual({
didResolutionMetadata: { error: 'notFound' },
didDocument: null,
didDocumentMetadata: {},
})
})
describe('caching', () => {
describe('default', () => {
it('should not cache', async () => {
mockmethod = jest.fn().mockReturnValue(mockReturn)
resolver = new Resolver({
mock: mockmethod,
})
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
return expect(mockmethod).toBeCalledTimes(2)
})
})
})
describe('cache=true', () => {
it('should cache', async () => {
mockmethod = jest.fn().mockReturnValue(mockReturn)
resolver = new Resolver(
{
mock: mockmethod,
},
{ cache: true }
)
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
return expect(mockmethod).toBeCalledTimes(1)
})
it('should respect no-cache', async () => {
mockmethod = jest.fn().mockReturnValue(mockReturn)
resolver = new Resolver(
{
mock: mockmethod,
},
{ cache: true }
)
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
await expect(resolver.resolve('did:mock:abcdef;no-cache=true')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
return expect(mockmethod).toBeCalledTimes(2)
})
it('should not cache with different params', async () => {
mockmethod = jest.fn().mockReturnValue(mockReturn)
resolver = new Resolver(
{
mock: mockmethod,
},
{ cache: true }
)
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
await expect(resolver.resolve('did:mock:abcdef?versionId=2')).resolves.toEqual({
didResolutionMetadata: { contentType: 'application/did+json' },
didDocument: {
id: 'did:mock:abcdef',
verificationMethod: [
{
id: 'owner',
controller: '1234',
type: 'xyz',
},
],
},
didDocumentMetadata: {},
})
return expect(mockmethod).toBeCalledTimes(2)
})
it('should not cache null docs', async () => {
mockmethod = jest.fn().mockReturnValue(
Promise.resolve({
didResolutionMetadata: { error: 'notFound' },
didDocument: null,
didDocumentMetadata: {},
})
)
resolver = new Resolver(
{
mock: mockmethod,
},
{ cache: true }
)
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { error: 'notFound' },
didDocument: null,
didDocumentMetadata: {},
})
await expect(resolver.resolve('did:mock:abcdef')).resolves.toEqual({
didResolutionMetadata: { error: 'notFound' },
didDocument: null,
didDocumentMetadata: {},
})
return expect(mockmethod).toBeCalledTimes(2)
})
})
})
}) | the_stack |
import { getBrowser } from "../browser";
import { getCSSMatches, serializeCSSMatches } from "./css-sniff";
describe("CSS Rules", () => {
// it("Simple global rules", async () => {
// const dom = await getJSDom("p { background: red;}", "<p>test</p>");
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe("p{background: red;}");
// });
// it("Filters unused selectors", async () => {
// const dom = await getJSDom("p,a { background: red;}", "<p>test</p>");
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe("p{background: red;}");
// });
// it("Includes @media queries", async () => {
// const dom = await getJSDom(
// "p,a { background: red;} @media print { p { color: purple } } ",
// "<p>test</p>"
// );
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe("p{background: red;}@media print {p{color: purple;}}");
// });
// it("Includes pseudo-elements", async () => {
// const dom = await getJSDom(
// 'p,a { background: red;} p:after { content: "aftery"} @media print { p:before { content: "test"; } } ',
// "<p>test</p>"
// );
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe(
// 'p{background: red;}p:after{content: "aftery";}@media print {p:before{content: "test";}}'
// );
// });
// it("Filters @media queries", async () => {
// const dom = await getJSDom(
// "p,a { background: red;} @media print { p,a { color: purple } } ",
// "<p>test</p>"
// );
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe("p{background: red;}@media print {p{color: purple;}}");
// });
// it("Handles escaping \\: in class (2 chars: a backslash and colon)", async () => {
// const dom = await getJSDom(
// ".link { background: blue;} .link.\\:focus { background: red;} ",
// '<p class="link :focus">test</p>'
// );
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe(
// ".link{background: blue;}.link.\\:focus{background: red;}"
// );
// });
// it("Serializes !important", async () => {
// const dom = await getJSDom(
// ".link { background: blue !important;} .link.\\:focus { background: red;} ",
// '<p class="link :focus">test</p>'
// );
// const paragraphs = [...dom.window.document.querySelectorAll("p")];
// const matchedCSS = await getCSSMatches(paragraphs, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).toBe(
// ".link{background: blue !important;}.link.\\:focus{background: red;}"
// );
// });
// it("Ignores @charset", async () => {
// const data = `@charset "UTF-8" ;\n body:before { background: red;}`;
// const dom = await getJSDom(data, '<body class="no-match"><p>test</p></body>');
// const body = [...dom.window.document.querySelectorAll("body")];
// const matchedCSS = await getCSSMatches(body, {
// document: dom.window.document
// });
// const css = serializeCSSRules(matchedCSS);
// expect(css).not.toContain("@charset");
// });
it("Handles bad case", async () => {
const html = `<div class="g-form-group {{ error?: g-form-group--error }}">
<fieldset class="g-fieldset" aria-describedby="hintId errorId" role="group">
<legend class="g-fieldset__legend g-fieldset__legend--xl">
<mt-variable key="label">Example label</mt-variable>
</legend>
<span id="hintId" class="g-hint">
<mt-variable key="hint">Example hint</mt-variable>
</span>
<mt-if key="?error">
<span id="errorId" class="g-error-message">
<span class="g-visually-hidden">Error: </span>
<mt-variable key="?error">Example error</mt-variable>
</span>
</mt-if>
<div id="id" class="g-date-input">
<div class="g-date-input__item">
<div class="g-form-group">
<label class="g-label g-date-input__label" for="dayId">
Day
</label>
<input
id="dayId"
class="g-input g-date-input__input g-input--width-2 {{ error?: g-input--error }}"
name="dayId"
type="text"
maxlength="2"
pattern="[0-9]*"
/>
</div>
</div>
<div class="g-date-input__item">
<div class="g-form-group">
<label class="g-label g-date-input__label" for="monthId">
Month
</label>
<input
id="monthId"
class="g-input g-date-input__input g-input--width-2 {{ error?: g-input--error }}"
name="monthId"
type="text"
maxlength="2"
pattern="[0-9]*"
/>
</div>
</div>
<div class="g-date-input__item">
<div class="g-form-group">
<label class="g-label g-date-input__label" for="yearId">
Year
</label>
<input
id="yearId"
class="g-input g-date-input__input g-input--width-4 {{ error?: g-input--error }}"
name="yearId"
type="text"
maxlength="4"
pattern="[0-9]*"
/>
</div>
</div>
</div>
</fieldset>
</div>`;
var css = `body:before {
background-color: #fcf8e3;
border-bottom: 1px solid #fbeed5;
border-left: 1px solid #fbeed5;
color: #c09853;
font: small-caption;
padding: 3px 6px;
pointer-events: none;
position: fixed;
right: 0;
top: 0;
z-index: 100;
}
@media (min-width: 20em) {
body:before {
content: 'mobile ≥ 320px (20em)';
}
}
@media (min-width: 40.0625em) {
body:before {
content: 'tablet ≥ 641px (40.0625em)';
}
}
@media (min-width: 48.0625em) {
body:before {
content: 'desktop ≥ 769px (48.0625em)';
}
}
.g-link {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@font-face {
font-family: 'Name';
src: url('/assets/fonts/light-2c037cf7e1-v1.eot');
src: url('/assets/fonts/light-2c037cf7e1-v1.eot?#iefix')
format('embedded-opentype'),
url('/assets/fonts/light-f38ad40456-v1.woff2') format('woff2'),
url('/assets/fonts/light-458f8ea81c-v1.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: fallback;
}
@font-face {
font-family: 'Name';
src: url('/assets/fonts/bold-fb2676462a-v1.eot');
src: url('/assets/fonts/bold-fb2676462a-v1.eot?#iefix')
format('embedded-opentype'),
url('/assets/fonts/bold-a2452cb66f-v1.woff2') format('woff2'),
url('/assets/fonts/bold-f38c792ac2-v1.woff') format('woff');
font-weight: bold;
font-style: normal;
font-display: fallback;
}
@font-face {
font-family: 'ntatabularnumbers';
src: url('/assets/fonts/light-tabular-498ea8ffe2-v1.eot');
src: url('/assets/fonts/light-tabular-498ea8ffe2-v1.eot?#iefix')
format('embedded-opentype'),
url('/assets/fonts/light-tabular-851b10ccdd-v1.woff2') format('woff2'),
url('/assets/fonts/light-tabular-62cc6f0a28-v1.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: fallback;
}
@font-face {
font-family: 'ntatabularnumbers';
src: url('/assets/fonts/bold-tabular-357fdfbcc3-v1.eot');
src: url('/assets/fonts/bold-tabular-357fdfbcc3-v1.eot?#iefix')
format('embedded-opentype'),
url('/assets/fonts/bold-tabular-b89238d840-v1.woff2') format('woff2'),
url('/assets/fonts/bold-tabular-784c21afb8-v1.woff') format('woff');
font-weight: bold;
font-style: normal;
font-display: fallback;
}
@media print {
.g-link {
font-family: sans-serif;
}
}
.g-link:focus,
.g-link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.g-link:link,
.g-link.\:link {
color: #005ea5;
}
.g-link:visited,
.g-link.\:visited {
color: #4c2c92;
}
.g-link:hover,
.g-link.\:hover {
color: #2b8cc4;
}
.g-link:active,
.g-link.\:active {
color: #2b8cc4;
}
.g-link:focus,
.g-link.\:focus {
color: #0b0c0c;
}
@media print {
.g-link[href^="/"]::after, .g-link[href^="http://"]::after, .g-link[href^="https://"]::after,
.g-link[href^="http.\://"]::after,
.g-link[href^="https.\://"]::after {
content: ' (' attr(href) ')';
font-size: 90%;
word-wrap: break-word;
}
}
.g-link--muted:link,
.g-link--muted:visited,
.g-link--muted:hover,
.g-link--muted:active,
.g-link--muted.\:link,
.g-link--muted.\:visited,
.g-link--muted.\:hover,
.g-link--muted.\:active {
color: #6f777b;
}
.g-link--muted:focus,
.g-link--muted.\:focus {
color: #0b0c0c;
}
.g-link--text-colour:link,
.g-link--text-colour:visited,
.g-link--text-colour:hover,
.g-link--text-colour:active,
.g-link--text-colour:focus,
.g-link--text-colour.\:link,
.g-link--text-colour.\:visited,
.g-link--text-colour.\:hover,
.g-link--text-colour.\:active,
.g-link--text-colour.\:focus {
color: #0b0c0c;
}
@media print {
.g-link--text-colour:link,
.g-link--text-colour:visited,
.g-link--text-colour:hover,
.g-link--text-colour:active,
.g-link--text-colour:focus,
.g-link--text-colour.\:link,
.g-link--text-colour.\:visited,
.g-link--text-colour.\:hover,
.g-link--text-colour.\:active,
.g-link--text-colour.\:focus {
color: #000000;
}
}
.g-link--no-visited-state:link,
.g-link--no-visited-state.\:link {
color: #005ea5;
}
.g-link--no-visited-state:visited,
.g-link--no-visited-state.\:visited {
color: #005ea5;
}
.g-link--no-visited-state:hover,
.g-link--no-visited-state.\:hover {
color: #2b8cc4;
}
.g-link--no-visited-state:active,
.g-link--no-visited-state.\:active {
color: #2b8cc4;
}
.g-link--no-visited-state:focus,
.g-link--no-visited-state.\:focus {
color: #0b0c0c;
}
.g-list {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 1.25rem;
font-size: 1.25rem;
line-height: 1.625;
color: #2a2a2a;
margin-top: 0;
margin-bottom: 1rem;
padding-left: 0;
list-style-type: none;
}
@media print {
.g-list {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-list {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-list {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-list {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-list {
margin-bottom: 1rem;
}
}
.g-list .g-list {
margin-top: 10px;
}
.g-list > li {
margin-bottom: 0.25rem;
}
.g-list--bullet {
padding-left: 20px;
list-style-type: disc;
}
.g-list--number {
padding-left: 20px;
list-style-type: decimal;
}
.g-list--bullet > li,
.g-list--number > li {
margin-bottom: 0;
}
@media (min-width: 40.0625em) {
.g-list--bullet > li,
.g-list--number > li {
margin-bottom: 5px;
}
}
.g-template {
background-color: #dee0e2;
-webkit-text-size-adjust: 100%;
-moz-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
text-size-adjust: 100%;
}
@media screen {
.g-template {
overflow-y: scroll;
}
}
.g-template__body {
margin: 0;
background-color: #ffffff;
}
.g-heading-xl {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 3rem;
font-size: 3rem;
line-height: 1.125;
display: block;
margin-top: 0;
margin-bottom: 1rem;
}
@media print {
.g-heading-xl {
color: #000000;
}
}
@media print {
.g-heading-xl {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-xl {
font-size: 3.5rem;
font-size: 3.5rem;
line-height: 1.15;
}
}
@media print {
.g-heading-xl {
font-size: 32pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-heading-xl {
margin-bottom: 1rem;
}
}
.g-heading-l {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 2rem;
font-size: 2rem;
line-height: 1.2;
display: block;
margin-top: 3.5rem;
margin-bottom: 0.5rem;
}
@media print {
.g-heading-l {
color: #000000;
}
}
@media print {
.g-heading-l {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-l {
font-size: 2.5rem;
font-size: 2.5rem;
line-height: 1.25;
}
}
@media print {
.g-heading-l {
font-size: 24pt;
line-height: 1.05;
}
}
@media (min-width: 40.0625em) {
.g-heading-l {
margin-bottom: 30px;
}
}
.g-heading-m {
color: #0b0c0c;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 1.5rem;
font-size: 1.5rem;
line-height: 1.25;
display: block;
margin-top: 2.5rem;
margin-bottom: 0.5rem;
}
@media print {
.g-heading-m {
color: #000000;
}
}
@media print {
.g-heading-m {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-m {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-heading-m {
font-size: 18pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-heading-m {
margin-bottom: 0.5rem;
}
}
.g-heading-s {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 1.25rem;
font-size: 1.25rem;
line-height: 1.25;
display: block;
margin-top: 2.5rem;
margin-bottom: 0.5rem;
}
@media print {
.g-heading-s {
color: #000000;
}
}
@media print {
.g-heading-s {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-s {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-heading-s {
font-size: 14pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-heading-s {
margin-bottom: 0.5rem;
}
}
.g-caption-xl {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
display: block;
margin-bottom: 5px;
color: #6f777b;
}
@media print {
.g-caption-xl {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-caption-xl {
font-size: 27px;
font-size: 1.6875rem;
line-height: 1.11111;
}
}
@media print {
.g-caption-xl {
font-size: 18pt;
line-height: 1.15;
}
}
.g-caption-l {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
display: block;
margin-bottom: 5px;
color: #6f777b;
}
@media print {
.g-caption-l {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-caption-l {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-caption-l {
font-size: 18pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-caption-l {
margin-bottom: 0;
}
}
.g-caption-m {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: block;
color: #6f777b;
}
@media print {
.g-caption-m {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-caption-m {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-caption-m {
font-size: 14pt;
line-height: 1.15;
}
}
.g-body-l,
.g-body-lead {
color: #0b0c0c;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
margin-top: 0;
margin-bottom: 20px;
}
@media print {
.g-body-l,
.g-body-lead {
color: #000000;
}
}
@media print {
.g-body-l,
.g-body-lead {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-body-l,
.g-body-lead {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-body-l,
.g-body-lead {
font-size: 18pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-body-l,
.g-body-lead {
margin-bottom: 30px;
}
}
.g-body-m,
.g-body {
color: #0b0c0c;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
margin-top: 0;
margin-bottom: 15px;
}
@media print {
.g-body-m,
.g-body {
color: #000000;
}
}
@media print {
.g-body-m,
.g-body {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-body-m,
.g-body {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-body-m,
.g-body {
font-size: 14pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-body-m,
.g-body {
margin-bottom: 20px;
}
}
.g-body-s {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.625;
margin-top: 0;
margin-bottom: 1rem;
}
@media print {
.g-body-s {
color: #000000;
}
}
@media print {
.g-body-s {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-body-s {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-body-s {
font-size: 14pt;
line-height: 1.2;
}
}
@media (min-width: 40.0625em) {
.g-body-s {
margin-bottom: 20px;
}
}
.g-body-xs {
color: #0b0c0c;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 12px;
font-size: 0.75rem;
line-height: 1.25;
margin-top: 0;
margin-bottom: 15px;
}
@media print {
.g-body-xs {
color: #000000;
}
}
@media print {
.g-body-xs {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-body-xs {
font-size: 14px;
font-size: 0.875rem;
line-height: 1.42857;
}
}
@media print {
.g-body-xs {
font-size: 12pt;
line-height: 1.2;
}
}
@media (min-width: 40.0625em) {
.g-body-xs {
margin-bottom: 20px;
}
}
.g-body-l + .g-heading-l,
.g-body-lead + .g-heading-l {
padding-top: 5px;
}
@media (min-width: 40.0625em) {
.g-body-l + .g-heading-l,
.g-body-lead + .g-heading-l {
padding-top: 10px;
}
}
.g-body-m + .g-heading-l,
.g-body + .g-heading-l,
.g-body-s + .g-heading-l,
.g-list + .g-heading-l {
padding-top: 15px;
}
@media (min-width: 40.0625em) {
.g-body-m + .g-heading-l,
.g-body + .g-heading-l,
.g-body-s + .g-heading-l,
.g-list + .g-heading-l {
padding-top: 20px;
}
}
.g-body-m + .g-heading-m,
.g-body + .g-heading-m,
.g-body-s + .g-heading-m,
.g-list + .g-heading-m,
.g-body-m + .g-heading-s,
.g-body + .g-heading-s,
.g-body-s + .g-heading-s,
.g-list + .g-heading-s {
padding-top: 5px;
}
@media (min-width: 40.0625em) {
.g-body-m + .g-heading-m,
.g-body + .g-heading-m,
.g-body-s + .g-heading-m,
.g-list + .g-heading-m,
.g-body-m + .g-heading-s,
.g-body + .g-heading-s,
.g-body-s + .g-heading-s,
.g-list + .g-heading-s {
padding-top: 10px;
}
}
.g-section-break {
margin: 0;
border: 0;
}
.g-section-break--xl {
margin-top: 30px;
margin-bottom: 30px;
}
@media (min-width: 40.0625em) {
.g-section-break--xl {
margin-top: 50px;
}
}
@media (min-width: 40.0625em) {
.g-section-break--xl {
margin-bottom: 50px;
}
}
.g-section-break--l {
margin-top: 20px;
margin-bottom: 20px;
}
@media (min-width: 40.0625em) {
.g-section-break--l {
margin-top: 30px;
}
}
@media (min-width: 40.0625em) {
.g-section-break--l {
margin-bottom: 30px;
}
}
.g-section-break--m {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 40.0625em) {
.g-section-break--m {
margin-top: 20px;
}
}
@media (min-width: 40.0625em) {
.g-section-break--m {
margin-bottom: 20px;
}
}
.g-section-break--visible {
border-bottom: 1px solid #bfc1c3;
}
.g-form-group {
margin-bottom: 20px;
}
.g-form-group:after {
content: '';
display: block;
clear: both;
}
@media (min-width: 40.0625em) {
.g-form-group {
margin-bottom: 30px;
}
}
.g-form-group .g-form-group:last-of-type,
.g-form-group .g-form-group.\:last-of-type {
margin-bottom: 0;
}
.g-form-group--error {
padding-left: 15px;
border-left: 5px solid #b10e1e;
}
.g-form-group--error .g-form-group {
padding: 0;
border: 0;
}
.g-grid-row {
margin-right: -15px;
margin-left: -15px;
}
.g-grid-row:after {
content: '';
display: block;
clear: both;
}
.g-grid-column-one-quarter {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-one-quarter {
width: 25%;
float: left;
}
}
.g-grid-column-one-third {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-one-third {
width: 33.3333%;
float: left;
}
}
.g-grid-column-one-half {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-one-half {
width: 50%;
float: left;
}
}
.g-grid-column-two-thirds {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-two-thirds {
width: 66.6666%;
float: left;
}
}
.g-grid-column-three-quarters {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-three-quarters {
width: 75%;
float: left;
}
}
.g-grid-column-full {
box-sizing: border-box;
width: 100%;
padding: 0 15px;
}
@media (min-width: 40.0625em) {
.g-grid-column-full {
width: 100%;
float: left;
}
}
.g-grid-column-one-quarter-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-one-quarter-from-desktop {
width: 25%;
float: left;
}
}
.g-grid-column-one-third-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-one-third-from-desktop {
width: 33.3333%;
float: left;
}
}
.g-grid-column-one-half-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-one-half-from-desktop {
width: 50%;
float: left;
}
}
.g-grid-column-two-thirds-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-two-thirds-from-desktop {
width: 66.6666%;
float: left;
}
}
.g-grid-column-three-quarters-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-three-quarters-from-desktop {
width: 75%;
float: left;
}
}
.g-grid-column-full-from-desktop {
box-sizing: border-box;
padding: 0 15px;
}
@media (min-width: 48.0625em) {
.g-grid-column-full-from-desktop {
width: 100%;
float: left;
}
}
.g-main-wrapper {
display: block;
padding-top: 20px;
padding-bottom: 20px;
}
@media (min-width: 40.0625em) {
.g-main-wrapper {
padding-top: 40px;
padding-bottom: 40px;
}
}
.g-main-wrapper--l {
padding-top: 30px;
}
@media (min-width: 40.0625em) {
.g-main-wrapper--l {
padding-top: 50px;
}
}
.g-width-container {
max-width: 960px;
margin: 0 15px;
}
@supports (margin: max(calc(0px))) {
.g-width-container {
margin-right: max(15px, calc(15px + env(safe-area-inset-right)));
margin-left: max(15px, calc(15px + env(safe-area-inset-left)));
}
}
@media (min-width: 40.0625em) {
.g-width-container {
margin: 0 30px;
}
@supports (margin: max(calc(0px))) {
.g-width-container {
margin-right: max(30px, calc(15px + env(safe-area-inset-right)));
margin-left: max(30px, calc(15px + env(safe-area-inset-left)));
}
}
}
@media (min-width: 1020px) {
.g-width-container {
margin: 0 auto;
}
@supports (margin: max(calc(0px))) {
.g-width-container {
margin: 0 auto;
}
}
}
.g-accordion {
margin-bottom: 20px;
}
@media (min-width: 40.0625em) {
.g-accordion {
margin-bottom: 30px;
}
}
.g-accordion__section {
padding-top: 15px;
}
.g-accordion__section-header {
padding-bottom: 15px;
}
.g-accordion__section-heading {
margin-top: 0;
margin-bottom: 0;
}
.g-accordion__section-button {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
display: inline-block;
margin-bottom: 0;
padding-top: 15px;
}
@media print {
.g-accordion__section-button {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-accordion__section-button {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-accordion__section-button {
font-size: 18pt;
line-height: 1.15;
}
}
.g-accordion__section-summary {
margin-top: 10px;
margin-bottom: 0;
}
.g-accordion__section-content > :last-child,
.g-accordion__section-content > .\:last-child {
margin-bottom: 0;
}
.js-enabled .g-accordion {
border-bottom: 1px solid #bfc1c3;
}
.js-enabled .g-accordion__section {
padding-top: 0;
border-top: 1px solid #bfc1c3;
}
.js-enabled .g-accordion__section-content {
display: none;
padding-top: 15px;
padding-bottom: 15px;
}
@media (min-width: 40.0625em) {
.js-enabled .g-accordion__section-content {
padding-top: 15px;
}
}
@media (min-width: 40.0625em) {
.js-enabled .g-accordion__section-content {
padding-bottom: 15px;
}
}
.js-enabled .g-accordion__section--expanded .g-accordion__section-content {
display: block;
}
.js-enabled .g-accordion__open-all {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
display: inline;
border-width: 0;
color: #005ea5;
background: none;
cursor: pointer;
}
@media print {
.js-enabled .g-accordion__open-all {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.js-enabled .g-accordion__open-all {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.js-enabled .g-accordion__open-all {
font-size: 14pt;
line-height: 1.2;
}
}
@media print {
.js-enabled .g-accordion__open-all {
font-family: sans-serif;
}
}
.js-enabled .g-accordion__open-all:focus,
.js-enabled .g-accordion__open-all.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.js-enabled .g-accordion__open-all:focus,
.js-enabled .g-accordion__open-all.\:focus {
background: none;
}
.js-enabled .g-accordion__section-header {
position: relative;
padding-right: 40px;
cursor: pointer;
}
.js-enabled .g-accordion__section-header:hover,
.js-enabled .g-accordion__section-header.\:hover {
background-color: #f8f8f8;
}
@media (hover: none) {
.js-enabled .g-accordion__section-header:hover,
.js-enabled .g-accordion__section-header.\:hover {
background-color: initial;
}
}
.js-enabled .g-accordion__section-header--focused {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.js-enabled .g-accordion__section-button {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: 100%;
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
padding-top: 15px;
padding-bottom: 0;
padding-left: 0;
border-width: 0;
color: #005ea5;
background: none;
text-align: left;
cursor: pointer;
}
@media print {
.js-enabled .g-accordion__section-button {
font-family: sans-serif;
}
}
.js-enabled .g-accordion__section-button:focus,
.js-enabled .g-accordion__section-button.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.js-enabled .g-accordion__section-button:focus,
.js-enabled .g-accordion__section-button.\:focus {
outline: none;
background: none;
}
.js-enabled .g-accordion__section-button:after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.js-enabled .g-accordion__controls {
text-align: right;
}
.js-enabled .g-accordion__icon {
position: absolute;
top: 50%;
right: 15px;
width: 16px;
height: 16px;
margin-top: -8px;
}
.js-enabled .g-accordion__icon:after,
.js-enabled .g-accordion__icon:before {
content: '';
box-sizing: border-box;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 25%;
height: 25%;
margin: auto;
border: 2px solid transparent;
background-color: #0b0c0c;
}
.js-enabled .g-accordion__icon:before {
width: 100%;
}
.js-enabled .g-accordion__icon:after {
height: 100%;
}
.js-enabled .g-accordion__section--expanded .g-accordion__icon:after {
content: ' ';
display: none;
}
.g-back-link {
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
display: inline-block;
position: relative;
margin-top: 15px;
margin-bottom: 15px;
padding-left: 14px;
border-bottom: 1px solid #0b0c0c;
text-decoration: none;
}
@media (min-width: 40.0625em) {
.g-back-link {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-back-link {
font-size: 14pt;
line-height: 1.2;
}
}
@media print {
.g-back-link {
font-family: sans-serif;
}
}
.g-back-link:focus,
.g-back-link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-back-link:link,
.g-back-link:visited,
.g-back-link:hover,
.g-back-link:active,
.g-back-link:focus,
.g-back-link.\:link,
.g-back-link.\:visited,
.g-back-link.\:hover,
.g-back-link.\:active,
.g-back-link.\:focus {
color: #0b0c0c;
}
@media print {
.g-back-link:link,
.g-back-link:visited,
.g-back-link:hover,
.g-back-link:active,
.g-back-link:focus,
.g-back-link.\:link,
.g-back-link.\:visited,
.g-back-link.\:hover,
.g-back-link.\:active,
.g-back-link.\:focus {
color: #000000;
}
}
.g-back-link:before {
display: block;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
-webkit-clip-path: polygon(0% 50%, 100% 100%, 100% 0%);
clip-path: polygon(0% 50%, 100% 100%, 100% 0%);
border-width: 5px 6px 5px 0;
border-right-color: inherit;
content: '';
position: absolute;
top: -1px;
bottom: 1px;
left: 0;
margin: auto;
}
.g-back-link:before {
top: -1px;
bottom: 1px;
}
.g-breadcrumbs {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
color: #0b0c0c;
margin-top: 15px;
margin-bottom: 10px;
}
@media print {
.g-breadcrumbs {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-breadcrumbs {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-breadcrumbs {
font-size: 14pt;
line-height: 1.2;
}
}
@media print {
.g-breadcrumbs {
color: #000000;
}
}
.g-breadcrumbs__list {
margin: 0;
padding: 0;
list-style-type: none;
}
.g-breadcrumbs__list:after {
content: '';
display: block;
clear: both;
}
.g-breadcrumbs__list-item {
display: inline-block;
position: relative;
margin-bottom: 5px;
margin-left: 10px;
padding-left: 15.655px;
float: left;
}
.g-breadcrumbs__list-item:before {
content: '';
display: block;
position: absolute;
top: -1px;
bottom: 1px;
left: -3.31px;
width: 7px;
height: 7px;
margin: auto 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
border: solid;
border-width: 1px 1px 0 0;
border-color: #6f777b;
}
.g-breadcrumbs__list-item:first-child,
.g-breadcrumbs__list-item.\:first-child {
margin-left: 0;
padding-left: 0;
}
.g-breadcrumbs__list-item:first-child:before,
.g-breadcrumbs__list-item.\:first-child:before {
content: none;
display: none;
}
.g-breadcrumbs__link {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
@media print {
.g-breadcrumbs__link {
font-family: sans-serif;
}
}
.g-breadcrumbs__link:focus,
.g-breadcrumbs__link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-breadcrumbs__link:link,
.g-breadcrumbs__link:visited,
.g-breadcrumbs__link:hover,
.g-breadcrumbs__link:active,
.g-breadcrumbs__link:focus,
.g-breadcrumbs__link.\:link,
.g-breadcrumbs__link.\:visited,
.g-breadcrumbs__link.\:hover,
.g-breadcrumbs__link.\:active,
.g-breadcrumbs__link.\:focus {
color: #0b0c0c;
}
@media print {
.g-breadcrumbs__link:link,
.g-breadcrumbs__link:visited,
.g-breadcrumbs__link:hover,
.g-breadcrumbs__link:active,
.g-breadcrumbs__link:focus,
.g-breadcrumbs__link.\:link,
.g-breadcrumbs__link.\:visited,
.g-breadcrumbs__link.\:hover,
.g-breadcrumbs__link.\:active,
.g-breadcrumbs__link.\:focus {
color: #000000;
}
}
.g-button {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 500;
font-size: 20px;
font-size: 20px;
line-height: 1.2;
box-sizing: border-box;
display: inline-block;
position: relative;
width: 100%;
margin-top: 0;
margin-bottom: 22px;
padding: 16px;
border: 2px solid transparent;
border-radius: 4px;
color: #ffffff;
background-color: #00823b;
box-shadow: 0 2px 0 0 #2a2a2a;
text-align: center;
vertical-align: top;
cursor: pointer;
-webkit-appearance: none;
}
@media print {
.g-button {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-button {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1;
}
}
@media print {
.g-button {
font-size: 14pt;
line-height: 19px;
}
}
.g-button:focus,
.g-button.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
@media (min-width: 40.0625em) {
.g-button {
margin-bottom: 32px;
}
}
@media (min-width: 40.0625em) {
.g-button {
width: auto;
}
}
.g-button:link,
.g-button:visited,
.g-button:active,
.g-button:hover,
.g-button.\:link,
.g-button.\:visited,
.g-button.\:active,
.g-button.\:hover {
color: #ffffff;
text-decoration: none;
}
.g-button::-moz-focus-inner {
padding: 0;
border: 0;
}
.g-button:hover,
.g-button:focus,
.g-button.\:hover,
.g-button.\:focus {
background-color: #00682f;
}
.g-button:active,
.g-button.\:active {
top: 2px;
box-shadow: none;
}
.g-button::before {
content: '';
display: block;
position: absolute;
top: -2px;
right: -2px;
bottom: -4px;
left: -2px;
background: transparent;
}
.g-button:active::before,
.g-button.\:active::before {
top: -4px;
}
.g-button--disabled,
.g-button[disabled='disabled'],
.g-button[disabled] {
opacity: 0.5;
background: #00823b;
}
.g-button--disabled:hover,
.g-button[disabled='disabled']:hover,
.g-button[disabled]:hover,
.g-button--disabled.\:hover,
.g-button[disabled='disabled'].\:hover,
.g-button[disabled].\:hover {
background-color: #00823b;
cursor: default;
}
.g-button--disabled:focus,
.g-button[disabled='disabled']:focus,
.g-button[disabled]:focus,
.g-button--disabled.\:focus,
.g-button[disabled='disabled'].\:focus,
.g-button[disabled].\:focus {
outline: none;
}
.g-button--disabled:active,
.g-button[disabled='disabled']:active,
.g-button[disabled]:active,
.g-button--disabled.\:active,
.g-button[disabled='disabled'].\:active,
.g-button[disabled].\:active {
top: 0;
box-shadow: 0 2px 0 #003418;
}
.g-button--secondary {
background-color: #dee0e2;
box-shadow: 0 2px 0 #858688;
}
.g-button--secondary,
.g-button--secondary:link,
.g-button--secondary:visited,
.g-button--secondary:active,
.g-button--secondary:hover,
.g-button--secondary.\:link,
.g-button--secondary.\:visited,
.g-button--secondary.\:active,
.g-button--secondary.\:hover {
color: #0b0c0c;
}
.g-button--secondary:hover,
.g-button--secondary:focus,
.g-button--secondary.\:hover,
.g-button--secondary.\:focus {
background-color: #c8cacb;
}
.g-button--warning {
background-color: #b10e1e;
box-shadow: 0 2px 0 #47060c;
}
.g-button--warning,
.g-button--warning:link,
.g-button--warning:visited,
.g-button--warning:active,
.g-button--warning:hover,
.g-button--warning.\:link,
.g-button--warning.\:visited,
.g-button--warning.\:active,
.g-button--warning.\:hover {
color: #ffffff;
}
.g-button--warning:hover,
.g-button--warning:focus,
.g-button--warning.\:hover,
.g-button--warning.\:focus {
background-color: #8e0b18;
}
.g-button--start {
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1;
min-height: auto;
padding-top: 8px;
padding-right: 40px;
padding-bottom: 8px;
padding-left: 15px;
background-image: url('/assets/images/icon-pointer.png');
background-repeat: no-repeat;
background-position: 100% 50%;
}
@media (min-width: 40.0625em) {
.g-button--start {
font-size: 24px;
font-size: 1.5rem;
line-height: 1;
}
}
@media print {
.g-button--start {
font-size: 18pt;
line-height: 1;
}
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2),
only screen and (min-resolution: 192dpi),
only screen and (min-resolution: 2dppx) {
.g-button--start {
background-image: url('/assets/images/icon-pointer-2x.png');
background-size: 30px 19px;
}
}
.g-button {
padding-top: 16px;
padding-bottom: 16px;
}
.g-button--start {
padding-top: 9px;
padding-bottom: 6px;
}
.g-error-message {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: block;
margin-bottom: 15px;
clear: both;
color: #b10e1e;
}
@media print {
.g-error-message {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-error-message {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-error-message {
font-size: 14pt;
line-height: 1.15;
}
}
.g-fieldset {
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.g-fieldset:after {
content: '';
display: block;
clear: both;
}
@supports not (caret-color: auto) {
.g-fieldset,
x:-moz-any-link,
x.\:-moz-any-link {
display: table-cell;
}
}
.g-fieldset__legend {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
box-sizing: border-box;
display: table;
max-width: 100%;
margin-bottom: 0px;
padding: 0;
overflow: hidden;
white-space: normal;
}
@media print {
.g-fieldset__legend {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-fieldset__legend {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-fieldset__legend {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-fieldset__legend {
color: #000000;
}
}
.g-fieldset__legend--xl {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 32px;
font-size: 2rem;
line-height: 1.09375;
margin-bottom: 15px;
}
@media print {
.g-fieldset__legend--xl {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-fieldset__legend--xl {
font-size: 48px;
font-size: 3rem;
line-height: 1.04167;
}
}
@media print {
.g-fieldset__legend--xl {
font-size: 32pt;
line-height: 1.15;
}
}
.g-fieldset__legend--l {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 24px;
font-size: 1.5rem;
line-height: 1.04167;
margin-bottom: 15px;
}
@media print {
.g-fieldset__legend--l {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-fieldset__legend--l {
font-size: 36px;
font-size: 2.25rem;
line-height: 1.11111;
}
}
@media print {
.g-fieldset__legend--l {
font-size: 24pt;
line-height: 1.05;
}
}
.g-fieldset__legend--m {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
margin-bottom: 15px;
}
@media print {
.g-fieldset__legend--m {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-fieldset__legend--m {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-fieldset__legend--m {
font-size: 18pt;
line-height: 1.15;
}
}
.g-fieldset__legend--s {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
@media print {
.g-fieldset__legend--s {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-fieldset__legend--s {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-fieldset__legend--s {
font-size: 14pt;
line-height: 1.15;
}
}
.g-fieldset__heading {
margin: 0;
font-size: inherit;
font-weight: inherit;
}
.g-hint {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: block;
margin-bottom: 15px;
color: #595959;
}
@media print {
.g-hint {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-hint {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-hint {
font-size: 14pt;
line-height: 1.15;
}
}
.g-label:not(.g-label--m):not(.g-label--l):not(.g-label--xl) + .g-hint,
.g-label.\:not\(.g-label--m\).\:not\(.g-label--l\).\:not\(.g-label--xl\)
+ .g-hint {
margin-bottom: 10px;
}
.g-fieldset__legend:not(.g-fieldset__legend--m):not(.g-fieldset__legend--l):not(.g-fieldset__legend--xl)
+ .g-hint,
.g-fieldset__legend.\:not\(.g-fieldset__legend--m\).\:not\(.g-fieldset__legend--l\).\:not\(.g-fieldset__legend--xl\)
+ .g-hint {
margin-bottom: 10px;
}
.g-fieldset__legend + .g-hint,
.g-fieldset__legend + .g-hint {
margin-top: -5px;
}
.g-label {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: bold;
font-size: 1.25rem;
font-size: 1.25rem;
line-height: 1.25;
color: #2a2a2a;
display: block;
margin-bottom: 5px;
}
@media print {
.g-label {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-label {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-label {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-label {
color: #000000;
}
}
.g-label--xl {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 32px;
font-size: 2rem;
line-height: 1.09375;
margin-bottom: 15px;
}
@media print {
.g-label--xl {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-label--xl {
font-size: 48px;
font-size: 3rem;
line-height: 1.04167;
}
}
@media print {
.g-label--xl {
font-size: 32pt;
line-height: 1.15;
}
}
.g-label--l {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 24px;
font-size: 1.5rem;
line-height: 1.04167;
margin-bottom: 15px;
}
@media print {
.g-label--l {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-label--l {
font-size: 36px;
font-size: 2.25rem;
line-height: 1.11111;
}
}
@media print {
.g-label--l {
font-size: 24pt;
line-height: 1.05;
}
}
.g-label--m {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
margin-bottom: 10px;
}
@media print {
.g-label--m {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-label--m {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-label--m {
font-size: 18pt;
line-height: 1.15;
}
}
.g-label--s {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
@media print {
.g-label--s {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-label--s {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-label--s {
font-size: 14pt;
line-height: 1.15;
}
}
.g-label-wrapper {
margin: 0;
}
.g-checkboxes__item {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 40px;
margin-bottom: 16px;
padding-left: 40px;
clear: left;
}
@media print {
.g-checkboxes__item {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-checkboxes__item {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-checkboxes__item {
font-size: 14pt;
line-height: 1.15;
}
}
.g-checkboxes__item:last-child,
.g-checkboxes__item:last-of-type,
.g-checkboxes__item.\:last-child,
.g-checkboxes__item.\:last-of-type {
margin-bottom: 0;
}
.g-checkboxes__input {
cursor: pointer;
position: absolute;
z-index: 1;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
margin: 0;
opacity: 0;
}
.g-checkboxes__label {
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
-ms-touch-action: manipulation;
touch-action: manipulation;
}
.g-checkboxes__label::before {
content: '';
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 40px;
border: 2px solid currentColor;
background: transparent;
}
.g-checkboxes__label::after {
content: '';
position: absolute;
top: 11px;
left: 9px;
width: 18px;
height: 7px;
-webkit-transform: rotate(-45deg);
-ms-transform: rotate(-45deg);
transform: rotate(-45deg);
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
opacity: 0;
background: transparent;
}
.g-checkboxes__hint {
display: block;
padding-right: 15px;
padding-left: 15px;
}
.g-checkboxes__input:focus + .g-checkboxes__label::before,
.g-checkboxes__input.\:focus + .g-checkboxes__label::before {
outline: 3px solid transparent;
outline-offset: 3px;
box-shadow: 0 0 0 3px #ffbf47;
}
.g-checkboxes__input:checked + .g-checkboxes__label::after,
.g-checkboxes__input.\:checked + .g-checkboxes__label::after {
opacity: 1;
}
.g-checkboxes__input:disabled,
.g-checkboxes__input:disabled + .g-checkboxes__label,
.g-checkboxes__input.\:disabled,
.g-checkboxes__input.\:disabled + .g-checkboxes__label {
cursor: default;
}
.g-checkboxes__input:disabled + .g-checkboxes__label,
.g-checkboxes__input.\:disabled + .g-checkboxes__label {
opacity: 0.5;
}
.g-checkboxes__conditional {
margin-bottom: 15px;
margin-left: 18px;
padding-left: 33px;
border-left: 4px solid #bfc1c3;
}
@media (min-width: 40.0625em) {
.g-checkboxes__conditional {
margin-bottom: 20px;
}
}
.js-enabled .g-checkboxes__conditional--hidden {
display: none;
}
.g-checkboxes__conditional > :last-child,
.g-checkboxes__conditional > .\:last-child {
margin-bottom: 0;
}
.g-checkboxes--small .g-checkboxes__item {
min-height: 0;
margin-bottom: 0;
padding-left: 34px;
float: left;
}
.g-checkboxes--small .g-checkboxes__item:after {
content: '';
display: block;
clear: both;
}
.g-checkboxes--small .g-checkboxes__input {
left: -10px;
}
.g-checkboxes--small .g-checkboxes__label {
margin-top: -2px;
padding: 13px 15px 13px 1px;
float: left;
}
@media (min-width: 40.0625em) {
.g-checkboxes--small .g-checkboxes__label {
padding: 11px 15px 10px 1px;
}
}
.g-checkboxes--small .g-checkboxes__label::before {
top: 8px;
width: 24px;
height: 24px;
}
.g-checkboxes--small .g-checkboxes__label::after {
top: 15px;
left: 6px;
width: 9px;
height: 3.5px;
border-width: 0 0 3px 3px;
}
.g-checkboxes--small .g-checkboxes__hint {
padding: 0;
clear: both;
}
.g-checkboxes--small .g-checkboxes__conditional {
margin-left: 10px;
padding-left: 20px;
clear: both;
}
.g-checkboxes--small
.g-checkboxes__item:hover
.g-checkboxes__input:not(:disabled)
+ .g-checkboxes__label::before,
.g-checkboxes--small
.g-checkboxes__item.\:hover
.g-checkboxes__input:not(:disabled)
+ .g-checkboxes__label::before {
box-shadow: 0 0 0 10px #dee0e2;
}
.g-checkboxes--small
.g-checkboxes__item:hover
.g-checkboxes__input:focus
+ .g-checkboxes__label::before,
.g-checkboxes--small
.g-checkboxes__item.\:hover
.g-checkboxes__input.\:focus
+ .g-checkboxes__label::before {
box-shadow: 0 0 0 3px #ffbf47, 0 0 0 10px #dee0e2;
}
@media (hover: none), (pointer: coarse) {
.g-checkboxes--small
.g-checkboxes__item:hover
.g-checkboxes__input:not(:disabled)
+ .g-checkboxes__label::before,
.g-checkboxes--small
.g-checkboxes__item.\:hover
.g-checkboxes__input:not(:disabled)
+ .g-checkboxes__label::before {
box-shadow: initial;
}
.g-checkboxes--small
.g-checkboxes__item:hover
.g-checkboxes__input:focus
+ .g-checkboxes__label::before,
.g-checkboxes--small
.g-checkboxes__item.\:hover
.g-checkboxes__input.\:focus
+ .g-checkboxes__label::before {
box-shadow: 0 0 0 3px #ffbf47;
}
}
.g-character-count {
margin-bottom: 20px;
}
@media (min-width: 40.0625em) {
.g-character-count {
margin-bottom: 30px;
}
}
.g-character-count .g-form-group,
.g-character-count .g-textarea {
margin-bottom: 5px;
}
.g-character-count .g-textarea--error {
padding: 3px;
}
.g-character-count__message {
margin-top: 0;
margin-bottom: 0;
}
.g-character-count__message--disabled {
visibility: hidden;
}
.g-summary-list {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
margin: 0;
margin-bottom: 20px;
}
@media print {
.g-summary-list {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-summary-list {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-summary-list {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-summary-list {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-summary-list {
display: table;
width: 100%;
table-layout: fixed;
}
}
@media (min-width: 40.0625em) {
.g-summary-list {
margin-bottom: 30px;
}
}
@media (max-width: 40.0525em) {
.g-summary-list__row {
margin-bottom: 15px;
border-bottom: 1px solid #bfc1c3;
}
}
@media (min-width: 40.0625em) {
.g-summary-list__row {
display: table-row;
}
}
.g-summary-list__key,
.g-summary-list__value,
.g-summary-list__actions {
margin: 0;
}
@media (min-width: 40.0625em) {
.g-summary-list__key,
.g-summary-list__value,
.g-summary-list__actions {
display: table-cell;
padding-right: 20px;
}
}
@media (min-width: 40.0625em) {
.g-summary-list__key,
.g-summary-list__value,
.g-summary-list__actions {
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #bfc1c3;
}
}
.g-summary-list__actions {
margin-bottom: 15px;
}
@media (min-width: 40.0625em) {
.g-summary-list__actions {
width: 20%;
padding-right: 0;
text-align: right;
}
}
.g-summary-list__key,
.g-summary-list__value {
word-wrap: break-word;
overflow-wrap: break-word;
}
.g-summary-list__key {
margin-bottom: 5px;
font-weight: 700;
}
@media (min-width: 40.0625em) {
.g-summary-list__key {
width: 30%;
}
}
@media (max-width: 40.0525em) {
.g-summary-list__value {
margin-bottom: 15px;
}
}
@media (min-width: 40.0625em) {
.g-summary-list__value {
width: 50%;
}
}
@media (min-width: 40.0625em) {
.g-summary-list__value:last-child,
.g-summary-list__value.\:last-child {
width: 70%;
}
}
.g-summary-list__value > p {
margin-bottom: 10px;
}
.g-summary-list__value > :last-child,
.g-summary-list__value > .\:last-child {
margin-bottom: 0;
}
.g-summary-list__actions-list {
width: 100%;
margin: 0;
padding: 0;
}
.g-summary-list__actions-list-item {
display: inline;
margin-right: 10px;
padding-right: 10px;
}
.g-summary-list__actions-list-item:not(:last-child) {
border-right: 1px solid #bfc1c3;
}
.g-summary-list__actions-list-item:last-child,
.g-summary-list__actions-list-item.\:last-child {
margin-right: 0;
padding-right: 0;
border: 0;
}
@media (max-width: 40.0525em) {
.g-summary-list--no-border .g-summary-list__row {
border: 0;
}
}
@media (min-width: 40.0625em) {
.g-summary-list--no-border .g-summary-list__key,
.g-summary-list--no-border .g-summary-list__value,
.g-summary-list--no-border .g-summary-list__actions {
padding-bottom: 11px;
border: 0;
}
}
@media (max-width: 40.0525em) {
.g-summary-list__row--no-border {
border: 0;
}
}
@media (min-width: 40.0625em) {
.g-summary-list__row--no-border .g-summary-list__key,
.g-summary-list__row--no-border .g-summary-list__value,
.g-summary-list__row--no-border .g-summary-list__actions {
padding-bottom: 11px;
border: 0;
}
}
.g-input {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
width: 100%;
height: 40px;
margin-top: 0;
padding: 0.5rem;
border: 1px solid #2a2a2a;
border-radius: 0;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
@media print {
.g-input {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-input {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-input {
font-size: 14pt;
line-height: 1.15;
}
}
.g-input:focus,
.g-input.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.g-input::-webkit-outer-spin-button,
.g-input::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
}
.g-input[type='number'] {
-moz-appearance: textfield;
}
.g-input--error {
border: 1px solid #b10e1e;
}
.g-input--width-30 {
max-width: 59ex;
}
.g-input--width-20 {
max-width: 41ex;
}
.g-input--width-10 {
max-width: 23ex;
}
.g-input--width-5 {
max-width: 10.8ex;
}
.g-input--width-4 {
max-width: 9ex;
}
.g-input--width-3 {
max-width: 7.2ex;
}
.g-input--width-2 {
max-width: 5.4ex;
}
.g-date-input {
font-size: 0;
}
.g-date-input:after {
content: '';
display: block;
clear: both;
}
.g-date-input__item {
display: inline-block;
margin-right: 20px;
margin-bottom: 0;
}
.g-date-input__label {
display: block;
}
.g-date-input__input {
margin-bottom: 0;
}
.g-details {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
margin-bottom: 20px;
display: block;
}
@media print {
.g-details {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-details {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-details {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-details {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-details {
margin-bottom: 30px;
}
}
.g-details__summary {
display: inline-block;
position: relative;
margin-bottom: 5px;
padding-left: 25px;
color: #005ea5;
cursor: pointer;
}
.g-details__summary-text {
text-decoration: underline;
}
.g-details__summary:hover,
.g-details__summary.\:hover {
color: #2b8cc4;
}
.g-details__summary:focus,
.g-details__summary.\:focus {
outline: 4px solid #ffbf47;
outline-offset: -1px;
color: #0b0c0c;
background: #ffbf47;
}
.g-details__summary::-webkit-details-marker {
display: none;
}
.g-details__summary:before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 0;
margin: auto;
display: block;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
-webkit-clip-path: polygon(0% 0%, 100% 50%, 0% 100%);
clip-path: polygon(0% 0%, 100% 50%, 0% 100%);
border-width: 7px 0 7px 12.124px;
border-left-color: inherit;
}
.g-details[open] > .g-details__summary:before {
display: block;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
-webkit-clip-path: polygon(0% 0%, 50% 100%, 100% 0%);
clip-path: polygon(0% 0%, 50% 100%, 100% 0%);
border-width: 12.124px 7px 0 7px;
border-top-color: inherit;
}
.g-details__text {
padding: 15px;
padding-left: 20px;
border-left: 5px solid #bfc1c3;
}
.g-details__text p {
margin-top: 0;
margin-bottom: 20px;
}
.g-details__text > :last-child,
.g-details__text > .\:last-child {
margin-bottom: 0;
}
.g-error-summary {
color: #0b0c0c;
padding: 15px;
margin-bottom: 30px;
border: 4px solid #b10e1e;
}
@media print {
.g-error-summary {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-error-summary {
padding: 20px;
}
}
@media (min-width: 40.0625em) {
.g-error-summary {
margin-bottom: 50px;
}
}
.g-error-summary:focus,
.g-error-summary.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
@media (min-width: 40.0625em) {
.g-error-summary {
border: 5px solid #b10e1e;
}
}
.g-error-summary__title {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
margin-top: 0;
margin-bottom: 15px;
}
@media print {
.g-error-summary__title {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-error-summary__title {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-error-summary__title {
font-size: 18pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-error-summary__title {
margin-bottom: 20px;
}
}
.g-error-summary__body {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
@media print {
.g-error-summary__body {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-error-summary__body {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-error-summary__body {
font-size: 14pt;
line-height: 1.15;
}
}
.g-error-summary__body p {
margin-top: 0;
margin-bottom: 15px;
}
@media (min-width: 40.0625em) {
.g-error-summary__body p {
margin-bottom: 20px;
}
}
.g-error-summary__list {
margin-top: 0;
margin-bottom: 0;
}
.g-error-summary__list a {
font-weight: 700;
}
.g-error-summary__list a:focus,
.g-error-summary__list a.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.g-error-summary__list a:link,
.g-error-summary__list a:visited,
.g-error-summary__list a:hover,
.g-error-summary__list a:active,
.g-error-summary__list a.\:link,
.g-error-summary__list a.\:visited,
.g-error-summary__list a.\:hover,
.g-error-summary__list a.\:active {
color: #b10e1e;
}
.g-error-summary__list a:focus,
.g-error-summary__list a.\:focus {
color: #0b0c0c;
}
.g-file-upload {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
}
@media print {
.g-file-upload {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-file-upload {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-file-upload {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-file-upload {
color: #000000;
}
}
.g-file-upload:focus,
.g-file-upload.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.g-file-upload--error {
border: 4px solid #b10e1e;
}
.g-footer {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
padding-top: 25px;
padding-bottom: 15px;
border-top: 1px solid #a1acb2;
color: #454a4c;
background: #dee0e2;
}
@media print {
.g-footer {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-footer {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-footer {
font-size: 14pt;
line-height: 1.2;
}
}
@media (min-width: 40.0625em) {
.g-footer {
padding-top: 40px;
}
}
@media (min-width: 40.0625em) {
.g-footer {
padding-bottom: 25px;
}
}
.g-footer__link:focus,
.g-footer__link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-footer__link:link,
.g-footer__link:visited,
.g-footer__link.\:link,
.g-footer__link.\:visited {
color: #454a4c;
}
.g-footer__link:hover,
.g-footer__link:active,
.g-footer__link.\:hover,
.g-footer__link.\:active {
color: #171819;
}
.g-footer__link:focus,
.g-footer__link.\:focus {
color: #0b0c0c;
}
.g-footer__section-break {
margin: 0;
margin-bottom: 30px;
border: 0;
border-bottom: 1px solid #bfc1c3;
}
@media (min-width: 40.0625em) {
.g-footer__section-break {
margin-bottom: 50px;
}
}
.g-footer__meta {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: -15px;
margin-left: -15px;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
}
.g-footer__meta-item {
margin-right: 15px;
margin-bottom: 25px;
margin-left: 15px;
}
.g-footer__meta-item--grow {
-webkit-box-flex: 1;
-webkit-flex: 1;
-ms-flex: 1;
flex: 1;
}
@media (max-width: 40.0525em) {
.g-footer__meta-item--grow {
-webkit-flex-basis: 320px;
-ms-flex-preferred-size: 320px;
flex-basis: 320px;
}
}
.g-footer__licence-logo {
display: inline-block;
margin-right: 10px;
vertical-align: top;
}
@media (max-width: 48.0525em) {
.g-footer__licence-logo {
margin-bottom: 15px;
}
}
.g-footer__licence-description {
display: inline-block;
}
.g-footer__copyright-logo {
display: inline-block;
min-width: 125px;
padding-top: 112px;
background-image: url('/assets/images/g-crest.png');
background-repeat: no-repeat;
background-position: 50% 0%;
background-size: 125px 102px;
text-align: center;
text-decoration: none;
white-space: nowrap;
}
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2),
only screen and (min-resolution: 192dpi),
only screen and (min-resolution: 2dppx) {
.g-footer__copyright-logo {
background-image: url('/assets/images/g-crest-2x.png');
}
}
.g-footer__inline-list {
margin-top: 0;
margin-bottom: 15px;
padding: 0;
}
.g-footer__meta-custom {
margin-bottom: 20px;
}
.g-footer__inline-list-item {
display: inline-block;
margin-right: 15px;
margin-bottom: 5px;
}
.g-footer__heading {
margin-bottom: 25px;
padding-bottom: 20px;
border-bottom: 1px solid #bfc1c3;
}
@media (min-width: 40.0625em) {
.g-footer__heading {
margin-bottom: 40px;
}
}
@media (max-width: 40.0525em) {
.g-footer__heading {
padding-bottom: 10px;
}
}
.g-footer__navigation {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
margin-right: -15px;
margin-left: -15px;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
.g-footer__section {
display: inline-block;
margin-right: 15px;
margin-bottom: 30px;
margin-left: 15px;
vertical-align: top;
-webkit-box-flex: 1;
-webkit-flex-grow: 1;
-ms-flex-positive: 1;
flex-grow: 1;
-webkit-flex-shrink: 1;
-ms-flex-negative: 1;
flex-shrink: 1;
}
@media (max-width: 48.0525em) {
.g-footer__section {
-webkit-flex-basis: 200px;
-ms-flex-preferred-size: 200px;
flex-basis: 200px;
}
}
@media (min-width: 48.0625em) {
.g-footer__section:first-child,
.g-footer__section.\:first-child {
-webkit-box-flex: 2;
-webkit-flex-grow: 2;
-ms-flex-positive: 2;
flex-grow: 2;
}
}
.g-footer__list {
margin: 0;
padding: 0;
list-style: none;
-webkit-column-gap: 30px;
-moz-column-gap: 30px;
column-gap: 30px;
}
@media (min-width: 48.0625em) {
.g-footer__list--columns-2 {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
}
.g-footer__list--columns-3 {
-webkit-column-count: 3;
-moz-column-count: 3;
column-count: 3;
}
}
.g-footer__list-item {
margin-bottom: 15px;
}
@media (min-width: 40.0625em) {
.g-footer__list-item {
margin-bottom: 20px;
}
}
.g-footer__list-item:last-child,
.g-footer__list-item.\:last-child {
margin-bottom: 0;
}
.g-header {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
border-bottom: 10px solid #ffffff;
color: #ffffff;
background: #0b0c0c;
}
@media print {
.g-header {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-header {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-header {
font-size: 14pt;
line-height: 1.2;
}
}
.g-header__container--full-width {
padding: 0 15px;
border-color: #005ea5;
}
.g-header__container--full-width .g-header__menu-button {
right: 15px;
}
.g-header__container {
position: relative;
margin-bottom: -10px;
padding-top: 10px;
border-bottom: 10px solid #005ea5;
}
.g-header__container:after {
content: '';
display: block;
clear: both;
}
.g-header__logotype {
margin-right: 5px;
}
.g-header__logotype-crown {
margin-right: 1px;
fill: currentColor;
vertical-align: middle;
}
.g-header__logotype-crown-fallback-image {
width: 36px;
height: 32px;
border: 0;
vertical-align: middle;
}
.g-header__product-name {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
display: inline-table;
padding-right: 10px;
}
@media print {
.g-header__product-name {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-header__product-name {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-header__product-name {
font-size: 18pt;
line-height: 1.15;
}
}
.g-header__link {
text-decoration: none;
}
.g-header__link:focus,
.g-header__link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-header__link:link,
.g-header__link:visited,
.g-header__link.\:link,
.g-header__link.\:visited {
color: #ffffff;
}
.g-header__link:hover,
.g-header__link.\:hover {
text-decoration: underline;
}
.g-header__link:focus,
.g-header__link.\:focus {
color: #0b0c0c;
}
.g-header__link--homepage {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
display: inline-block;
font-size: 30px;
line-height: 30px;
}
@media print {
.g-header__link--homepage {
font-family: sans-serif;
}
}
.g-header__link--homepage:link,
.g-header__link--homepage:visited,
.g-header__link--homepage.\:link,
.g-header__link--homepage.\:visited {
text-decoration: none;
}
.g-header__link--homepage:hover,
.g-header__link--homepage:active,
.g-header__link--homepage.\:hover,
.g-header__link--homepage.\:active {
margin-bottom: -1px;
border-bottom: 1px solid;
}
.g-header__link--service-name {
display: inline-block;
margin-bottom: 10px;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 18px;
font-size: 1.125rem;
line-height: 1.11111;
}
@media print {
.g-header__link--service-name {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-header__link--service-name {
font-size: 24px;
font-size: 1.5rem;
line-height: 1.25;
}
}
@media print {
.g-header__link--service-name {
font-size: 18pt;
line-height: 1.15;
}
}
.g-header__logo,
.g-header__content {
box-sizing: border-box;
}
.g-header__logo {
margin-bottom: 10px;
padding-right: 50px;
}
@media (min-width: 40.0625em) {
.g-header__logo {
margin-bottom: 10px;
}
}
@media (min-width: 48.0625em) {
.g-header__logo {
width: 33.33%;
padding-right: 15px;
float: left;
vertical-align: top;
}
}
@media (min-width: 48.0625em) {
.g-header__content {
width: 66.66%;
padding-left: 15px;
float: left;
}
}
.g-header__menu-button {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
display: none;
position: absolute;
top: 20px;
right: 0;
margin: 0;
padding: 0;
border: 0;
color: #ffffff;
background: none;
}
@media print {
.g-header__menu-button {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-header__menu-button {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-header__menu-button {
font-size: 14pt;
line-height: 1.2;
}
}
.g-header__menu-button:hover,
.g-header__menu-button.\:hover {
text-decoration: underline;
}
.g-header__menu-button::after {
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
-webkit-clip-path: polygon(0% 0%, 50% 100%, 100% 0%);
clip-path: polygon(0% 0%, 50% 100%, 100% 0%);
border-width: 8.66px 5px 0 5px;
border-top-color: inherit;
content: '';
margin-left: 5px;
}
.g-header__menu-button:focus,
.g-header__menu-button.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
@media (min-width: 40.0625em) {
.g-header__menu-button {
top: 15px;
}
}
.g-header__menu-button--open::after {
display: inline-block;
width: 0;
height: 0;
border-style: solid;
border-color: transparent;
-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
border-width: 0 5px 8.66px 5px;
border-bottom-color: inherit;
}
.g-header__navigation {
margin-bottom: 10px;
display: block;
margin: 0;
padding: 0;
list-style: none;
}
@media (min-width: 40.0625em) {
.g-header__navigation {
margin-bottom: 10px;
}
}
.js-enabled .g-header__menu-button {
display: block;
}
@media (min-width: 48.0625em) {
.js-enabled .g-header__menu-button {
display: none;
}
}
.js-enabled .g-header__navigation {
display: none;
}
@media (min-width: 48.0625em) {
.js-enabled .g-header__navigation {
display: block;
}
}
.js-enabled .g-header__navigation--open {
display: block;
}
@media (min-width: 48.0625em) {
.g-header__navigation--end {
margin: 0;
padding: 5px 0;
text-align: right;
}
}
.g-header__navigation--no-service-name {
padding-top: 40px;
}
.g-header__navigation-item {
padding: 10px 0;
border-bottom: 1px solid #2e3133;
}
@media (min-width: 48.0625em) {
.g-header__navigation-item {
display: inline-block;
margin-right: 15px;
padding: 5px 0;
border: 0;
}
}
.g-header__navigation-item a {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
white-space: nowrap;
}
@media print {
.g-header__navigation-item a {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-header__navigation-item a {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-header__navigation-item a {
font-size: 14pt;
line-height: 1.2;
}
}
.g-header__navigation-item--active a:link,
.g-header__navigation-item--active a:hover,
.g-header__navigation-item--active a:visited,
.g-header__navigation-item--active a.\:link,
.g-header__navigation-item--active a.\:hover,
.g-header__navigation-item--active a.\:visited {
color: #1d8feb;
}
.g-header__navigation-item--active a:focus,
.g-header__navigation-item--active a.\:focus {
color: #0b0c0c;
}
.g-header__navigation-item:last-child,
.g-header__navigation-item.\:last-child {
margin-right: 0;
}
@media print {
.g-header {
border-bottom-width: 0;
color: #0b0c0c;
background: transparent;
}
.g-header__logotype-crown-fallback-image {
display: none;
}
.g-header__link:link,
.g-header__link:visited,
.g-header__link.\:link,
.g-header__link.\:visited {
color: #0b0c0c;
}
.g-header__link:after {
display: none;
}
}
.g-header__logotype-crown,
.g-header__logotype-crown-fallback-image {
position: relative;
top: -4px;
}
.g-header {
padding-top: 3px;
}
.g-inset-text {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
padding: 15px;
margin-top: 20px;
margin-bottom: 20px;
clear: both;
border-left: 8px solid #23cba5;
background: #f4f4f4;
}
@media print {
.g-inset-text {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-inset-text {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-inset-text {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-inset-text {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-inset-text {
margin-top: 30px;
}
}
@media (min-width: 40.0625em) {
.g-inset-text {
margin-bottom: 30px;
}
}
.g-inset-text > :first-child,
.g-inset-text > .\:first-child {
margin-top: 0;
}
.g-inset-text > :only-child,
.g-inset-text > :last-child,
.g-inset-text > .\:only-child,
.g-inset-text > .\:last-child {
margin-bottom: 0;
}
.g-panel {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
margin-bottom: 15px;
padding: 35px;
border: 5px solid transparent;
text-align: center;
}
@media print {
.g-panel {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-panel {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-panel {
font-size: 14pt;
line-height: 1.15;
}
}
@media (max-width: 40.0525em) {
.g-panel {
padding: 25px;
}
}
.g-panel--confirmation {
color: #ffffff;
background: #28a197;
}
.g-panel__title {
margin-top: 0;
margin-bottom: 30px;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 32px;
font-size: 2rem;
line-height: 1.09375;
}
@media print {
.g-panel__title {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-panel__title {
font-size: 48px;
font-size: 3rem;
line-height: 1.04167;
}
}
@media print {
.g-panel__title {
font-size: 32pt;
line-height: 1.15;
}
}
.g-panel__title:last-child,
.g-panel__title.\:last-child {
margin-bottom: 0;
}
.g-panel__body {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 24px;
font-size: 1.5rem;
line-height: 1.04167;
}
@media print {
.g-panel__body {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-panel__body {
font-size: 36px;
font-size: 2.25rem;
line-height: 1.11111;
}
}
@media print {
.g-panel__body {
font-size: 24pt;
line-height: 1.05;
}
}
.g-tag {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.25;
display: inline-block;
padding: 4px 8px;
padding-bottom: 1px;
outline: 2px solid transparent;
outline-offset: -2px;
color: #ffffff;
background-color: #005ea5;
letter-spacing: 1px;
text-decoration: none;
text-transform: uppercase;
}
@media print {
.g-tag {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-tag {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-tag {
font-size: 14pt;
line-height: 1.25;
}
}
.g-tag--inactive {
background-color: #6f777b;
}
.g-phase-banner {
padding-top: 10px;
padding-bottom: 10px;
border-bottom: 1px solid #bfc1c3;
}
.g-phase-banner__content {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
color: #0b0c0c;
display: table;
margin: 0;
}
@media print {
.g-phase-banner__content {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-phase-banner__content {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-phase-banner__content {
font-size: 14pt;
line-height: 1.2;
}
}
@media print {
.g-phase-banner__content {
color: #000000;
}
}
.g-phase-banner__content__tag {
margin-right: 10px;
}
.g-phase-banner__text {
display: table-cell;
vertical-align: baseline;
}
.g-tabs {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
margin-top: 5px;
margin-bottom: 20px;
}
@media print {
.g-tabs {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-tabs {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-tabs {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-tabs {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-tabs {
margin-top: 5px;
}
}
@media (min-width: 40.0625em) {
.g-tabs {
margin-bottom: 30px;
}
}
.g-tabs__title {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
margin-bottom: 5px;
}
@media print {
.g-tabs__title {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-tabs__title {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-tabs__title {
font-size: 14pt;
line-height: 1.15;
}
}
.g-tabs__list {
margin: 0;
padding: 0;
list-style: none;
}
@media (max-width: 40.0525em) {
.g-tabs__list {
margin-bottom: 20px;
}
}
@media (max-width: 40.0525em) and (min-width: 40.0625em) {
.g-tabs__list {
margin-bottom: 30px;
}
}
.g-tabs__list-item {
margin-left: 25px;
}
.g-tabs__list-item::before {
content: '\\2014 ';
margin-left: -25px;
padding-right: 5px;
}
.g-tabs__tab {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: inline-block;
padding-top: 10px;
padding-bottom: 10px;
}
@media print {
.g-tabs__tab {
font-family: sans-serif;
}
}
.g-tabs__tab:focus,
.g-tabs__tab.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-tabs__tab:link,
.g-tabs__tab.\:link {
color: #005ea5;
}
.g-tabs__tab:visited,
.g-tabs__tab.\:visited {
color: #4c2c92;
}
.g-tabs__tab:hover,
.g-tabs__tab.\:hover {
color: #2b8cc4;
}
.g-tabs__tab:active,
.g-tabs__tab.\:active {
color: #2b8cc4;
}
.g-tabs__tab:focus,
.g-tabs__tab.\:focus {
color: #0b0c0c;
}
@media print {
.g-tabs__tab {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-tabs__tab {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-tabs__tab {
font-size: 14pt;
line-height: 1.15;
}
}
.g-tabs__tab[aria-current='true'] {
color: #0b0c0c;
text-decoration: none;
}
.g-tabs__panel {
margin-bottom: 30px;
}
@media (min-width: 40.0625em) {
.g-tabs__panel {
margin-bottom: 50px;
}
}
@media (min-width: 40.0625em) {
.js-enabled .g-tabs__list {
border-bottom: 1px solid #bfc1c3;
}
.js-enabled .g-tabs__list:after {
content: '';
display: block;
clear: both;
}
.js-enabled .g-tabs__list-item {
margin-left: 0;
}
.js-enabled .g-tabs__list-item::before {
content: none;
}
.js-enabled .g-tabs__title {
display: none;
}
.js-enabled .g-tabs__tab {
margin-right: 5px;
padding-right: 20px;
padding-left: 20px;
float: left;
color: #0b0c0c;
background-color: #f8f8f8;
text-align: center;
text-decoration: none;
}
.js-enabled .g-tabs__tab--selected {
margin-top: -5px;
margin-bottom: -1px;
padding-top: 14px;
padding-right: 19px;
padding-bottom: 16px;
padding-left: 19px;
border: 1px solid #bfc1c3;
border-bottom: 0;
color: #0b0c0c;
background-color: #ffffff;
}
.js-enabled .g-tabs__tab--selected:focus,
.js-enabled .g-tabs__tab--selected.\:focus {
background-color: transparent;
}
.js-enabled .g-tabs__panel {
margin-bottom: 0;
padding-top: 30px;
padding-right: 20px;
padding-bottom: 30px;
padding-left: 20px;
border: 1px solid #bfc1c3;
border-top: 0;
}
}
@media (min-width: 40.0625em) and (min-width: 40.0625em) {
.js-enabled .g-tabs__panel {
margin-bottom: 0;
}
}
@media (min-width: 40.0625em) {
.js-enabled .g-tabs__panel--hidden {
display: none;
}
.js-enabled .g-tabs__panel > :last-child,
.js-enabled .g-tabs__panel > .\:last-child {
margin-bottom: 0;
}
}
.g-radios__item {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 40px;
margin-bottom: 10px;
padding-left: 40px;
clear: left;
}
@media print {
.g-radios__item {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-radios__item {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-radios__item {
font-size: 14pt;
line-height: 1.15;
}
}
.g-radios__item:last-child,
.g-radios__item:last-of-type,
.g-radios__item.\:last-child,
.g-radios__item.\:last-of-type {
margin-bottom: 0;
}
.g-radios__input {
cursor: pointer;
position: absolute;
z-index: 1;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
margin: 0;
opacity: 0;
}
.g-radios__label {
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
-ms-touch-action: manipulation;
touch-action: manipulation;
}
.g-radios__label::before {
content: '';
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 40px;
border: 2px solid currentColor;
border-radius: 50%;
background: transparent;
}
.g-radios__label::after {
content: '';
position: absolute;
top: 10px;
left: 10px;
width: 0;
height: 0;
border: 10px solid currentColor;
border-radius: 50%;
opacity: 0;
background: currentColor;
}
.g-radios__hint {
display: block;
padding-right: 15px;
padding-left: 15px;
}
.g-radios__input:focus + .g-radios__label::before,
.g-radios__input.\:focus + .g-radios__label::before {
outline: 3px solid transparent;
outline-offset: 3px;
box-shadow: 0 0 0 4px #ffbf47;
}
.g-radios__input:checked + .g-radios__label::after,
.g-radios__input.\:checked + .g-radios__label::after {
opacity: 1;
}
.g-radios__input:disabled,
.g-radios__input:disabled + .g-radios__label,
.g-radios__input.\:disabled,
.g-radios__input.\:disabled + .g-radios__label {
cursor: default;
}
.g-radios__input:disabled + .g-radios__label,
.g-radios__input.\:disabled + .g-radios__label {
opacity: 0.5;
}
@media (min-width: 40.0625em) {
.g-radios--inline:after {
content: '';
display: block;
clear: both;
}
.g-radios--inline .g-radios__item {
margin-right: 20px;
float: left;
clear: none;
}
}
.g-radios--inline.g-radios--conditional .g-radios__item {
margin-right: 0;
float: none;
}
.g-form-divider {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
width: 40px;
margin-bottom: 10px;
text-align: center;
}
@media print {
.g-form-divider {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-form-divider {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-form-divider {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-form-divider {
color: #000000;
}
}
.g-radios__conditional {
margin-bottom: 15px;
margin-left: 18px;
padding-left: 33px;
border-left: 4px solid #bfc1c3;
}
@media (min-width: 40.0625em) {
.g-radios__conditional {
margin-bottom: 20px;
}
}
.js-enabled .g-radios__conditional--hidden {
display: none;
}
.g-radios__conditional > :last-child,
.g-radios__conditional > .\:last-child {
margin-bottom: 0;
}
.g-radios--small .g-radios__item {
min-height: 0;
margin-bottom: 0;
padding-left: 34px;
float: left;
}
.g-radios--small .g-radios__item:after {
content: '';
display: block;
clear: both;
}
.g-radios--small .g-radios__input {
left: -10px;
}
.g-radios--small .g-radios__label {
margin-top: -2px;
padding: 13px 15px 13px 1px;
float: left;
}
@media (min-width: 40.0625em) {
.g-radios--small .g-radios__label {
padding: 11px 15px 10px 1px;
}
}
.g-radios--small .g-radios__label::before {
top: 8px;
width: 24px;
height: 24px;
}
.g-radios--small .g-radios__label::after {
top: 14px;
left: 6px;
border-width: 6px;
}
.g-radios--small .g-radios__hint {
padding: 0;
clear: both;
pointer-events: none;
}
.g-radios--small .g-radios__conditional {
margin-left: 10px;
padding-left: 20px;
clear: both;
}
.g-radios--small .g-form-divider {
width: 24px;
margin-bottom: 5px;
}
.g-radios--small
.g-radios__item:hover
.g-radios__input:not(:disabled)
+ .g-radios__label::before,
.g-radios--small
.g-radios__item.\:hover
.g-radios__input:not(:disabled)
+ .g-radios__label::before {
box-shadow: 0 0 0 10px #dee0e2;
}
.g-radios--small
.g-radios__item:hover
.g-radios__input:focus
+ .g-radios__label::before,
.g-radios--small
.g-radios__item.\:hover
.g-radios__input.\:focus
+ .g-radios__label::before {
box-shadow: 0 0 0 4px #ffbf47, 0 0 0 10px #dee0e2;
}
@media (hover: none), (pointer: coarse) {
.g-radios--small
.g-radios__item:hover
.g-radios__input:not(:disabled)
+ .g-radios__label::before,
.g-radios--small
.g-radios__item.\:hover
.g-radios__input:not(:disabled)
+ .g-radios__label::before {
box-shadow: initial;
}
.g-radios--small
.g-radios__item:hover
.g-radios__input:focus
+ .g-radios__label::before,
.g-radios--small
.g-radios__item.\:hover
.g-radios__input.\:focus
+ .g-radios__label::before {
box-shadow: 0 0 0 4px #ffbf47;
}
}
.g-select {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
max-width: 100%;
height: auto;
padding: 5px;
border: 1px solid #000000;
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
padding: 0.4rem 2.5rem 0.5rem 0.6rem;
background-repeat: no-repeat;
border-radius: 0;
background-position: right 0.7em top 50%;
background-size: 1rem auto;
background-image: url('data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%0A%20%20%20%20%20%20%20%20%20%20%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2214%22%20height%3D%228.5%22%20viewBox%3D%220%200%2016%2010.5%22%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3Cpath%20d%3D%22M1%201%20L8%208.5%20L15%201%22%20stroke-width%3D%223%22%20stroke%3D%22currentColor%22%20fill%3D%22transparent%22%20%2F%3E%0A%20%20%20%20%20%20%20%20%20%20%3C%2Fsvg%3E');
}
@media print {
.g-select {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-select {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.25;
}
}
@media print {
.g-select {
font-size: 14pt;
line-height: 1.25;
}
}
.g-select:focus,
.g-select.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
.g-select option:active,
.g-select option:checked,
.g-select:focus::-ms-value,
.g-select option.\:active,
.g-select option.\:checked,
.g-select.\:focus::-ms-value {
color: #ffffff;
background-color: #005ea5;
}
.g-select--error {
border: 1px solid #b10e1e;
}
.g-skip-link {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: 0 !important;
overflow: hidden !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important;
white-space: nowrap !important;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-size: 14px;
font-size: 0.875rem;
line-height: 1.14286;
display: block;
padding: 10px 15px;
}
.g-skip-link:active,
.g-skip-link:focus,
.g-skip-link.\:active,
.g-skip-link.\:focus {
position: static !important;
width: auto !important;
height: auto !important;
margin: inherit !important;
overflow: visible !important;
clip: auto !important;
-webkit-clip-path: none !important;
clip-path: none !important;
white-space: inherit !important;
}
@media print {
.g-skip-link {
font-family: sans-serif;
}
}
.g-skip-link:focus,
.g-skip-link.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
background-color: #ffbf47;
}
.g-skip-link:link,
.g-skip-link:visited,
.g-skip-link:hover,
.g-skip-link:active,
.g-skip-link:focus,
.g-skip-link.\:link,
.g-skip-link.\:visited,
.g-skip-link.\:hover,
.g-skip-link.\:active,
.g-skip-link.\:focus {
color: #0b0c0c;
}
@media print {
.g-skip-link:link,
.g-skip-link:visited,
.g-skip-link:hover,
.g-skip-link:active,
.g-skip-link:focus,
.g-skip-link.\:link,
.g-skip-link.\:visited,
.g-skip-link.\:hover,
.g-skip-link.\:active,
.g-skip-link.\:focus {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-skip-link {
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
}
}
@media print {
.g-skip-link {
font-size: 14pt;
line-height: 1.2;
}
}
@supports (padding: max(calc(0px))) {
.g-skip-link {
padding-right: max(15px, calc(15px + env(safe-area-inset-right)));
padding-left: max(15px, calc(15px + env(safe-area-inset-left)));
}
}
.g-table {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
width: 100%;
margin-bottom: 20px;
border-spacing: 0;
border-collapse: collapse;
}
@media print {
.g-table {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-table {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-table {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-table {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-table {
margin-bottom: 30px;
}
}
.g-table__header {
font-weight: 700;
}
.g-table__header,
.g-table__cell {
padding: 10px 20px 10px 0;
border-bottom: 1px solid #bfc1c3;
text-align: left;
}
.g-table__cell--numeric {
font-family: 'ntatabularnumbers', Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
}
@media print {
.g-table__cell--numeric {
font-family: sans-serif;
}
}
.g-table__header--numeric,
.g-table__cell--numeric {
text-align: right;
}
.g-table__header:last-child,
.g-table__cell:last-child,
.g-table__header.\:last-child,
.g-table__cell.\:last-child {
padding-right: 0;
}
.g-table__caption {
font-weight: 700;
display: table-caption;
text-align: left;
}
.g-textarea {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
display: block;
width: 100%;
min-height: 40px;
margin-bottom: 20px;
padding: 5px;
resize: vertical;
border: 2px solid #0b0c0c;
border-radius: 0;
-webkit-appearance: none;
}
@media print {
.g-textarea {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-textarea {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.25;
}
}
@media print {
.g-textarea {
font-size: 14pt;
line-height: 1.25;
}
}
.g-textarea:focus,
.g-textarea.\:focus {
outline: 3px solid #ffbf47;
outline-offset: 0;
}
@media (min-width: 40.0625em) {
.g-textarea {
margin-bottom: 30px;
}
}
.g-textarea--error {
border: 4px solid #b10e1e;
}
.g-warning-text {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
position: relative;
margin-bottom: 20px;
padding: 10px 0;
}
@media print {
.g-warning-text {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-warning-text {
font-size: 19px;
font-size: 1.1875rem;
line-height: 1.31579;
}
}
@media print {
.g-warning-text {
font-size: 14pt;
line-height: 1.15;
}
}
@media print {
.g-warning-text {
color: #000000;
}
}
@media (min-width: 40.0625em) {
.g-warning-text {
margin-bottom: 30px;
}
}
.g-warning-text__assistive {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important;
border: 0 !important;
white-space: nowrap !important;
}
.g-warning-text__icon {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 700;
display: inline-block;
position: absolute;
top: 50%;
left: 0;
min-width: 32px;
min-height: 29px;
margin-top: -20px;
padding-top: 3px;
border: 3px solid #0b0c0c;
border-radius: 50%;
color: #ffffff;
background: #0b0c0c;
font-size: 1.6em;
line-height: 29px;
text-align: center;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
@media print {
.g-warning-text__icon {
font-family: sans-serif;
}
}
.g-warning-text__text {
display: block;
padding-left: 50px;
}
.g-clearfix:after {
content: '';
display: block;
clear: both;
}
.g-visually-hidden {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: 0 !important;
padding: 0 !important;
overflow: hidden !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important;
border: 0 !important;
white-space: nowrap !important;
}
.g-visually-hidden-focusable {
position: absolute !important;
width: 1px !important;
height: 1px !important;
margin: 0 !important;
overflow: hidden !important;
clip: rect(0 0 0 0) !important;
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important;
white-space: nowrap !important;
}
.g-visually-hidden-focusable:active,
.g-visually-hidden-focusable:focus,
.g-visually-hidden-focusable.\:active,
.g-visually-hidden-focusable.\:focus {
position: static !important;
width: auto !important;
height: auto !important;
margin: inherit !important;
overflow: visible !important;
clip: auto !important;
-webkit-clip-path: none !important;
clip-path: none !important;
white-space: inherit !important;
}
.g-\!-display-inline {
display: inline !important;
}
.g-\!-display-inline-block {
display: inline-block !important;
}
.g-\!-display-block {
display: block !important;
}
.g-\!-margin-0 {
margin: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-0 {
margin: 0 !important;
}
}
.g-\!-margin-top-0 {
margin-top: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-0 {
margin-top: 0 !important;
}
}
.g-\!-margin-right-0 {
margin-right: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-0 {
margin-right: 0 !important;
}
}
.g-\!-margin-bottom-0 {
margin-bottom: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-0 {
margin-bottom: 0 !important;
}
}
.g-\!-margin-left-0 {
margin-left: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-0 {
margin-left: 0 !important;
}
}
.g-\!-margin-1 {
margin: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-1 {
margin: 5px !important;
}
}
.g-\!-margin-top-1 {
margin-top: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-1 {
margin-top: 5px !important;
}
}
.g-\!-margin-right-1 {
margin-right: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-1 {
margin-right: 5px !important;
}
}
.g-\!-margin-bottom-1 {
margin-bottom: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-1 {
margin-bottom: 5px !important;
}
}
.g-\!-margin-left-1 {
margin-left: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-1 {
margin-left: 5px !important;
}
}
.g-\!-margin-2 {
margin: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-2 {
margin: 10px !important;
}
}
.g-\!-margin-top-2 {
margin-top: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-2 {
margin-top: 10px !important;
}
}
.g-\!-margin-right-2 {
margin-right: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-2 {
margin-right: 10px !important;
}
}
.g-\!-margin-bottom-2 {
margin-bottom: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-2 {
margin-bottom: 10px !important;
}
}
.g-\!-margin-left-2 {
margin-left: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-2 {
margin-left: 10px !important;
}
}
.g-\!-margin-3 {
margin: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-3 {
margin: 15px !important;
}
}
.g-\!-margin-top-3 {
margin-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-3 {
margin-top: 15px !important;
}
}
.g-\!-margin-right-3 {
margin-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-3 {
margin-right: 15px !important;
}
}
.g-\!-margin-bottom-3 {
margin-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-3 {
margin-bottom: 15px !important;
}
}
.g-\!-margin-left-3 {
margin-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-3 {
margin-left: 15px !important;
}
}
.g-\!-margin-4 {
margin: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-4 {
margin: 20px !important;
}
}
.g-\!-margin-top-4 {
margin-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-4 {
margin-top: 20px !important;
}
}
.g-\!-margin-right-4 {
margin-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-4 {
margin-right: 20px !important;
}
}
.g-\!-margin-bottom-4 {
margin-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-4 {
margin-bottom: 20px !important;
}
}
.g-\!-margin-left-4 {
margin-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-4 {
margin-left: 20px !important;
}
}
.g-\!-margin-5 {
margin: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-5 {
margin: 25px !important;
}
}
.g-\!-margin-top-5 {
margin-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-5 {
margin-top: 25px !important;
}
}
.g-\!-margin-right-5 {
margin-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-5 {
margin-right: 25px !important;
}
}
.g-\!-margin-bottom-5 {
margin-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-5 {
margin-bottom: 25px !important;
}
}
.g-\!-margin-left-5 {
margin-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-5 {
margin-left: 25px !important;
}
}
.g-\!-margin-6 {
margin: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-6 {
margin: 30px !important;
}
}
.g-\!-margin-top-6 {
margin-top: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-6 {
margin-top: 30px !important;
}
}
.g-\!-margin-right-6 {
margin-right: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-6 {
margin-right: 30px !important;
}
}
.g-\!-margin-bottom-6 {
margin-bottom: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-6 {
margin-bottom: 30px !important;
}
}
.g-\!-margin-left-6 {
margin-left: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-6 {
margin-left: 30px !important;
}
}
.g-\!-margin-7 {
margin: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-7 {
margin: 40px !important;
}
}
.g-\!-margin-top-7 {
margin-top: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-7 {
margin-top: 40px !important;
}
}
.g-\!-margin-right-7 {
margin-right: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-7 {
margin-right: 40px !important;
}
}
.g-\!-margin-bottom-7 {
margin-bottom: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-7 {
margin-bottom: 40px !important;
}
}
.g-\!-margin-left-7 {
margin-left: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-7 {
margin-left: 40px !important;
}
}
.g-\!-margin-8 {
margin: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-8 {
margin: 50px !important;
}
}
.g-\!-margin-top-8 {
margin-top: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-8 {
margin-top: 50px !important;
}
}
.g-\!-margin-right-8 {
margin-right: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-8 {
margin-right: 50px !important;
}
}
.g-\!-margin-bottom-8 {
margin-bottom: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-8 {
margin-bottom: 50px !important;
}
}
.g-\!-margin-left-8 {
margin-left: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-8 {
margin-left: 50px !important;
}
}
.g-\!-margin-9 {
margin: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-9 {
margin: 60px !important;
}
}
.g-\!-margin-top-9 {
margin-top: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-top-9 {
margin-top: 60px !important;
}
}
.g-\!-margin-right-9 {
margin-right: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-right-9 {
margin-right: 60px !important;
}
}
.g-\!-margin-bottom-9 {
margin-bottom: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-bottom-9 {
margin-bottom: 60px !important;
}
}
.g-\!-margin-left-9 {
margin-left: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-margin-left-9 {
margin-left: 60px !important;
}
}
.g-\!-padding-0 {
padding: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-0 {
padding: 0 !important;
}
}
.g-\!-padding-top-0 {
padding-top: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-0 {
padding-top: 0 !important;
}
}
.g-\!-padding-right-0 {
padding-right: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-0 {
padding-right: 0 !important;
}
}
.g-\!-padding-bottom-0 {
padding-bottom: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-0 {
padding-bottom: 0 !important;
}
}
.g-\!-padding-left-0 {
padding-left: 0 !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-0 {
padding-left: 0 !important;
}
}
.g-\!-padding-1 {
padding: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-1 {
padding: 5px !important;
}
}
.g-\!-padding-top-1 {
padding-top: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-1 {
padding-top: 5px !important;
}
}
.g-\!-padding-right-1 {
padding-right: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-1 {
padding-right: 5px !important;
}
}
.g-\!-padding-bottom-1 {
padding-bottom: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-1 {
padding-bottom: 5px !important;
}
}
.g-\!-padding-left-1 {
padding-left: 5px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-1 {
padding-left: 5px !important;
}
}
.g-\!-padding-2 {
padding: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-2 {
padding: 10px !important;
}
}
.g-\!-padding-top-2 {
padding-top: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-2 {
padding-top: 10px !important;
}
}
.g-\!-padding-right-2 {
padding-right: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-2 {
padding-right: 10px !important;
}
}
.g-\!-padding-bottom-2 {
padding-bottom: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-2 {
padding-bottom: 10px !important;
}
}
.g-\!-padding-left-2 {
padding-left: 10px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-2 {
padding-left: 10px !important;
}
}
.g-\!-padding-3 {
padding: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-3 {
padding: 15px !important;
}
}
.g-\!-padding-top-3 {
padding-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-3 {
padding-top: 15px !important;
}
}
.g-\!-padding-right-3 {
padding-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-3 {
padding-right: 15px !important;
}
}
.g-\!-padding-bottom-3 {
padding-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-3 {
padding-bottom: 15px !important;
}
}
.g-\!-padding-left-3 {
padding-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-3 {
padding-left: 15px !important;
}
}
.g-\!-padding-4 {
padding: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-4 {
padding: 20px !important;
}
}
.g-\!-padding-top-4 {
padding-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-4 {
padding-top: 20px !important;
}
}
.g-\!-padding-right-4 {
padding-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-4 {
padding-right: 20px !important;
}
}
.g-\!-padding-bottom-4 {
padding-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-4 {
padding-bottom: 20px !important;
}
}
.g-\!-padding-left-4 {
padding-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-4 {
padding-left: 20px !important;
}
}
.g-\!-padding-5 {
padding: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-5 {
padding: 25px !important;
}
}
.g-\!-padding-top-5 {
padding-top: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-5 {
padding-top: 25px !important;
}
}
.g-\!-padding-right-5 {
padding-right: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-5 {
padding-right: 25px !important;
}
}
.g-\!-padding-bottom-5 {
padding-bottom: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-5 {
padding-bottom: 25px !important;
}
}
.g-\!-padding-left-5 {
padding-left: 15px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-5 {
padding-left: 25px !important;
}
}
.g-\!-padding-6 {
padding: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-6 {
padding: 30px !important;
}
}
.g-\!-padding-top-6 {
padding-top: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-6 {
padding-top: 30px !important;
}
}
.g-\!-padding-right-6 {
padding-right: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-6 {
padding-right: 30px !important;
}
}
.g-\!-padding-bottom-6 {
padding-bottom: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-6 {
padding-bottom: 30px !important;
}
}
.g-\!-padding-left-6 {
padding-left: 20px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-6 {
padding-left: 30px !important;
}
}
.g-\!-padding-7 {
padding: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-7 {
padding: 40px !important;
}
}
.g-\!-padding-top-7 {
padding-top: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-7 {
padding-top: 40px !important;
}
}
.g-\!-padding-right-7 {
padding-right: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-7 {
padding-right: 40px !important;
}
}
.g-\!-padding-bottom-7 {
padding-bottom: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-7 {
padding-bottom: 40px !important;
}
}
.g-\!-padding-left-7 {
padding-left: 25px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-7 {
padding-left: 40px !important;
}
}
.g-\!-padding-8 {
padding: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-8 {
padding: 50px !important;
}
}
.g-\!-padding-top-8 {
padding-top: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-8 {
padding-top: 50px !important;
}
}
.g-\!-padding-right-8 {
padding-right: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-8 {
padding-right: 50px !important;
}
}
.g-\!-padding-bottom-8 {
padding-bottom: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-8 {
padding-bottom: 50px !important;
}
}
.g-\!-padding-left-8 {
padding-left: 30px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-8 {
padding-left: 50px !important;
}
}
.g-\!-padding-9 {
padding: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-9 {
padding: 60px !important;
}
}
.g-\!-padding-top-9 {
padding-top: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-top-9 {
padding-top: 60px !important;
}
}
.g-\!-padding-right-9 {
padding-right: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-right-9 {
padding-right: 60px !important;
}
}
.g-\!-padding-bottom-9 {
padding-bottom: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-bottom-9 {
padding-bottom: 60px !important;
}
}
.g-\!-padding-left-9 {
padding-left: 40px !important;
}
@media (min-width: 40.0625em) {
.g-\!-padding-left-9 {
padding-left: 60px !important;
}
}
.g-\!-font-size-80 {
font-size: 53px !important;
font-size: 3.3125rem !important;
line-height: 1.03774 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-80 {
font-size: 80px !important;
font-size: 5rem !important;
line-height: 1 !important;
}
}
@media print {
.g-\!-font-size-80 {
font-size: 53pt !important;
line-height: 1.1 !important;
}
}
.g-\!-font-size-48 {
font-size: 32px !important;
font-size: 2rem !important;
line-height: 1.09375 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-48 {
font-size: 48px !important;
font-size: 3rem !important;
line-height: 1.04167 !important;
}
}
@media print {
.g-\!-font-size-48 {
font-size: 32pt !important;
line-height: 1.15 !important;
}
}
.g-\!-font-size-36 {
font-size: 24px !important;
font-size: 1.5rem !important;
line-height: 1.04167 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-36 {
font-size: 36px !important;
font-size: 2.25rem !important;
line-height: 1.11111 !important;
}
}
@media print {
.g-\!-font-size-36 {
font-size: 24pt !important;
line-height: 1.05 !important;
}
}
.g-\!-font-size-27 {
font-size: 18px !important;
font-size: 1.125rem !important;
line-height: 1.11111 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-27 {
font-size: 27px !important;
font-size: 1.6875rem !important;
line-height: 1.11111 !important;
}
}
@media print {
.g-\!-font-size-27 {
font-size: 18pt !important;
line-height: 1.15 !important;
}
}
.g-\!-font-size-24 {
font-size: 18px !important;
font-size: 1.125rem !important;
line-height: 1.11111 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-24 {
font-size: 24px !important;
font-size: 1.5rem !important;
line-height: 1.25 !important;
}
}
@media print {
.g-\!-font-size-24 {
font-size: 18pt !important;
line-height: 1.15 !important;
}
}
.g-\!-font-size-19 {
font-size: 16px !important;
font-size: 1rem !important;
line-height: 1.25 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-19 {
font-size: 19px !important;
font-size: 1.1875rem !important;
line-height: 1.31579 !important;
}
}
@media print {
.g-\!-font-size-19 {
font-size: 14pt !important;
line-height: 1.15 !important;
}
}
.g-\!-font-size-16 {
font-size: 14px !important;
font-size: 0.875rem !important;
line-height: 1.14286 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-16 {
font-size: 16px !important;
font-size: 1rem !important;
line-height: 1.25 !important;
}
}
@media print {
.g-\!-font-size-16 {
font-size: 14pt !important;
line-height: 1.2 !important;
}
}
.g-\!-font-size-14 {
font-size: 12px !important;
font-size: 0.75rem !important;
line-height: 1.25 !important;
}
@media (min-width: 40.0625em) {
.g-\!-font-size-14 {
font-size: 14px !important;
font-size: 0.875rem !important;
line-height: 1.42857 !important;
}
}
@media print {
.g-\!-font-size-14 {
font-size: 12pt !important;
line-height: 1.2 !important;
}
}
.g-\!-font-weight-regular {
font-weight: 400 !important;
}
.g-\!-font-weight-bold {
font-weight: 700 !important;
}
.g-\!-width-full {
width: 100% !important;
}
.g-\!-width-three-quarters {
width: 100% !important;
}
@media (min-width: 40.0625em) {
.g-\!-width-three-quarters {
width: 75% !important;
}
}
.g-\!-width-two-thirds {
width: 100% !important;
}
@media (min-width: 40.0625em) {
.g-\!-width-two-thirds {
width: 66.66% !important;
}
}
.g-\!-width-one-half {
width: 100% !important;
}
@media (min-width: 40.0625em) {
.g-\!-width-one-half {
width: 50% !important;
}
}
.g-\!-width-one-third {
width: 100% !important;
}
@media (min-width: 40.0625em) {
.g-\!-width-one-third {
width: 33.33% !important;
}
}
.g-\!-width-one-quarter {
width: 100% !important;
}
@media (min-width: 40.0625em) {
.g-\!-width-one-quarter {
width: 25% !important;
}
}
.app-no-canvas-background {
background-color: #ffffff;
}
.app-iframe-in-component-preview {
margin: 15px 0;
}
.app-iframe-in-component-preview:before {
display: none;
}
.app-\!-di {
display: inline;
}
.app-component-preview {
position: relative;
margin-top: -15px;
margin-bottom: 15px;
width: 100%;
}
.app-component-preview__iframe {
z-index: 20;
display: block;
position: relative;
border: none;
width: 100%;
}
.app-iframe-in-component-preview .app-whitespace-highlight {
content: ' ';
display: table;
clear: both;
width: 100%;
box-shadow: 0 0 0 5px #e4f2ff;
}
.app-iframe-in-component-preview .app-whitespace-highlight:after {
content: '';
display: block;
clear: both;
}
.app-banner {
padding-top: 30px;
padding-bottom: 30px;
overflow: hidden;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 24px;
font-size: 1.5rem;
line-height: 1.5;
font-family: sans-serif;
}
@media print {
.app-banner {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.app-banner {
font-size: 36px;
font-size: 2.25rem;
line-height: 1.5;
}
}
@media print {
.app-banner {
font-size: 24pt;
line-height: 1.5;
}
}
.app-banner .app-banner__button {
margin-bottom: 0;
}
.app-banner .g-body {
color: inherit;
font-size: inherit;
}
.app-banner .g-link {
color: #ffffff;
}
.app-banner .g-link:focus,
.app-banner .g-link.\:focus {
color: #0b0c0c;
}
.app-banner--warning {
color: #ffffff;
background: #b10e1e;
}
.app-banner--warning .app-banner__button,
.app-banner--warning .app-banner__button:active,
.app-banner--warning .app-banner__button:hover,
.app-banner--warning .app-banner__button:focus,
.app-banner--warning .app-banner__button.\:active,
.app-banner--warning .app-banner__button.\:hover,
.app-banner--warning .app-banner__button.\:focus {
margin-bottom: 0;
color: #0b0c0c;
background: #ffffff;
box-shadow: 0 2px 0 #0b0c0c;
}
.g-heading-xs {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 1.125rem;
line-height: 1.25;
display: block;
margin-top: 2.5rem;
margin-bottom: 0.5rem;
}
@media print {
.g-heading-xs {
color: #000000;
}
}
@media print {
.g-heading-xs {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-xs {
font-size: 0.9375rem;
line-height: 1.31579;
}
}
@media print {
.g-heading-xs {
font-size: 13pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-heading-xs {
margin-bottom: 0.5rem;
}
}
.g-body-m + .g-heading-xs,
.g-body + .g-heading-xs,
.g-body-s + .g-heading-xs,
.g-list + .g-heading-xs {
padding-top: 5px;
}
@media (min-width: 40.0625em) {
.g-body-m + .g-heading-xs,
.g-body + .g-heading-xs,
.g-body-s + .g-heading-xs,
.g-list + .g-heading-xs {
padding-top: 10px;
}
}
.g-heading-xxs {
color: #2a2a2a;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: g-heading-font-weight;
font-size: 1rem;
line-height: 1.25;
display: block;
margin-top: 2.5rem;
margin-bottom: 15px;
}
@media print {
.g-heading-xxs {
color: #000000;
}
}
@media print {
.g-heading-xxs {
font-family: sans-serif;
}
}
@media (min-width: 40.0625em) {
.g-heading-xxs {
font-size: 0.875rem;
line-height: 1.31579;
}
}
@media print {
.g-heading-xxs {
font-size: 12pt;
line-height: 1.15;
}
}
@media (min-width: 40.0625em) {
.g-heading-xxs {
margin-bottom: 20px;
}
}
.g-body-m + .g-heading-xxs,
.g-body + .g-heading-xxs,
.g-body-s + .g-heading-xxs,
.g-list + .g-heading-xxs {
padding-top: 5px;
}
@media (min-width: 40.0625em) {
.g-body-m + .g-heading-xxs,
.g-body + .g-heading-xxs,
.g-body-s + .g-heading-xxs,
.g-list + .g-heading-xxs {
padding-top: 10px;
}
}
.g-heading-mb-8 {
margin-bottom: 8px;
}
.g-heading-mb-0 {
margin-bottom: 0px;
}
.g-select::-ms-expand {
display: none;
}
.g-hint > * {
margin-top: 0px;
}
.g-list li .g-list {
margin-top: 0.5rem;
}
`;
const dom = await getBrowser(
{
template: {
id: "test",
html,
css
}
},
{ type: "jsdom" }
);
const body = dom.bodyNodes;
const matchedCSS = await getCSSMatches(body, {
document: dom.bodyNodes[0].ownerDocument
});
const cssSubset = serializeCSSMatches(matchedCSS);
expect(cssSubset).toContain("g-date-input__item");
});
}); | the_stack |
module WinJSTests {
"use strict";
var strings = {
simpleResource: { value: "hello" },
simpleResourceLang: { value: "hello", lang: "en-us" },
color: { value: "red" },
colorLang: { value: "red", lang: "jp" },
nestedResource: { value: "<div id='one' data-win-res='{textContent:\"simpleResource\"}'></div>" },
nestedResourceLang: { value: "<div id='one' data-win-res='{textContent:\"simpleResourceLang\"}'></div>" },
nestedResourceTopLang: { value: "<div id='one' data-win-res='{textContent:\"simpleResource\"}'></div>", lang: "fr" },
nestedResourceConflictLang: { value: "<div id='one' data-win-res='{textContent:\"simpleResourceLang\"}'></div>", lang: "fr" }
};
function withCustomGet(f) {
var old = WinJS.Resources.getString;
try {
WinJS.Resources.getString = function (resourceId) {
return strings[resourceId] || { value: resourceId, empty: true };
};
f();
}
finally {
WinJS.Resources.getString = old;
}
}
function errorHandler(msg) {
try {
LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg);
} catch (ex) { }
}
export class DeclResources {
testSimple() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"simpleResource\"}'></div>");
WinJS.Resources.processAll(d);
var child = d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
});
}
testValidationMissingResource(complete) {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"invalidResource\"}'></div>");
var old = WinJS.validation;
WinJS.validation = true;
WinJS.Resources.processAll(d)
.then(
function success() {
LiveUnit.Assert.fail("processAll should throw");
},
function error(e) {
// @TODO, can't do this check b/c we are overriding custom lookup so we don't find the format string for the error message ;)
//
//LiveUnit.Assert.isTrue(e.indexOf("invalidResource") !== -1, "should have the name of the missing resource");
}
)
.then(null, errorHandler)
.then(function () {
WinJS.validation = old;
})
.then(complete);
});
}
testSimpleLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"simpleResourceLang\"}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("en-us", child.lang);
});
}
// UNDONE: blocked by WIN8:425876
testAttributeLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{attributes:{\"aria-label\":\"simpleResourceLang\"}}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.getAttribute("aria-label"));
LiveUnit.Assert.areEqual("en-us", child.lang);
});
}
testAttributeLang2() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{attributes:{arialabel:\"simpleResourceLang\"}}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.getAttribute("arialabel"));
LiveUnit.Assert.areEqual("en-us", child.lang);
});
}
testDotted() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"simpleResource\", style: { backgroundColor: \"color\" }}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("red", child.style.backgroundColor);
});
}
testDottedLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"simpleResource\", style: { backgroundColor: \"colorLang\" }}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("jp", child.lang);
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("red", child.style.backgroundColor);
});
}
testDottedConflictLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{textContent:\"simpleResourceLang\", style: { backgroundColor: \"colorLang\" }}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("jp", child.lang); // last lang wins, declaration order
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("red", child.style.backgroundColor);
});
}
testDottedConflictLangRev() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='one' data-win-res='{ style: { backgroundColor: \"colorLang\" }, textContent:\"simpleResourceLang\" }'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("en-us", child.lang); // last lang wins, declaration order
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("red", child.style.backgroundColor);
});
}
testNested() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='two' data-win-res='{innerHTML:\"nestedResource\"}'></div>");
WinJS.Resources.processAll(d);
var child = d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
});
}
testNestedLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='two' data-win-res='{innerHTML:\"nestedResourceLang\"}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("en-us", child.lang);
});
}
testNestedTopLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='two' data-win-res='{innerHTML:\"nestedResourceTopLang\"}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("", child.lang);
var top = <HTMLElement>d.querySelector("#two");
LiveUnit.Assert.areEqual("fr", top.lang);
});
}
testNestedConflictLang() {
withCustomGet(function () {
var d = document.createElement("div");
WinJS.Utilities.setInnerHTMLUnsafe(d, "<div id='two' data-win-res='{innerHTML:\"nestedResourceConflictLang\"}'></div>");
WinJS.Resources.processAll(d);
var child = <HTMLElement>d.querySelector("#one");
LiveUnit.Assert.areEqual("hello", child.textContent);
LiveUnit.Assert.areEqual("en-us", child.lang);
var top = <HTMLElement>d.querySelector("#two");
LiveUnit.Assert.areEqual("fr", top.lang);
});
}
testEvents() {
withCustomGet(function () {
var value = 0;
var scaleValue = 1;
var langValue = "EN-US";
WinJS.Resources.addEventListener("contextchanged", function (e) {
if (e.detail.qualifier === "Scale") {
scaleValue = e.detail.changed;
}
}, false);
WinJS.Resources.addEventListener("contextchanged", function (e) {
if (e.detail.qualifier === "Language") {
langValue = e.detail.changed;
}
}, false);
WinJS.Resources.addEventListener("changed", function () {
value++;
}, false);
WinJS.Resources.dispatchEvent('contextchanged', { qualifier: "Scale", changed: 3 });
LiveUnit.Assert.areEqual(scaleValue, 3);
WinJS.Resources.dispatchEvent('contextchanged', { qualifier: "Language", changed: "JA-JP" });
LiveUnit.Assert.areEqual(langValue, "JA-JP");
WinJS.Resources.dispatchEvent('changed', {});
LiveUnit.Assert.areEqual(value, 1);
});
}
}
}
LiveUnit.registerTestClass("WinJSTests.DeclResources"); | the_stack |
import { strDuration } from 'common-sk/modules/human';
import { render, svg } from 'lit-html';
import { $$ } from 'common-sk/modules/dom';
export interface Block {
start: Date;
end: Date;
color?: string;
label?: string;
}
export interface Lane {
label: string;
blocks: Block[];
}
export interface Data {
lanes: Lane[];
start?: Date;
end?: Date;
epochs?: Date[];
}
interface DisplayBlock {
x: number;
y: number;
width: number;
height: number;
title: string;
color: string;
}
interface Label {
text: string;
x: number;
y: number;
width: number;
}
interface Epoch {
x: number;
y: number;
width: number;
height: number;
color: string;
}
interface RulerTick {
x1: number;
y1: number;
x2: number;
y2: number;
}
interface RulerText {
x: number;
y: number;
rotationX: number;
rotationY: number;
text: string;
}
interface Border {
x1: number;
y1: number;
x2: number;
y2: number;
}
const blockHeightProportion = 0.8;
const chartMarginLeft = 5;
const chartMarginRight = 110;
const chartMarginY = 5;
const labelFontFamily = 'Arial';
const labelFontSize = 11;
const labelHeight = 20;
const labelMarginRight = 10;
const mouseoverHeight = 50;
const rulerHeight = 78;
const rulerLabelMarginRight = 5;
const rulerLabelRotation = -30;
const rulerTickLength = 15;
const snapThreshold = 15;
/**
* Draw a chart as a child of the given HTMLElement.
*/
export function draw(container: HTMLElement, data: Data) {
// Calculate the space needed to display the labels.
const boundingRect = container.getBoundingClientRect();
const totalWidth = boundingRect.width;
const totalHeight = boundingRect.height;
const blocksHeight = totalHeight - rulerHeight - mouseoverHeight - 2 * chartMarginY;
const rowHeight = blocksHeight / data.lanes.length;
const blockHeight = rowHeight * blockHeightProportion;
const blockMarginY = (rowHeight - blockHeight) / 2;
const labelMarginY = (rowHeight - labelHeight) / 2;
// This is a temporary throwaway canvas which is only used for measuring
// text.
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!;
ctx.font = `${labelFontSize}px ${labelFontFamily}`;
let maxLabelWidth = 0;
data.lanes.forEach((lane: Lane) => {
const width = ctx.measureText(lane.label).width;
if (width > maxLabelWidth) {
maxLabelWidth = width;
}
});
// Define the chart area.
const blocksStartX = chartMarginLeft + maxLabelWidth + labelMarginRight;
const blocksStartY = chartMarginY + mouseoverHeight;
const blocksWidth = totalWidth - blocksStartX - chartMarginRight;
// Find the time range which encompasses all blocks.
let tStart = data.start?.getTime() || Number.MAX_SAFE_INTEGER;
let tEnd = data.end?.getTime() || 0;
data.lanes.forEach((lane: Lane) => {
lane.blocks.forEach((block: Block) => {
const start = new Date(block.start).getTime();
if (start < tStart) {
tStart = start;
}
if (start > tEnd) {
tEnd = start;
}
const end = new Date(block.end).getTime();
if (end < tStart) {
tStart = end;
}
if (end > tEnd) {
tEnd = end;
}
});
});
if (tStart > tEnd) {
throw `Start timestamp (${tStart}) is after end (${tEnd})`;
}
const duration = tEnd - tStart;
const timeStart = tStart;
// Derive the coordinates for the blocks and their labels.
const blocks: DisplayBlock[] = [];
const labels: Label[] = [];
data.lanes.forEach((lane: Lane, laneIndex: number) => {
labels.push({
text: lane.label,
x: chartMarginLeft + maxLabelWidth,
y: blocksStartY + laneIndex * rowHeight + labelHeight / 2 + labelMarginY,
width: maxLabelWidth,
});
lane.blocks.forEach((block: Block) => {
const start = block.start.getTime();
const end = block.end.getTime();
let title = '';
if (block.label) {
title = `${block.label} `;
}
title += strDuration((end - start) / 1000);
blocks.push({
x: blocksStartX + (blocksWidth * (start - tStart)) / duration,
y: blocksStartY + laneIndex * rowHeight + blockMarginY,
width: Math.max((blocksWidth * (end - start)) / duration, 1.0),
height: blockHeight,
title: title,
color: block.color || '#000000',
});
});
});
// Create the ruler.
// We want approximately one tick every 50-100 px.
const numTargetTicks = blocksWidth / 75;
const approxTickSize = duration / numTargetTicks;
// Round the tick size to the nearest multiple of an appropriate unit.
// Timestamps are in milliseconds.
const units = [
1, // 1 ms
5, // 5 ms
10, // 10 ms
50, // 50 ms
100, // 100 ms
500, // 500 ms
1000, // 1 s
5000, // 5 s
10000, // 10 s
30000, // 30 s
60000, // 1 m
300000, // 5 m
600000, // 10 m
1800000, // 30 m
3600000, // 1 h
10800000, // 3 h
21600000, // 6 h
43200000, // 12 h
86400000, // 1 d
];
let lowestDist = -1;
let actualTickSize = units[0];
for (const unit of units) {
const dist = Math.abs(approxTickSize - unit);
if (lowestDist === -1 || dist < lowestDist) {
lowestDist = dist;
actualTickSize = unit;
}
}
// Find an "anchor" for the ticks to start. We want the ticks to be on a
// nice round hour/minute/second/millisecond, so take the start timestamp
// and truncate to the day.
const tickAnchor = new Date(tStart);
tickAnchor.setHours(0);
tickAnchor.setMinutes(0);
tickAnchor.setSeconds(0);
tickAnchor.setMilliseconds(0);
// Create the ticks. The first tick is the first multiple of the tick size
// which comes after tStart.
const numTicksPastAnchor = Math.ceil(
(tStart - tickAnchor.getTime()) / actualTickSize,
);
let tick = tickAnchor.getTime() + numTicksPastAnchor * actualTickSize;
const ticks = [];
while (tick < tEnd) {
ticks.push(tick);
tick += actualTickSize;
}
// Create background blocks for each epoch.
const epochs = data.epochs || [];
// Ensure that there's an epoch block which reaches to the end of the chart.
epochs.push(new Date(tEnd));
const normEpochs: Epoch[] = [];
const epochColors = ['#EFEFEF', '#EAEAEA'];
let lastX = blocksStartX;
for (let i = 0; i < epochs.length; i++) {
const epoch = epochs[i].getTime();
if (epoch >= tStart && epoch <= tEnd) {
const x = blocksStartX + (blocksWidth * (epoch - tStart)) / duration;
normEpochs.push({
x: lastX,
y: blocksStartY,
width: x - lastX,
height: blocksHeight,
color: epochColors[i % epochColors.length],
});
lastX = x;
}
}
const rulerTicks: RulerTick[] = [];
const rulerTexts: RulerText[] = [];
let lastDate = new Date(ticks[0]).getDate();
for (const tick of ticks) {
const x = blocksStartX + (blocksWidth * (tick - tStart)) / duration;
const y1 = blocksStartY + blocksHeight;
const y2 = y1 + rulerTickLength;
rulerTicks.push({
x1: x,
y1: y1,
x2: x,
y2: y2,
});
const d = new Date(tick);
rulerTexts.push({
x: x - rulerLabelMarginRight,
y: y2,
rotationX: x,
rotationY: y2,
text:
d.getDate() === lastDate ? d.toLocaleTimeString() : d.toLocaleString(),
});
lastDate = d.getDate();
}
// Draw border lines around the chart.
const borders = [
{
x1: blocksStartX,
y1: blocksStartY,
x2: blocksStartX,
y2: blocksStartY + blocksHeight,
},
{
x1: blocksStartX,
y1: blocksStartY + blocksHeight,
x2: blocksStartX + blocksWidth,
y2: blocksStartY + blocksHeight,
},
];
// Event handlers.
let dragStartX: number | undefined;
// Helper function for finding the x-value and timestamp given a mouse
// event.
const getMouseX = (e: MouseEvent): number => {
// Convert event x-coordinate to a coordinate within the chart area.
let x = e.clientX - boundingRect!.x;
if (x < blocksStartX) {
x = blocksStartX;
} else if (x > boundingRect!.width - chartMarginRight) {
x = boundingRect!.width - chartMarginRight;
}
// Find the nearest block border; if we're close enough, snap the line.
let nearest = 0;
let nearestDist = blocksWidth;
for (const block of blocks) {
let dist = Math.abs(block.x - x);
if (dist < nearestDist) {
nearest = block.x;
nearestDist = dist;
}
dist = Math.abs(block.x + block.width - x);
if (dist < nearestDist) {
nearest = block.x + block.width;
nearestDist = dist;
}
}
if (nearestDist < snapThreshold) {
x = nearest;
}
return x;
};
// Helper function for finding the timestamp associated with the given
// x-coordinate on the chart.
const getTimeAtMouseX = (x: number): Date => new Date(timeStart + ((x - blocksStartX) / blocksWidth) * duration);
// Create a vertical line used on mouseover. This is a helper function used
// by the mousemove callback function.
const mouseMoved = (e: MouseEvent) => {
const svg = $$<SVGElement>('svg', container);
if (!svg) {
return;
}
// Update the vertical cursor line.
const x = getMouseX(e);
const mouseLine = $$<SVGLineElement>('#mouse-line', svg)!;
mouseLine.setAttributeNS(null, 'x1', `${x}`);
mouseLine.setAttributeNS(null, 'x2', `${x}`);
// Update the timestamp for the cursor.
const ts = getTimeAtMouseX(x);
const mouseTime = $$<SVGTextElement>('#mouse-text', svg)!;
mouseTime.setAttributeNS(null, 'x', `${x}`);
mouseTime.innerHTML = ts.toLocaleTimeString();
// If we're selecting, update the selection box.
if (dragStartX !== undefined) {
let x1 = dragStartX;
let x2 = x;
if (x2 < x1) {
x2 = x1;
x1 = x;
}
const selectRect = $$<SVGRectElement>('#select-rect', svg)!;
const selectText = $$<SVGTextElement>('#select-text', svg)!;
const selectLineStart = $$<SVGLineElement>('#select-line-start', svg)!;
const selectLineEnd = $$<SVGLineElement>('#select-line-end', svg)!;
selectRect.setAttributeNS(null, 'x', `${x1}`);
selectRect.setAttributeNS(null, 'width', `${x2 - x1}`);
selectLineStart.setAttributeNS(null, 'x1', `${x1}`);
selectLineStart.setAttributeNS(null, 'x2', `${x1}`);
selectLineEnd.setAttributeNS(null, 'x1', `${x2}`);
selectLineEnd.setAttributeNS(null, 'x2', `${x2}`);
// Update the selected time range label.
const selectedDuration = getTimeAtMouseX(x2).getTime() - getTimeAtMouseX(x1).getTime();
selectText.setAttributeNS(null, 'x', `${(x1 + x2) / 2}`);
selectText.innerHTML = strDuration(selectedDuration / 1000);
// The cursor time label interferes with the selected time labels.
// make it disappear if we're actively selecting.
mouseTime.innerHTML = '';
}
};
// Create a selection box when the mouse is clicked and dragged. This is a
// helper function used by the mousedown callback function.
const mouseSelectStart = (e: MouseEvent) => {
const svg = $$<SVGElement>('svg', container);
if (!svg) {
return;
}
const selectRect = $$<SVGRectElement>('#select-rect', svg)!;
const selectLineStart = $$<SVGLineElement>('#select-line-start', svg)!;
const selectLineEnd = $$<SVGLineElement>('#select-line-end', svg)!;
const x = getMouseX(e);
selectRect.setAttributeNS(null, 'x', `${x}`);
selectLineStart.setAttributeNS(null, 'x1', `${x}`);
selectLineStart.setAttributeNS(null, 'x2', `${x}`);
selectLineEnd.setAttributeNS(null, 'x1', `${x}`);
selectLineEnd.setAttributeNS(null, 'x2', `${x}`);
dragStartX = x;
};
const mouseOut = (e: MouseEvent) => {
dragStartX = undefined;
};
// Render.
render(
svg`
<svg
width="${totalWidth}"
height="${totalHeight}"
@mousemove="${(e: MouseEvent) => {
mouseMoved(e);
}}"
@mousedown="${(e: MouseEvent) => {
mouseSelectStart(e);
}}"
@mouseup="${(e: MouseEvent) => {
mouseOut(e);
}}"
@mouseleave="${(e: MouseEvent) => {
mouseOut(e);
}}"
>
${normEpochs.map(
(epoch: Epoch) => svg`
<rect
x="${epoch.x}"
y="${epoch.y}"
width="${epoch.width}"
height="${epoch.height}"
class="epoch"
>
</rect>
`,
)}
${labels.map(
(lbl: Label) => svg`
<text
alignment-baseline="middle"
text-anchor="end"
x="${lbl.x}"
y="${lbl.y}"
width="${lbl.width}"
height="${labelHeight}"
>
${lbl.text}
</text>
`,
)}
${blocks.map(
(block: DisplayBlock) => svg`
<rect
x="${block.x}"
y="${block.y}"
width="${block.width}"
height="${block.height}"
fill="${block.color}"
>
<title>${block.title}</title>
</rect>
`,
)}
${borders.map(
(b: Border) => svg`
<line
x1="${b.x1}"
y1="${b.y1}"
x2="${b.x2}"
y2="${b.y2}"
>
</line>
`,
)}
${rulerTicks.map(
(tick: RulerTick) => svg`
<line
x1="${tick.x1}"
y1="${tick.y1}"
x2="${tick.x2}"
y2="${tick.y2}"
>
</line>
`,
)}
${rulerTexts.map(
(text: RulerText) => svg`
<text
alignment-baseline="middle"
text-anchor="end"
x="${text.x}"
y="${text.y}"
transform="rotate(${rulerLabelRotation} ${text.rotationX} ${text.rotationY})"
>
${text.text}
</text>
`,
)}
<line
id="mouse-line"
x1="-1000"
y1="${blocksStartY - 10}"
x2="-1000"
y2="${blocksStartY + blocksHeight}"
>
</line>
<text
id="mouse-text"
alignment-baseline="bottom"
text-anchor="middle"
x="-1000"
y="${blocksStartY - 20}"
>
</text>
<rect
id="select-rect"
fill="red"
fill-opacity="0.2"
x="-1000"
y="${blocksStartY}"
width="0"
height="${blocksHeight}"
>
</rect>
<text
id="select-text"
alignment-baseline="bottom"
text-anchor="middle"
x="-1000"
y="${blocksStartY - 10}"
>
</text>
<line
id="select-line-start"
x1="-1000"
y1="${blocksStartY - 10}"
x2="-1000"
y2="${blocksStartY}"
>
</line>
<line
id="select-line-end"
x1="-1000"
y1="${blocksStartY - 10}"
x2="-1000"
y2="${blocksStartY}"
>
</line>
</svg>
`,
container,
);
} | the_stack |
import utils from './utils'
import * as fse from 'fs-extra'
import * as path from 'path'
import * as xcode from 'xcode'
import * as merge from 'merge'
import * as colors from 'colors'
import * as plist from 'plist'
import * as EventEmitter from 'events'
import { LOGLEVEL } from './log-types'
import Config from './config'
import npmHelper from './utils/npm-helper'
import podfile from './utils/podfile'
export default class Plugin extends EventEmitter {
private shouldInstallPackage: boolean = false
private shouldUninstallPackage: boolean = false
private config: Config
private pluginConfigs: any
private pluginConfigPath: string
private androidPluginConfigs: any[]
private androidPluginConfigPath: string
constructor(config?: any) {
super()
this.config = new Config(config)
this.pluginConfigs = this.config.defaultConfig
// Get plugin config in project.
this.pluginConfigPath = path.join(this.config.rootPath, this.config.filename)
if (fse.existsSync(this.pluginConfigPath)) {
this.pluginConfigs = JSON.parse(fse.readFileSync(this.pluginConfigPath))
}
this.androidPluginConfigs = []
// Get plugin config in android project.
this.androidPluginConfigPath = path.join(this.config.androidPath, this.config.androidConfigFilename)
if (fse.existsSync(this.androidPluginConfigPath)) {
this.androidPluginConfigs = JSON.parse(fse.readFileSync(this.androidPluginConfigPath))
}
}
async installInPackage(dir, pluginName, version, option) {
const packageFilePath = path.join(dir, 'package.json')
this.emit(LOGLEVEL.LOG, 'Downloading plugin...')
if (fse.existsSync(packageFilePath)) {
const pkg = require(packageFilePath)
pkg.dependencies[pluginName] = version
fse.writeJson(packageFilePath, pkg, { spaces: '\t' })
}
await utils.installNpmPackage()
const browserPluginName = option.web && option.web.name ? option.web.name : pluginName
if (option.web) {
this.emit(LOGLEVEL.LOG, `Update plugins.json...`)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, browserPluginName, option, 'web')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
this.emit(LOGLEVEL.LOG, `Building plugins...`)
try {
await utils.buildJS('build:plugin', true)
this.emit(LOGLEVEL.SUCCESS, `Building plugins successful.`)
} catch (error) {
this.emit(LOGLEVEL.ERROR, error)
}
}
}
installPList(projectRoot, projectPath, config) {
const xcodeproj = xcode.project(projectPath)
xcodeproj.parseSync()
const xcBuildConfiguration = xcodeproj.pbxXCBuildConfigurationSection()
let plistFileEntry
let plistFile
for (const p in xcBuildConfiguration) {
const entry = xcBuildConfiguration[p]
if (entry.buildSettings && entry.buildSettings.INFOPLIST_FILE) {
plistFileEntry = entry
break
}
}
if (plistFileEntry) {
plistFile = path.join(
projectRoot,
plistFileEntry.buildSettings.INFOPLIST_FILE.replace(/^"(.*)"$/g, '$1').replace(/\\&/g, '&'),
)
}
if (!fse.existsSync(plistFile)) {
this.emit(LOGLEVEL.ERROR, 'Could not find *-Info.plist file')
} else {
let obj = plist.parse(fse.readFileSync(plistFile, 'utf8'))
obj = merge.recursive(true, obj, config)
fse.writeFileSync(plistFile, plist.build(obj))
}
}
async handleInstall(dir, pluginName, version, option) {
if (option.web) {
// should install npm package into project or not.
this.shouldInstallPackage = true
}
// check out the type of current project
if (utils.isIOSProject(dir)) {
const project: any = utils.isIOSProject(dir)
if (!fse.existsSync(path.join(dir, project.name, 'Podfile'))) {
this.emit(LOGLEVEL.ERROR, "can't find Podfile file")
return
}
const iosPackageName = option.ios && option.ios.name ? option.ios.name : pluginName
if (option.ios && option.ios.plist) {
let projectPath
if (!project.isWorkspace) {
projectPath = path.join(dir, project.name, 'project.pbxproj')
}
this.installPList(dir, projectPath, option.ios.plist || {})
} else if (option.ios) {
const iosVersion = (option.ios && option.ios.version) || version
const buildPatch = podfile.makeBuildPatch(iosPackageName, iosVersion)
// Build Podfile config.
podfile.applyPatch(path.join(dir, project.name, 'Podfile'), buildPatch)
this.emit(LOGLEVEL.WARN, `${pluginName} has installed success in iOS project.`)
this.emit(LOGLEVEL.INFO, `if you want to update it, please use \`weex plugin update\` command.`)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, iosPackageName, option, 'ios')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
}
}
if (utils.isAndroidProject(dir)) {
const androidPackageName = option.android && option.android.name ? option.android.name : pluginName
if (option.android) {
this.androidPluginConfigs = utils.updateAndroidPluginConfigs(
this.androidPluginConfigs,
androidPackageName,
option.android,
)
await utils.writeAndroidPluginFile(
this.config.androidPath,
this.androidPluginConfigPath,
this.androidPluginConfigs,
)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, androidPackageName, option, 'android')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
this.emit(LOGLEVEL.WARN, `${pluginName} has installed success in Android project.`)
this.emit(LOGLEVEL.INFO, `if you want to update it, please use \`weex plugin update\` command.`)
}
}
}
async installNewPlugin(dir, pluginName, version) {
let result: any = await utils.isNewVersionPlugin(pluginName, version)
if (result.error) {
this.emit(LOGLEVEL.ERROR, result.error)
return
} else if (result) {
await this.handleInstall(dir, pluginName, version, result)
if (this.shouldInstallPackage) {
await this.installInPackage(dir, pluginName, version, result)
}
} else {
this.emit(LOGLEVEL.WARN, `This package of weex is not support anymore! Please choose other package.`)
}
}
async installForWeb(plugins) {
if (!Array.isArray(plugins) || plugins.length <= 0) {
return
}
const packageJsonFile = path.join(this.config.root, 'package.json')
let packageJson = JSON.parse(fse.readFileSync(packageJsonFile))
plugins.forEach(plugin => {
packageJson['dependencies'][plugin.name] = plugin.version
})
packageJson = utils.sortDependencies(packageJson)
fse.writeJson(packageJsonFile, packageJson, { spaces: '\t' })
this.emit(LOGLEVEL.LOG, `Downloading plugins...`)
await utils.installNpmPackage()
this.emit(LOGLEVEL.LOG, `Building plugins...`)
try {
await utils.buildJS('build:plugin', true)
this.emit(LOGLEVEL.SUCCESS, `Building plugins successful.`)
} catch (error) {
this.emit(LOGLEVEL.ERROR, error)
}
}
async installForIOS(plugins) {
if (!Array.isArray(plugins) || plugins.length <= 0) {
return
}
plugins.forEach(plugin => {
const buildPatch = podfile.makeBuildPatch(plugin.name, plugin.version)
// Build Podfile config.
podfile.applyPatch(path.join(this.config.iosPath, 'Podfile'), buildPatch)
this.emit(LOGLEVEL.SUCCESS, `${plugin.name} has installed success in iOS project`)
})
}
async installForAndroid(plugins) {
if (!Array.isArray(plugins) || plugins.length <= 0) {
return
}
plugins.forEach(plugin => {
// write .wx_config.json on `platform/android`
this.androidPluginConfigs = utils.updateAndroidPluginConfigs(this.androidPluginConfigs, plugin.name, plugin)
this.emit(LOGLEVEL.SUCCESS, `${plugin.name} has installed success in Android project`)
})
await utils.writeAndroidPluginFile(this.config.androidPath, this.androidPluginConfigPath, this.androidPluginConfigs)
}
async install(pluginName) {
let version
if (/@/gi.test(pluginName)) {
const temp = pluginName.split('@')
pluginName = temp[0]
version = temp[1]
}
const dir = process.cwd()
// get the lastest version
if (!version) {
version = await npmHelper.getLastestVersion(pluginName)
await this.installNewPlugin(dir, pluginName, version)
} else {
await this.installNewPlugin(dir, pluginName, version)
}
}
async installForNewPlatform(platforms) {
const pluginsList = JSON.parse(fse.readFileSync(path.join(this.config.rootPath, this.config.filename)))
if (platforms && !Array.isArray(platforms)) {
platforms = [platforms]
}
platforms.forEach(async platform => {
switch (platform) {
case 'web':
await this.installForWeb(pluginsList[platform])
break
case 'ios':
await this.installForIOS(pluginsList[platform])
break
case 'android':
await this.installForAndroid(pluginsList[platform])
break
default:
break
}
})
}
async uninstallInPackage(dir, pluginName) {
const packageJsonPath = path.join(dir, 'package.json')
// Update package.json
if (fse.existsSync(packageJsonPath)) {
const packageJson = require(packageJsonPath)
if (packageJson.dependencies[pluginName]) {
delete packageJson.dependencies[pluginName]
}
fse.writeJson(packageJsonPath, packageJson, { spaces: '\t' })
}
this.emit(LOGLEVEL.INFO, `Update plugins.json...`)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, pluginName, {}, 'web')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
this.emit(LOGLEVEL.INFO, `Building plugins...`)
await utils.buildJS('build:plugin', true)
this.emit(LOGLEVEL.SUCCESS, `Building plugins successful.`)
}
async handleUninstall(dir, pluginName, version, option) {
if (option.web) {
// should install npm package into project or not.
this.shouldUninstallPackage = true
}
// check out the type of current project
if (utils.isIOSProject(dir)) {
const project: any = utils.isIOSProject(dir)
if (!fse.existsSync(path.join(dir, project.name, 'Podfile'))) {
this.emit(LOGLEVEL.ERROR, "can't find Podfile file")
return
}
const iosPackageName = option.ios && option.ios.name ? option.ios.name : pluginName
const iosVersion = (option.ios && option.ios.version) || version
const buildPatch = podfile.makeBuildPatch(iosPackageName, iosVersion)
// Remove Podfile config.
podfile.revokePatch(path.join(dir, project.name, 'Podfile'), buildPatch)
this.emit(LOGLEVEL.INFO, `${pluginName} has removed from iOS project`)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, iosPackageName, '', 'ios')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
}
if (utils.isAndroidProject(dir)) {
const androidPackageName = option.android && option.android.name ? option.android.name : pluginName
this.androidPluginConfigs = utils.updateAndroidPluginConfigs(this.androidPluginConfigs, androidPackageName)
await utils.writeAndroidPluginFile(
this.config.androidPath,
this.androidPluginConfigPath,
this.androidPluginConfigs,
)
// const androidVersion = option.android && option.android.version || version
// const buildPatch = gradle.makeBuildPatch(androidPackageName, androidVersion, option.android.groupId || '')
// Remove gradle config.
// gradle.revokePatch(path.join(dir, 'build.gradle'), buildPatch)
this.emit(LOGLEVEL.INFO, `${pluginName} has removed from Android project`)
// Update plugin.json in the project.
this.pluginConfigs = utils.updatePluginConfigs(this.pluginConfigs, androidPackageName, '', 'android')
await utils.writePluginFile(this.config.rootPath, this.pluginConfigPath, this.pluginConfigs)
}
if (fse.existsSync(path.join(dir, 'package.json'))) {
await this.uninstallInPackage(dir, pluginName)
} else {
this.emit(
LOGLEVEL.WARN,
`The project may not be a weex project, please use \`${colors.white.bold('weex create [projectname]')}\``,
)
}
}
async uninstallNewPlugin(dir, pluginName, version) {
let result = await utils.isNewVersionPlugin(pluginName, version)
if (result) {
await this.handleUninstall(dir, pluginName, version, result)
if (this.shouldUninstallPackage) {
await this.uninstallInPackage(dir, pluginName)
}
} else {
this.emit(LOGLEVEL.ERROR, `This package of weex is not support anymore! Please choose other package.`)
}
}
async uninstall(pluginName) {
let version
if (/@/gi.test(pluginName)) {
const temp = pluginName.split('@')
pluginName = temp[0]
version = temp[1]
}
const dir = process.cwd()
// get the lastest version
if (!version) {
version = await npmHelper.getLastestVersion(pluginName)
await this.uninstallNewPlugin(dir, pluginName, version)
} else {
await this.uninstallNewPlugin(dir, pluginName, version)
}
}
} | the_stack |
declare function cancelAnimationFrame(requestID: number): void;
/**
* 在下次进行重绘时执行。
*/
declare function requestAnimationFrame(callback: ()=>void): number;
/**
* 可取消由 setTimeout() 方法设置的定时器。
*/
declare function clearTimeout(timeoutID: number): void;
/**
* 可取消由 setInterval() 方法设置的定时器。
*/
declare function clearInterval(intervalID: number): void;
/**
* 设定一个定时器,在定时到期以后执行注册的回调函数
*/
declare function setTimeout(callback: ()=>void, delay: number, rest: any): number;
/**
* 设定一个定时器,按照指定的周期(以毫秒计)来执行注册的回调函数
*/
declare function setInterval(callback: ()=>void, delay: number, rest: any): number;
declare const wx: {
/**
* 创建一个画布对象。首次调用创建的是显示在屏幕上的画布,之后调用创建的都是离屏画布。
*/
createCanvas(): Canvas;
/**
* 只有开放数据域能调用,获取主域和开放数据域共享的 sharedCanvas
*/
getSharedCanvas(): Canvas;
/**
* 创建一个图片对象
*/
createImage(): Image;
/**
* 获取一行文本的行高
*/
getTextLineHeight(object: {fontStyle:string,fontWeight:string,fontSize:number,fontFamily:string,text:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): number;
/**
* 加载自定义字体文件
*/
loadFont(path: string): string;
/**
* 可以修改渲染帧率。默认渲染帧率为 60 帧每秒。修改后,requestAnimationFrame 的回调频率会发生改变。
*/
setPreferredFramesPerSecond(fps: number): void;
/**
* 退出当前小游戏
*/
exitMiniProgram(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 返回小程序启动参数
*/
getLaunchOptionsSync(): LaunchOption;
/**
* 监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。
*/
onHide(callback: ()=>void): void;
/**
* 取消监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。
*/
offHide(callback: ()=>void): void;
/**
* 监听小游戏回到前台的事件
*/
onShow(callback: ()=>void): void;
/**
* 取消监听小游戏回到前台的事件
*/
offShow(callback: ()=>void): void;
/**
* 获取系统信息
*/
getSystemInfo(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.getSystemInfo 的同步版本
*/
getSystemInfoSync(): SystemInfo;
/**
* 监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功
*/
onAudioInterruptionEnd(callback: ()=>void): void;
/**
* 取消监听音频中断结束,在收到 onAudioInterruptionBegin 事件之后,小程序内所有音频会暂停,收到此事件之后才可再次播放成功
*/
offAudioInterruptionEnd(callback: ()=>void): void;
/**
* 监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。
*/
onAudioInterruptionBegin(callback: ()=>void): void;
/**
* 取消监听音频因为受到系统占用而被中断开始,以下场景会触发此事件:闹钟、电话、FaceTime 通话、微信语音聊天、微信视频聊天。此事件触发后,小程序内所有音频会暂停。
*/
offAudioInterruptionBegin(callback: ()=>void): void;
/**
* 监听全局错误事件
*/
onError(callback: ()=>void): void;
/**
* 取消监听全局错误事件
*/
offError(callback: ()=>void): void;
/**
* 监听开始触摸事件
*/
onTouchStart(callback: ()=>void): void;
/**
* 取消监听开始触摸事件
*/
offTouchStart(callback: ()=>void): void;
/**
* 监听触点移动事件
*/
onTouchMove(callback: ()=>void): void;
/**
* 取消监听触点移动事件
*/
offTouchMove(callback: ()=>void): void;
/**
* 监听触摸结束事件
*/
onTouchEnd(callback: ()=>void): void;
/**
* 取消监听触摸结束事件
*/
offTouchEnd(callback: ()=>void): void;
/**
* 监听触点失效事件
*/
onTouchCancel(callback: ()=>void): void;
/**
* 取消监听触点失效事件
*/
offTouchCancel(callback: ()=>void): void;
/**
* 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 wx.stopAccelerometer 停止监听。
*/
onAccelerometerChange(callback: ()=>void): void;
startAccelerometer(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
stopAccelerometer(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取设备电量
*/
getBatteryInfo(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.getBatteryInfo 的同步版本
*/
getBatteryInfoSync(): string;
getClipboardData(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
setClipboardData(object: {data:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听罗盘数据,频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。
*/
onCompassChange(callback: ()=>void): void;
startCompass(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
stopCompass(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取网络类型
*/
getNetworkType(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
onNetworkStatusChange(callback: ()=>void): void;
getScreenBrightness(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
setKeepScreenOn(object: {keepScreenOn:boolean,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
setScreenBrightness(object: {value:number,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
vibrateShort(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
vibrateLong(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取全局唯一的文件管理器
*/
getFileSystemManager(): FileSystemManager;
/**
* 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用;当用户点击“显示在聊天顶部”时,此接口可继续调用。
*/
getLocation(object: {type:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 下载文件资源到本地,客户端直接发起一个 HTTP GET 请求,返回文件的本地文件路径。
*/
downloadFile(object: {url:string,header:Object,filePath:string,fail:(res:any)=>void,complete?:(res:any)=>void}): DownloadTask;
/**
* 发起网络请求。
*/
request(object: {url:string,data:string|Object,header?:Object,method:string,dataType?:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): RequestTask;
/**
* 创建一个 WebSocket 连接。最多同时存在 2 个 WebSocket 连接。
*/
connectSocket(object: {url:string,header:Object,method:string,protocols:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): SocketTask;
/**
* 关闭 WeSocket 连接
*/
closeSocket(object: {code:number,reason:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听WebSocket 连接打开事件
*/
onSocketOpen(callback: ()=>void): void;
/**
* 监听WebSocket 连接关闭事件
*/
onSocketClose(callback: ()=>void): void;
/**
* 监听WebSocket 接受到服务器的消息事件
*/
onSocketMessage(callback: ()=>void): void;
/**
* 监听WebSocket 错误事件
*/
onSocketError(callback: ()=>void): void;
/**
* 通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。
*/
sendSocketMessage(object: {data:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 将本地资源上传到开发者服务器,客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data 。
*/
uploadFile(object: {url:string,filePath:string,name:string,header:Object,formData:Object,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): UploadTask;
/**
* 通过 wx.login 接口获得的用户登录态拥有一定的时效性。用户越久未使用小程序,用户登录态越有可能失效。反之如果用户一直在使用小程序,则用户登录态一直保持有效。具体时效逻辑由微信维护,对开发者透明。开发者只需要调用 wx.checkSession 接口检测当前用户登录态是否有效。登录态过期后开发者可以再调用 wx.login 获取新的用户登录态。
*/
checkSession(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 调用接口获取登录凭证(code)进而换取用户登录态信息,包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)等。用户数据的加解密通讯需要依赖会话密钥完成。
*/
login(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
authorize(object: {scope:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 在无须用户授权的情况下,批量获取用户信息。该接口只在开放数据域下可用
*/
getUserInfo(object: {openIdList?:any[],lang?:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
getSetting(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
openSetting(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
getWeRunData(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 拉取当前用户所有同玩好友的托管数据。该接口只可在开放数据域下使用
*/
getFriendCloudStorage(object: {keyList:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 在小游戏是通过群分享卡片打开的情况下,可以通过调用该接口获取群同玩成员的游戏数据。该接口只可在开放数据域下使用。
*/
getGroupCloudStorage(object: {shareTicket:string,keyList:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取当前用户托管数据当中对应 key 的数据。该接口只可在开放数据域下使用
*/
getUserCloudStorage(object: {keyList:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 删除用户托管数据当中对应 key 的数据。
*/
removeUserCloudStorage(object: {keyList:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 对用户托管数据进行写数据操作,允许同时写多组 KV 数据。
*/
setUserCloudStorage(object: {KVDataList:any[],success:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取开放数据域
*/
getOpenDataContext(): OpenDataContext;
/**
* 监听主域发送的消息
*/
onMessage(callback: (data:any)=>void): void;
getShareInfo(object: {shareTicket:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
hideShareMenu(object?: {success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听用户点击右上角菜单的“转发”按钮时触发的事件
*/
onShareAppMessage(callback: ()=>void): void;
/**
* 取消监听用户点击右上角菜单的“转发”按钮时触发的事件
*/
offShareAppMessage(callback: ()=>void): void;
showShareMenu(object: {withShareTicket:boolean,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 主动拉起转发,进入选择通讯录界面。
*/
shareAppMessage(object: {title?:string,imageUrl?:string,query?:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
updateShareMenu(object: {withShareTicket?:boolean,success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
setEnableDebug(object: {enableDebug:boolean,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 清理本地数据缓存
*/
clearStorage(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.clearStorage 的同步版本
*/
clearStorageSync(): void;
/**
* 从本地缓存中异步获取指定 key 的内容
*/
getStorage(object: {key:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 异步获取当前storage的相关信息
*/
getStorageInfo(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.getStorage 的同步版本
*/
getStorageSync(key: string): Object|string;
/**
* wx.getStorageInfo 的同步版本
*/
getStorageInfoSync(): Object;
/**
* 从本地缓存中移除指定 key
*/
removeStorage(object: {key:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.removeStorage 的同步版本
*/
removeStorageSync(key: string): void;
/**
* 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容。
*/
setStorage(object: {key:string,data:Object|string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* wx.setStorage 的同步版本
*/
setStorageSync(key: string, data: Object|string): void;
/**
* 隐藏消息提示框
*/
hideToast(object?: {success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
hideLoading(object?: {success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 显示模态对话框
*/
showModal(object: {title:string,content:string,showCancel?:boolean,cancelText:string,cancelColor?:string,confirmText:string,confirmColor?:string,success:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 显示消息提示框
*/
showToast(object: {title:Object,icon:Object,image:Object,success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
showLoading(object: {title:string,mask:boolean,success?:(res:any)=>void,fail?:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 参数
*/
showActionSheet(object: {itemList:any[],itemColor:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 隐藏键盘
*/
hideKeyboard(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听键盘输入事件
*/
onKeyboardInput(callback: ()=>void): void;
/**
* 取消监听键盘输入事件
*/
offKeyboardInput(callback: ()=>void): void;
/**
* 监听用户点击键盘 Confirm 按钮时的事件
*/
onKeyboardConfirm(callback: ()=>void): void;
/**
* 取消监听用户点击键盘 Confirm 按钮时的事件
*/
offKeyboardConfirm(callback: ()=>void): void;
/**
* 监听监听键盘收起的事件
*/
onKeyboardComplete(callback: ()=>void): void;
/**
* 取消监听监听键盘收起的事件
*/
offKeyboardComplete(callback: ()=>void): void;
/**
* 显示键盘
*/
showKeyboard(object: {defaultValue:string,maxLength:number,multiple:boolean,confirmHold:boolean,confirmType:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 动态设置通过右上角按钮拉起的菜单的样式。
*/
setMenuStyle(object: {style:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 当在配置中设置 showStatusBarStyle 时,屏幕顶部会显示状态栏。此接口可以修改状态栏的样式。
*/
setStatusBarStyle(object: {style:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听窗口尺寸变化事件
*/
onWindowResize(callback: ()=>void): void;
/**
* 取消监听窗口尺寸变化事件
*/
offWindowResize(callback: ()=>void): void;
/**
* 返回值
*/
getUpdateManager(): UpdateManager;
/**
* 创建一个 Worker 线程,目前限制最多只能创建一个 Worker,创建下一个 Worker 前请调用 Worker.terminate
*/
createWorker(): Worker;
/**
* 创建一个 InnerAudioContext 实例
*/
createInnerAudioContext(): InnerAudioContext;
getRecorderManager(): RecorderManager;
/**
* 从本地相册选择图片或使用相机拍照。
*/
chooseImage(object: {count:number}): void;
/**
* 预览图片
*/
previewImage(object: {current:string,urls:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
saveImageToPhotosAlbum(object: {filePath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 创建视频
*/
createVideo(object: {x:number,y:number,width:number,height:number,src:number,poster:number,initialTime:number,playbackRate:number,live:number,objectFit:number,controls:number,autoplay:number,loop:number,muted:number}): Video;
/**
* 获取性能管理器
*/
getPerformance(): Performance;
/**
* 加快触发 JavaScrpitCore Garbage Collection(垃圾回收),GC 时机是由 JavaScrpitCore 来控制的,并不能保证调用后马上触发 GC。
*/
triggerGC(): void;
/**
* 发起米大师支付
*/
requestMidasPayment(object: {mode:string,env:number,offerId:string,currencyType:string,platform:string,buyQuantity:number,zoneId:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
}
declare interface Canvas {
/**
* 获取画布对象的绘图上下文
*/
getContext(contextType: string, contextAttributes: {antialias:boolean,preserveDrawingBuffer:boolean,antialiasSamples:number}): RenderingContext;
/**
* 将当前 Canvas 保存为一个临时文件,并生成相应的临时文件路径。
*/
toTempFilePath(object: {x:number,y:number,width:number,height:number,destWidth:number,destHeight:number,fileType:string,quality:number,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): string;
/**
* 把画布上的绘制内容以一个 data URI 的格式返回
*/
toDataURL(): string;
/**
* Canvas.toTempFilePath 的同步版本
*/
toTempFilePathSync(object: {x:number,y:number,width:number,height:number,destWidth:number,destHeight:number,fileType:string,quality:number}): void;
}
declare interface FileSystemManager {
/**
* 判断文件/目录是否存在
*/
access(object: {path:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.access 的同步版本
*/
accessSync(path: string): void;
/**
* 复制文件
*/
copyFile(object: {srcPath:string,destPath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.copyFile 的同步版本
*/
copyFileSync(srcPath: string, destPath: string): void;
/**
* 获取该小程序下的 本地临时文件 或 本地缓存文件 信息
*/
getFileInfo(object: {filePath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取该小程序下已保存的本地缓存文件列表
*/
getSavedFileList(object: {success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 创建目录
*/
mkdir(object: {dirPath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.mkdir 的同步版本
*/
mkdirSync(dirPath: string): void;
/**
* 删除该小程序下已保存的本地缓存文件
*/
removeSavedFile(object: {filePath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 读取本地文件内容
*/
readFile(object: {filePath:string,encoding:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 重命名文件,可以把文件从 oldPath 移动到 newPath
*/
rename(object: {oldPath:string,newPath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 删除目录
*/
rmdir(object: {dirPath:Object,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 读取目录内文件列表
*/
readdir(object: {dirPath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.readdir 的同步版本
*/
readdirSync(dirPath: string): string[];
/**
* FileSystemManager.rename 的同步版本
*/
renameSync(oldPath: string, newPath: string): void;
/**
* FileSystemManager.rmdir 的同步版本
*/
rmdirSync(dirPath: {}): void;
/**
* FileSystemManager.readFile 的同步版本
*/
readFileSync(filePath: string, encoding: string): string[];
/**
* 保存临时文件到本地。此接口会移动临时文件,因此调用成功后,tempFilePath 将不可用。
*/
saveFile(object: {tempFilePath:string,filePath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 获取文件 Stats 对象
*/
stat(object: {path:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): Stats;
/**
* FileSystemManager.saveFile 的同步版本
*/
saveFileSync(tempFilePath: string, filePath: string): number;
/**
* FileSystemManager.stat 的同步版本
*/
statSync(path: string): Stats;
/**
* 删除文件
*/
unlink(object: {filePath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 解压文件
*/
unzip(object: {zipFilePath:string,targetPath:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.unlink 的同步版本
*/
unlinkSync(filePath: string): void;
/**
* 写文件
*/
writeFile(object: {filePath:string,data:any[],encoding:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* FileSystemManager.writeFile 的同步版本
*/
writeFileSync(filePath: string, data: string|ArrayBuffer, encoding: string): void;
}
declare interface Stats {
/**
* 判断当前文件是否一个目录
*/
isDirectory(): boolean;
/**
* 判断当前文件是否一个普通文件
*/
isFile(): boolean;
}
declare interface DownloadTask {
abort(): void;
onProgressUpdate(callback: ()=>void): void;
}
declare interface RequestTask {
abort(): void;
}
declare interface SocketTask {
/**
* 关闭 WebSocket 连接
*/
close(object: {code:number,reason:string,success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
/**
* 监听WebSocket 连接打开事件
*/
onOpen(callback: ()=>void): void;
/**
* 监听WebSocket 连接关闭事件
*/
onClose(callback: ()=>void): void;
/**
* 监听WebSocket 错误事件
*/
onError(callback: ()=>void): void;
/**
* 监听WebSocket 接受到服务器的消息事件
*/
onMessage(callback: ()=>void): void;
/**
* 通过 WebSocket 连接发送数据
*/
send(object: {data:any[],success:(res:any)=>void,fail:(res:any)=>void,complete?:(res:any)=>void}): void;
}
declare interface UploadTask {
abort(): void;
onProgressUpdate(callback: ()=>void): void;
}
declare interface OpenDataContext {
/**
* 向开放数据域发送消息
*/
postMessage(message: {}): void;
}
declare interface UpdateManager {
/**
* 应用更新包并重启
*/
applyUpdate(): void;
/**
* 监听检查更新结果回调
*/
onCheckForUpdate(callback: ()=>void): void;
/**
* 监听更新包下载成功回调
*/
onUpdateReady(callback: ()=>void): void;
/**
* 监听更新包下载失败回调
*/
onUpdateFailed(callback: ()=>void): void;
}
declare interface Worker {
/**
* 监听接收主线程/Worker 线程向当前线程发送的消息
*/
onMessage(callback: ()=>void): void;
/**
* 向主线程/Worker 线程发送的消息。
*/
postMessage(message: {}): void;
/**
* 结束当前 worker 线程,仅限在主线程 worker 对象上调用。
*/
terminate(): void;
}
declare interface InnerAudioContext {
/**
* 销毁当前实例
*/
destroy(): void;
/**
* 取消监听音频进入可以播放状态的事件
*/
offCanplay(callback: ()=>void): void;
/**
* 监听音频暂停事件
*/
onPause(callback: ()=>void): void;
/**
* 监听音频停止事件
*/
onStop(callback: ()=>void): void;
/**
* 取消监听音频停止事件
*/
offStop(callback: ()=>void): void;
/**
* 监听音频自然播放至结束的事件
*/
onEnded(callback: ()=>void): void;
/**
* 取消监听音频自然播放至结束的事件
*/
offEnded(callback: ()=>void): void;
/**
* 监听音频播放进度更新事件
*/
onTimeUpdate(callback: ()=>void): void;
/**
* 监听音频播放事件
*/
onPlay(callback: ()=>void): void;
/**
* 监听音频播放错误事件
*/
onError(callback: ()=>void): void;
/**
* 取消监听音频暂停事件
*/
offPause(callback: ()=>void): void;
/**
* 监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发
*/
onWaiting(callback: ()=>void): void;
/**
* 取消监听音频加载中事件,当音频因为数据不足,需要停下来加载时会触发
*/
offWaiting(callback: ()=>void): void;
/**
* 监听音频进行跳转操作的事件
*/
onSeeking(callback: ()=>void): void;
/**
* 取消监听音频进行跳转操作的事件
*/
offSeeking(callback: ()=>void): void;
/**
* 监听音频完成跳转操作的事件
*/
onSeeked(callback: ()=>void): void;
/**
* 取消监听音频完成跳转操作的事件
*/
offSeeked(callback: ()=>void): void;
/**
* 取消监听音频播放事件
*/
offPlay(callback: ()=>void): void;
/**
* 取消监听音频播放进度更新事件
*/
offTimeUpdate(callback: ()=>void): void;
/**
* 监听音频进入可以播放状态的事件
*/
onCanplay(callback: ()=>void): void;
/**
* 取消监听音频播放错误事件
*/
offError(callback: ()=>void): void;
/**
* 停止。停止后的音频再播放会从头开始播放。
*/
pause(): void;
/**
* 播放
*/
play(): void;
/**
* 跳转到指定位置,单位 s
*/
seek(position: number): void;
src:string;
autoplay:boolean;
loop:boolean;
obeyMuteSwitch:boolean;
duration:number;
buffered:number;
volume:number;
}
declare interface RecorderManager {
/**
* 监听录音暂停事件
*/
onPause(callback: ()=>void): void;
/**
* 监听录音结束事件
*/
onStop(callback: ()=>void): void;
/**
* 监听已录制完指定帧大小的文件事件。如果设置了 frameSize,则会回调此事件。
*/
onFrameRecorded(callback: ()=>void): void;
/**
* 监听录音错误事件
*/
onError(callback: ()=>void): void;
/**
* 监听录音开始事件
*/
onStart(callback: ()=>void): void;
/**
* 暂停录音
*/
pause(): void;
/**
* 继续录音
*/
resume(): void;
/**
* 停止录音
*/
stop(): void;
/**
* 开始录音
*/
start(object: {duration:number,sampleRate:number,numberOfChannels:number,encodeBitRate:number,format:string,frameSize:number}): void;
}
declare interface Video {
/**
* 视频退出全屏
*/
exitFullScreen(): Promise<Object>;
/**
* 取消监听视频暂停事件
*/
offPause(callback: ()=>void): void;
/**
* 监听视频播放到末尾事件
*/
onEnded(callback: ()=>void): void;
/**
* 取消监听视频播放到末尾事件
*/
offEnded(callback: ()=>void): void;
/**
* 监听视频播放进度更新事件
*/
onTimeUpdate(callback: ()=>void): void;
/**
* 取消监听视频播放进度更新事件
*/
offTimeUpdate(callback: ()=>void): void;
/**
* 监听视频错误事件
*/
onError(callback: ()=>void): void;
/**
* 取消监听视频错误事件
*/
offError(callback: ()=>void): void;
/**
* 监听视频播放事件
*/
onPlay(callback: ()=>void): void;
/**
* 监听视频暂停事件
*/
onPause(callback: ()=>void): void;
/**
* 取消监听视频缓冲事件
*/
offWaiting(callback: ()=>void): void;
/**
* 监听视频缓冲事件
*/
onWaiting(callback: ()=>void): void;
/**
* 取消监听视频播放事件
*/
offPlay(callback: ()=>void): void;
/**
* 暂停视频
*/
pause(): Promise<Object>;
/**
* 播放视频
*/
play(): Promise<Object>;
/**
* 视频全屏
*/
requestFullScreen(): Promise<Object>;
/**
* 视频跳转
*/
seek(time: number): Promise<Object>;
/**
* 停止视频
*/
stop(): Promise<Object>;
}
declare interface Performance {
/**
* 可以获取当前时间以微秒为单位的时间戳
*/
now(): number;
}
declare interface Image {
/**
* 图片的 URL
*/
src: string;
/**
* 图片的真实宽度
*/
width: number;
/**
* 图片的真实高度
*/
height: number;
/**
* 图片的加载完成
*/
onload: () => void;
}
declare class LaunchOption {
/** 场景值*/
scene: number;
/** 启动参数*/
query: Object;
/** 当前小游戏是否被显示在聊天顶部*/
isSticky: boolean;
/** shareTicket*/
shareTicket: string;
}
declare class SystemInfo {
/** 手机品牌*/
brand: string;
/** 手机型号*/
model: string;
/** 设备像素比 */
pixelRatio: number;
/** 屏幕宽度*/
screenWidth: number;
/** 屏幕高度*/
screenHeight: number;
/** 可使用窗口宽度*/
windowWidth: number;
/** 可使用窗口高度*/
windowHeight: number;
/** 微信设置的语言*/
language: string;
/** 微信版本号*/
version: string;
/** 操作系统版本*/
system: string;
/** 客户端平台*/
platform: string
/** 用户字体大小设置。以“我-设置 - 通用 - 字体大小”中的设置为准,单位 px。*/
fontSizeSetting: number;
/** 客户端基础库版本*/
SDKVersion: string;
/** 性能等级*/
benchmarkLevel: number;
/** 电量,范围 1 - 100*/
battery: number;
/** wifi 信号强度,范围 0 - 4 */
wifiSignal: number;
}
declare class Stats {
/**
* 文件的类型和存取的权限,对应 POSIX stat.st_mode
*/
mode: string;
/**
* 文件大小,单位:B,对应 POSIX stat.st_size
*/
size: number;
/**
* 文件最近一次被存取或被执行的时间,UNIX 时间戳,对应 POSIX stat.st_atime
*/
lastAccessedTime: number;
/**
* 文件最后一次被修改的时间,UNIX 时间戳,对应 POSIX stat.st_mtime
*/
lastModifiedTime: number;
}
/**
* 通过 Canvas.getContext('2d') 接口可以获取 CanvasRenderingContext2D 对象。CanvasRenderingContext2D 实现了 HTML The 2D rendering context 定义的大部分属性、方法。通过 Canvas.getContext('webgl') 接口可以获取 WebGLRenderingContext 对象。 WebGLRenderingContext 实现了 WebGL 1.0 定义的所有属性、方法、常量。
* 2d 接口支持情况
* iOS/Android 不支持的 2d 属性和接口
* globalCompositeOperation 不支持以下值: source-in source-out destination-atop lighter copy。如果使用,不会报错,但是将得到与预期不符的结果。
* isPointInPath
* WebGL 接口支持情况
* iOS/Android 不支持的 WebGL 接
*/
declare interface RenderingContext {} | the_stack |
import { Component, OnDestroy, OnInit, TemplateRef, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, Observable, Subscription, from } from 'rxjs';
import { JhiAlertService, JhiEventManager } from 'ng-jhipster';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { Gateway } from 'app/shared/model/gateway.model';
import { Flow, IFlow, LogLevelType } from 'app/shared/model/flow.model';
import { FlowService } from './flow.service';
import { Endpoint, EndpointType, IEndpoint } from 'app/shared/model/endpoint.model';
import { IHeader } from 'app/shared/model/header.model';
import { Service } from 'app/shared/model/service.model';
import { Route } from 'app/shared/model/route.model';
import { EndpointService } from '../endpoint/';
import { ServiceService } from '../service';
import { HeaderService } from '../header';
import { RouteService } from '../route';
import { GatewayService } from '../gateway';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { Components, ComponentType, typesLinks } from '../../shared/camel/component-type';
import { Services } from '../../shared/camel/service-connections';
import { map } from 'rxjs/operators';
import { HeaderDialogComponent, HeaderPopupService } from 'app/entities/header';
import { RouteDialogComponent, RoutePopupService } from 'app/entities/route';
import { ServiceDialogComponent, ServicePopupService } from 'app/entities/service';
import * as moment from 'moment';
@Component({
selector: 'jhi-flow-edit-all',
templateUrl: './flow-edit-all.component.html',
encapsulation: ViewEncapsulation.None
})
export class FlowEditAllComponent implements OnInit, OnDestroy {
flow: IFlow;
headers: IHeader[];
routes: Route[];
services: Service[];
endpointsOptions: Array<Array<Option>> = [[]];
URIList: Array<Array<Endpoint>> = [[]];
allendpoints: IEndpoint[] = new Array<Endpoint>();
endpoints: IEndpoint[] = new Array<Endpoint>();
endpoint: IEndpoint;
public endpointTypes = ['FROM', 'TO', 'ERROR']; //Dont include RESPONSE here!
public logLevelListType = [
LogLevelType.OFF,
LogLevelType.INFO,
LogLevelType.ERROR,
LogLevelType.TRACE,
LogLevelType.WARN,
LogLevelType.DEBUG
];
panelCollapsed: any = 'uno';
public isCollapsed = true;
active;
active2;
disabled = true;
activeEndpoint: any;
isSaving: boolean;
savingFlowFailed = false;
savingFlowFailedMessage = 'Saving failed (check logs)';
savingFlowSuccess = false;
savingFlowSuccessMessage = 'Flow successfully saved';
savingCheckEndpoints = true;
finished = false;
gateways: Gateway[];
configuredGateway: Gateway;
gatewayName: String;
singleGateway = false;
indexGateway: number;
embeddedBroker = false;
createRoute: number;
predicate: any;
reverse: any;
headerCreated: boolean;
routeCreated: boolean;
serviceCreated: boolean;
namePopoverMessage: string;
notesPopoverMessage: string;
autoStartPopoverMessage: string;
assimblyHeadersPopoverMessage: string;
offloadingPopoverMessage: string;
parallelProcessingPopoverMessage: string;
maximumRedeliveriesPopoverMessage: string;
redeliveryDelayPopoverMessage: string;
logLevelPopoverMessage: string;
componentPopoverMessage: string;
optionsPopoverMessage: string;
headerPopoverMessage: string;
routePopoverMessage: string;
servicePopoverMessage: string;
popoverMessage: string;
selectedComponentType: string;
selectedOptions: Array<Array<any>> = [[]];
componentOptions: Array<any> = [];
customOptions: Array<any> = [];
componentTypeAssimblyLinks: Array<string> = new Array<string>();
componentTypeCamelLinks: Array<string> = new Array<string>();
uriPlaceholders: Array<string> = new Array<string>();
uriPopoverMessages: Array<string> = new Array<string>();
typesLinks: Array<TypeLinks>;
editFlowForm: FormGroup;
displayNextButton = false;
invalidUriMessage: string;
notUniqueUriMessage: string;
testConnectionForm: FormGroup;
testConnectionMessage: string;
connectionHost: any;
connectionPort: any;
connectionTimeout: any;
hostnamePopoverMessage: string;
portPopoverMessage: string;
timeoutPopoverMessage: string;
filterService: Array<Array<Service>> = [[]];
serviceType: Array<string> = [];
selectedService: Service = new Service();
closeResult: string;
numberOfFromEndpoints: number = 0;
numberOfToEndpoints: number = 0;
numberOfResponseEndpoints: number = 0;
private subscription: Subscription;
private eventSubscriber: Subscription;
private wikiDocUrl: string;
private camelDocUrl: string;
loading = false;
modalRef: NgbModalRef | null;
constructor(
private eventManager: JhiEventManager,
private gatewayService: GatewayService,
private flowService: FlowService,
private endpointService: EndpointService,
private headerService: HeaderService,
private routeService: RouteService,
private serviceService: ServiceService,
private jhiAlertService: JhiAlertService,
private route: ActivatedRoute,
private router: Router,
public servicesList: Services,
public components: Components,
private modalService: NgbModal,
private headerPopupService: HeaderPopupService,
private routePopupService: RoutePopupService,
private servicePopupService: ServicePopupService
) {}
ngOnInit() {
this.isSaving = false;
this.createRoute = 0;
this.setPopoverMessages();
this.activeEndpoint = this.route.snapshot.queryParamMap.get('endpointid');
this.subscription = this.route.params.subscribe(params => {
if (params['mode'] === 'clone') {
this.load(params['id'], true);
} else {
this.load(params['id'], false);
}
});
this.registerChangeInFlows();
}
load(id, isCloning?: boolean) {
forkJoin([
this.flowService.getWikiDocUrl(),
this.flowService.getCamelDocUrl(),
this.headerService.getAllHeaders(),
this.routeService.getAllRoutes(),
this.serviceService.getAllServices(),
this.gatewayService.query(),
this.endpointService.query(),
this.flowService.getGatewayName()
]).subscribe(([wikiDocUrl, camelDocUrl, headers, routes, services, gateways, allendpoints, gatewayName]) => {
this.wikiDocUrl = wikiDocUrl.body;
this.camelDocUrl = camelDocUrl.body;
this.headers = headers.body;
this.headerCreated = this.headers.length > 0;
this.routes = routes.body;
this.routeCreated = this.routes.length > 0;
this.services = services.body;
this.serviceCreated = this.services.length > 0;
this.gateways = gateways.body;
this.singleGateway = this.gateways.length === 1;
this.gatewayName = gatewayName.body;
this.allendpoints = allendpoints.body;
if (this.singleGateway) {
this.indexGateway = 0;
if (this.gateways[this.indexGateway].type.valueOf().toLocaleLowerCase() == 'broker') {
this.embeddedBroker = true;
}
} else {
this.indexGateway = this.gateways.findIndex(gateway => gateway.name === this.gatewayName);
if (this.gateways[this.indexGateway].type.valueOf().toLocaleLowerCase() == 'broker') {
this.embeddedBroker = true;
}
}
if (id) {
this.flowService.find(id).subscribe(flow => {
if (flow) {
this.flow = flow.body;
if (this.singleGateway) {
this.flow.gatewayId = this.gateways[this.indexGateway].id;
}
this.initializeForm(this.flow);
this.endpointService.findByFlowId(id).subscribe(flowEndpointsData => {
let endpoints = flowEndpointsData.body;
let index = 0;
this.endpoints = [];
this.endpointTypes.forEach((endpointType, j) => {
let filteredEndpoints = endpoints.filter(endpoint => endpoint.endpointType === endpointType);
let filteredEndpointsWithResponse = new Array<Endpoint>();
//add response endpoints
filteredEndpoints.forEach(endpoint => {
filteredEndpointsWithResponse.push(endpoint);
if (endpoint.responseId != undefined) {
endpoints.filter(ep => {
if (ep.endpointType === 'RESPONSE' && ep.responseId === endpoint.responseId) {
this.numberOfResponseEndpoints += 1;
filteredEndpointsWithResponse.push(ep);
}
});
}
});
filteredEndpoints = filteredEndpointsWithResponse;
filteredEndpoints.forEach((endpoint, i) => {
if (typeof this.endpointsOptions[index] === 'undefined') {
this.endpointsOptions.push([]);
}
this.endpoint = new Endpoint(
endpoint.id,
endpoint.endpointType,
endpoint.componentType,
endpoint.uri,
endpoint.options,
endpoint.responseId,
endpoint.flowId,
endpoint.serviceId,
endpoint.headerId,
endpoint.routeId
);
this.endpoints.push(endpoint);
let formgroup = this.initializeEndpointData(endpoint);
(<FormArray>this.editFlowForm.controls.endpointsData).insert(index, formgroup);
this.setTypeLinks(endpoint, index);
this.getOptions(
endpoint,
this.editFlowForm.controls.endpointsData.get(index.toString()),
this.endpointsOptions[index],
index
);
if (this.endpoint.endpointType === 'FROM') {
this.numberOfFromEndpoints = this.numberOfFromEndpoints + 1;
} else if (this.endpoint.endpointType === 'TO') {
this.numberOfToEndpoints = this.numberOfToEndpoints + 1;
}
index = index + 1;
}, this);
}, this);
if (this.activeEndpoint) {
const activeIndex = this.endpoints.findIndex(item => item.id == this.activeEndpoint);
if (activeIndex === -1) {
this.active = '0';
} else {
this.active = activeIndex.toString();
}
} else {
this.active = '0';
}
if (isCloning) {
this.clone();
}
this.finished = true;
});
}
});
} else if (!this.finished) {
setTimeout(() => {
//create new flow object
this.flow = new Flow();
this.flow.notes = '';
this.flow.autoStart = false;
this.flow.offLoading = false;
this.flow.parallelProcessing = true;
this.flow.assimblyHeaders = true;
this.flow.maximumRedeliveries = 0;
this.flow.redeliveryDelay = 3000;
this.flow.logLevel = LogLevelType.OFF;
if (this.singleGateway) {
this.indexGateway = 0;
this.flow.gatewayId = this.gateways[this.indexGateway].id;
} else {
this.configuredGateway = this.gateways.find(gateway => gateway.name === this.gatewayName);
this.indexGateway = this.gateways.findIndex(gateway => gateway.name === this.gatewayName);
this.flow.gatewayId = this.configuredGateway.id;
}
this.initializeForm(this.flow);
//create new from endpoint
this.endpoint = new Endpoint();
this.endpoint.endpointType = EndpointType.FROM;
this.endpoint.componentType = ComponentType[this.gateways[this.indexGateway].defaultFromComponentType];
(<FormArray>this.editFlowForm.controls.endpointsData).push(this.initializeEndpointData(this.endpoint));
this.endpointsOptions[0] = [new Option()];
//set documentation links
this.setTypeLinks(this.endpoint, 0);
let componentType = this.endpoint.componentType.toString().toLowerCase();
let camelComponentType = this.components.getCamelComponentType(componentType);
//get list of options (from Camel Catalog
this.setComponentOptions(this.endpoint, camelComponentType);
this.numberOfFromEndpoints = 1;
let optionArrayFrom: Array<string> = [];
optionArrayFrom.splice(0, 0, '');
this.selectedOptions.splice(0, 0, optionArrayFrom);
this.endpoints.push(this.endpoint);
//create new to endpoint
this.endpoint = new Endpoint();
this.endpoint.endpointType = EndpointType.TO;
this.endpoint.componentType = ComponentType[this.gateways[this.indexGateway].defaultToComponentType];
(<FormArray>this.editFlowForm.controls.endpointsData).push(this.initializeEndpointData(this.endpoint));
this.endpointsOptions[1] = [new Option()];
this.setTypeLinks(this.endpoint, 1);
componentType = this.endpoint.componentType.toString().toLowerCase();
camelComponentType = this.components.getCamelComponentType(componentType);
this.setComponentOptions(this.endpoint, camelComponentType);
this.numberOfToEndpoints = 1;
let optionArrayTo: Array<string> = [];
optionArrayTo.splice(0, 0, '');
this.selectedOptions.splice(1, 0, optionArrayTo);
this.endpoints.push(this.endpoint);
//create new error endpoint
this.endpoint = new Endpoint();
this.endpoint.endpointType = EndpointType.ERROR;
this.endpoint.componentType = ComponentType[this.gateways[this.indexGateway].defaultErrorComponentType];
(<FormArray>this.editFlowForm.controls.endpointsData).push(this.initializeEndpointData(this.endpoint));
this.endpointsOptions[2] = [new Option()];
this.setTypeLinks(this.endpoint, 2);
componentType = this.endpoint.componentType.toString().toLowerCase();
camelComponentType = this.components.getCamelComponentType(componentType);
this.setComponentOptions(this.endpoint, camelComponentType);
let optionArrayError: Array<string> = [];
optionArrayError.splice(0, 0, '');
this.selectedOptions.splice(2, 0, optionArrayError);
this.endpoints.push(this.endpoint);
this.finished = true;
this.displayNextButton = true;
}, 0);
}
this.active = '0';
});
}
clone() {
//reset id and flow name to null
this.flow.id = null;
this.flow.name = null;
this.flow.endpoints = null;
this.endpoints.forEach((endpoint, i) => {
endpoint.id = null;
});
this.updateForm();
let scrollToTop = window.setInterval(() => {
let pos = window.pageYOffset;
if (pos > 0) {
window.scrollTo(0, pos - 20); // how far to scroll on each step
} else {
window.clearInterval(scrollToTop);
}
}, 16);
}
//this filters services not of the correct type
filterServices(endpoint: any, formService: FormControl) {
this.serviceType[this.endpoints.indexOf(endpoint)] = this.servicesList.getServiceType(endpoint.componentType);
this.filterService[this.endpoints.indexOf(endpoint)] = this.services.filter(
f => f.type === this.serviceType[this.endpoints.indexOf(endpoint)]
);
if (this.filterService[this.endpoints.indexOf(endpoint)].length > 0 && endpoint.serviceId) {
formService.setValue(this.filterService[this.endpoints.indexOf(endpoint)].find(fs => fs.id === endpoint.serviceId).id);
}
}
setTypeLinks(endpoint: any, endpointFormIndex?, e?: Event) {
const endpointForm = <FormGroup>(<FormArray>this.editFlowForm.controls.endpointsData).controls[endpointFormIndex];
if (typeof e !== 'undefined') {
//set componenttype to selected component and clear other fields
endpoint.componentType = e;
endpoint.uri = null;
endpoint.headerId = '';
endpoint.routeId = '';
endpoint.serviceId = '';
let i;
let numberOfOptions = this.endpointsOptions[endpointFormIndex].length - 1;
for (i = numberOfOptions; i > 0; i--) {
this.endpointsOptions[endpointFormIndex][i] = null;
this.removeOption(this.endpointsOptions[endpointFormIndex], this.endpointsOptions[endpointFormIndex][i], endpointFormIndex);
}
endpointForm.controls.uri.patchValue(endpoint.uri);
(<FormArray>endpointForm.controls.options).controls[0].patchValue({
key: null,
value: null
});
endpointForm.controls.header.patchValue(endpoint.headerId);
endpointForm.controls.service.patchValue(endpoint.routeId);
endpointForm.controls.service.patchValue(endpoint.serviceId);
} else if (!endpoint.componentType) {
endpoint.componentType = ComponentType.FILE;
}
let type;
let camelType;
let componentType;
let camelComponentType;
this.selectedComponentType = endpoint.componentType.toString();
componentType = endpoint.componentType.toString().toLowerCase();
camelComponentType = this.components.getCamelComponentType(componentType);
type = typesLinks.find(x => x.name === endpoint.componentType.toString());
camelType = typesLinks.find(x => x.name === camelComponentType.toUpperCase());
this.filterServices(endpoint, endpointForm.controls.service as FormControl);
this.componentTypeAssimblyLinks[endpointFormIndex] = this.wikiDocUrl + type.assimblyTypeLink;
this.componentTypeCamelLinks[endpointFormIndex] = this.camelDocUrl + camelType.camelTypeLink;
this.uriPlaceholders[endpointFormIndex] = type.uriPlaceholder;
this.uriPopoverMessages[endpointFormIndex] = type.uriPopoverMessage;
// set options keys
if (typeof e !== 'undefined') {
this.setComponentOptions(endpoint, camelComponentType).subscribe(data => {
//add custom options if available
this.customOptions.forEach(customOption => {
if (customOption.componentType === camelComponentType) {
this.componentOptions[endpointFormIndex].push(customOption);
}
});
});
}
endpointForm.patchValue({ componentType: componentType.toUpperCase() });
this.enableFields(endpointForm);
this.setURIlist(endpointFormIndex);
}
setPopoverMessages() {
this.namePopoverMessage = `Name of the flow. Usually the name of the message type like <i>order</i>.<br/><br>Displayed on the <i>flows</i> page.`;
this.notesPopoverMessage = `Notes to documentatie your flow`;
this.autoStartPopoverMessage = `If true then the flow starts automatically when the gateway starts.`;
this.assimblyHeadersPopoverMessage = `If true then message headers like timestamp, uri, flowid and correlationid are set. These headers start with Assimbly and can be used for logging purposes. `;
this.offloadingPopoverMessage = `If true then the flow sends a copy of every message to the wiretap endpoint.<br/><br/>
This endpoint is configured at <i>Settings --> Offloading</i>.`;
this.parallelProcessingPopoverMessage = `If true then to endpoints are processed in parallel.`;
this.maximumRedeliveriesPopoverMessage = `The maximum times a messages is redelivered in case of failure.<br/><br/>`;
this.redeliveryDelayPopoverMessage = `The delay in miliseconds between redeliveries (this delays all messages!)`;
this.logLevelPopoverMessage = `Sets the log level (default=OFF). This logs incoming and outgoing messages in the flow`;
this.componentPopoverMessage = `The Apache Camel scheme to use. Click on the Apache Camel or Assimbly button for online documentation on the selected scheme.`;
this.optionsPopoverMessage = `Options for the selected component. You can add one or more key/value pairs.<br/><br/>
Click on the Apache Camel button to view documation on the valid options.`;
this.optionsPopoverMessage = ``;
this.headerPopoverMessage = `A group of key/value pairs to add to the message header.<br/><br/> Use the button on the right to create or edit a header.`;
this.routePopoverMessage = `A Camel route defined in XML.<br/><br/>`;
this.servicePopoverMessage = `If available then a service can be selected. For example a service that sets up a connection.<br/><br/>
Use the button on the right to create or edit services.`;
this.popoverMessage = `Destination`;
this.hostnamePopoverMessage = `URL, IP-address or DNS Name. For example camel.apache.org or 127.0.0.1`;
this.portPopoverMessage = `Number of the port. Range between 1 and 65536`;
this.timeoutPopoverMessage = `Timeout in seconds to wait for connection.`;
}
setURIlist(index) {
this.URIList[index] = [];
let tEndpointsUnique = this.allendpoints.filter((v, i, a) => a.findIndex(t => t.uri === v.uri) === i);
tEndpointsUnique.forEach((endpoint, i) => {
if (this.selectedComponentType === endpoint.componentType) {
this.URIList[index].push(endpoint);
}
});
}
enableFields(endpointForm) {
let componentHasService = this.servicesList.getServiceType(endpointForm.controls.componentType.value);
if (endpointForm.controls.componentType.value === 'WASTEBIN') {
endpointForm.controls.uri.disable();
endpointForm.controls.options.disable();
endpointForm.controls.header.disable();
endpointForm.controls.route.disable();
endpointForm.controls.service.disable();
} else if (endpointForm.controls.componentType.value === 'WASTEBIN') {
endpointForm.controls.uri.enable();
endpointForm.controls.options.enable();
endpointForm.controls.header.enable();
endpointForm.controls.route.enable();
if (this.embeddedBroker) {
endpointForm.controls.service.disable();
} else {
endpointForm.controls.service.enable();
}
} else if (componentHasService) {
endpointForm.controls.uri.enable();
endpointForm.controls.options.enable();
endpointForm.controls.header.enable();
endpointForm.controls.route.enable();
endpointForm.controls.service.enable();
} else {
endpointForm.controls.uri.enable();
endpointForm.controls.options.enable();
endpointForm.controls.header.enable();
endpointForm.controls.route.enable();
endpointForm.controls.service.disable();
}
}
initializeForm(flow: Flow) {
this.editFlowForm = new FormGroup({
id: new FormControl(flow.id),
name: new FormControl(flow.name, Validators.required),
notes: new FormControl(flow.notes),
autoStart: new FormControl(flow.autoStart),
assimblyHeaders: new FormControl(flow.assimblyHeaders),
offloading: new FormControl(flow.offLoading),
parallelProcessing: new FormControl(flow.parallelProcessing),
maximumRedeliveries: new FormControl(flow.maximumRedeliveries),
redeliveryDelay: new FormControl(flow.redeliveryDelay),
logLevel: new FormControl(flow.logLevel),
gateway: new FormControl(flow.gatewayId),
endpointsData: new FormArray([])
});
}
initializeEndpointData(endpoint: Endpoint): FormGroup {
return new FormGroup({
id: new FormControl(endpoint.id),
componentType: new FormControl(endpoint.componentType, Validators.required),
uri: new FormControl(endpoint.uri),
options: new FormArray([this.initializeOption()]),
header: new FormControl(endpoint.headerId),
route: new FormControl(endpoint.routeId),
service: new FormControl(endpoint.serviceId, Validators.required)
});
}
initializeOption(): FormGroup {
return new FormGroup({
key: new FormControl(null),
value: new FormControl(null),
defaultValue: new FormControl('')
});
}
initializeTestConnectionForm() {
this.testConnectionForm = new FormGroup({
connectionHost: new FormControl(null, Validators.required),
connectionPort: new FormControl(80),
connectionTimeout: new FormControl(10)
});
}
updateForm() {
this.updateFlowData(this.flow);
let endpointsData = this.editFlowForm.controls.endpointsData as FormArray;
this.endpoints.forEach((endpoint, i) => {
this.updateEndpointData(endpoint, endpointsData.controls[i] as FormControl);
});
}
updateFlowData(flow: Flow) {
this.editFlowForm.patchValue({
id: flow.id,
name: flow.name,
notes: flow.notes,
autoStart: flow.autoStart,
assimblyHeaders: flow.assimblyHeaders,
offloading: flow.offLoading,
parallelProcessing: flow.parallelProcessing,
maximumRedeliveries: flow.maximumRedeliveries,
redeliveryDelay: flow.redeliveryDelay,
logLevel: flow.logLevel,
gateway: flow.gatewayId
});
}
updateEndpointData(endpoint: any, endpointData: FormControl) {
endpointData.patchValue({
id: endpoint.id,
endpointType: endpoint.endpointType,
componentType: endpoint.componentType,
uri: endpoint.uri,
header: endpoint.headerId,
route: endpoint.routeId,
service: endpoint.serviceId,
responseId: endpoint.responseId
});
}
setComponentOptions(endpoint: Endpoint, componentType: string): Observable<any> {
return from(
new Promise((resolve, reject) => {
setTimeout(() => {
this.getComponentOptions(componentType).subscribe(data => {
let componentOptions = data.properties;
this.componentOptions[this.endpoints.indexOf(endpoint)] = Object.keys(componentOptions).map(key => ({
...componentOptions[key],
...{ name: key }
}));
this.componentOptions[this.endpoints.indexOf(endpoint)].sort(function(a, b) {
return a.displayName.toLowerCase().localeCompare(b.displayName.toLowerCase());
});
resolve();
});
}, 10);
})
);
}
getComponentOptions(componentType: String): any {
return this.flowService.getComponentOptions(1, componentType).pipe(
map(options => {
return options.body;
})
);
}
getOptions(endpoint: Endpoint, endpointForm: any, endpointOptions: Array<Option>, index: number) {
let optionArray: Array<string> = [];
if (!endpoint.options) {
endpoint.options = '';
}
let componentType = endpoint.componentType.toString().toLowerCase();
let camelComponentType = this.components.getCamelComponentType(componentType);
this.setComponentOptions(endpoint, camelComponentType).subscribe(data => {
const options = endpoint.options.split('&');
options.forEach((option, optionIndex) => {
const o = new Option();
if (typeof endpointForm.controls.options.controls[optionIndex] === 'undefined') {
endpointForm.controls.options.push(this.initializeOption());
}
if (option.includes('=')) {
o.key = option.split('=')[0];
o.value = option
.split('=')
.slice(1)
.join('=');
} else {
o.key = null;
o.value = null;
}
optionArray.splice(optionIndex, 0, o.key);
endpointForm.controls.options.controls[optionIndex].patchValue({
key: o.key,
value: o.value
});
if (this.componentOptions[index]) {
const optionNameExist = this.componentOptions[index].some(el => el.name === o.key);
if (!optionNameExist && o.key) {
this.componentOptions[index].push({
name: o.key,
displayName: o.key,
description: 'Custom option',
group: 'custom',
type: 'string',
componentType: camelComponentType
});
this.customOptions.push({
name: o.key,
displayName: o.key,
description: 'Custom option',
group: 'custom',
type: 'string',
componentType: camelComponentType
});
}
}
endpointOptions.push(o);
});
});
this.selectedOptions.splice(index, 0, optionArray);
}
setOptions() {
this.endpoints.forEach((endpoint, i) => {
endpoint.options = '';
this.setEndpointOptions(this.endpointsOptions[i], endpoint, this.selectOptions(i));
});
}
setEndpointOptions(endpointOptions: Array<Option>, endpoint, formOptions: FormArray) {
let index = 0;
endpointOptions.forEach((option, i) => {
option.key = (<FormGroup>formOptions.controls[i]).controls.key.value;
option.value = (<FormGroup>formOptions.controls[i]).controls.value.value;
if (option.key && option.value) {
endpoint.options += index > 0 ? `&${option.key}=${option.value}` : `${option.key}=${option.value}`;
index++;
}
});
}
addOption(options: Array<Option>, endpointIndex) {
this.selectOptions(endpointIndex).push(this.initializeOption());
options.push(new Option());
}
removeOption(options: Array<Option>, option: Option, endpointIndex) {
const optionIndex = options.indexOf(option);
let formOptions: FormArray = this.selectOptions(endpointIndex);
//remove from form
formOptions.removeAt(optionIndex);
formOptions.updateValueAndValidity();
//remove from arrays
options.splice(optionIndex, 1);
this.selectedOptions[endpointIndex].splice(optionIndex, 1);
}
selectOptions(endpointIndex): FormArray {
const endpointData = (<FormArray>this.editFlowForm.controls.endpointsData).controls[endpointIndex];
return <FormArray>(<FormGroup>endpointData).controls.options;
}
changeOptionSelection(selectedOption, index, optionIndex, endpoint) {
let defaultValue;
let componentOption = this.componentOptions[index].filter(option => option.name === selectedOption);
if (componentOption[0]) {
defaultValue = componentOption[0].defaultValue;
} else {
const customOption = new Option();
customOption.key = selectedOption;
let componentType = endpoint.componentType.toString().toLowerCase();
let camelComponentType = this.components.getCamelComponentType(componentType);
let optionArray: Array<string> = [];
optionArray.splice(optionIndex, 0, customOption.key);
console.log('add to custom options cameltype X=' + JSON.stringify(this.selectedOptions[index]));
this.componentOptions[index].push({
name: selectedOption,
displayName: selectedOption,
description: 'Custom option',
group: 'custom',
type: 'string',
componentType: camelComponentType
});
this.customOptions.push({
name: selectedOption,
displayName: selectedOption,
description: 'Custom option',
group: 'custom',
type: 'string',
componentType: camelComponentType
});
}
const endpointData = (<FormArray>this.editFlowForm.controls.endpointsData).controls[index];
const formOptions = <FormArray>(<FormGroup>endpointData).controls.options;
if (defaultValue) {
(<FormGroup>formOptions.controls[optionIndex]).controls.defaultValue.patchValue('Default Value: ' + defaultValue);
} else {
(<FormGroup>formOptions.controls[optionIndex]).controls.defaultValue.patchValue('');
}
}
addOptionTag(name) {
return { name: name, displayName: name, description: 'Custom option', group: 'custom', type: 'string', componentType: 'file' };
}
addEndpoint(endpoint, index) {
let newIndex = index + 1;
if (endpoint.responseId != undefined) {
newIndex += 1;
}
this.endpoints.splice(newIndex, 0, new Endpoint());
this.endpointsOptions.splice(newIndex, 0, [new Option()]);
if (endpoint.endpointType === 'FROM') {
this.numberOfFromEndpoints = this.numberOfFromEndpoints + 1;
} else if (endpoint.endpointType === 'TO') {
this.numberOfToEndpoints = this.numberOfToEndpoints + 1;
}
const newEndpoint = this.endpoints.find((e, i) => i === newIndex);
newEndpoint.endpointType = endpoint.endpointType;
newEndpoint.componentType = ComponentType[this.gateways[this.indexGateway].defaultToComponentType];
(<FormArray>this.editFlowForm.controls.endpointsData).insert(newIndex, this.initializeEndpointData(newEndpoint));
this.setTypeLinks(endpoint, newIndex);
let optionArray: Array<string> = [];
optionArray.splice(0, 0, '');
this.selectedOptions.splice(newIndex, 0, optionArray);
this.active = newIndex.toString();
}
removeEndpoint(endpoint, endpointDataName) {
if (endpoint.endpointType === 'FROM') {
this.numberOfFromEndpoints = this.numberOfFromEndpoints - 1;
} else if (endpoint.endpointType === 'TO') {
this.numberOfToEndpoints = this.numberOfToEndpoints - 1;
if (endpoint.responseId != undefined) {
this.removeResponseEndpoint(endpoint);
}
}
const i = this.endpoints.indexOf(endpoint);
this.endpoints.splice(i, 1);
this.endpointsOptions.splice(i, 1);
this.editFlowForm.removeControl(endpointDataName); //'endpointData'+index
(<FormArray>this.editFlowForm.controls.endpointsData).removeAt(i);
}
addResponseEndpoint(endpoint) {
this.numberOfResponseEndpoints = this.numberOfResponseEndpoints + 1;
let toIndex = this.endpoints.indexOf(endpoint);
let responseIndex = toIndex + 1;
this.endpoints.splice(responseIndex, 0, new Endpoint());
this.endpointsOptions.splice(responseIndex, 0, [new Option()]);
const newEndpoint = this.endpoints.find((e, i) => i === responseIndex);
newEndpoint.endpointType = EndpointType.RESPONSE;
newEndpoint.componentType = ComponentType[this.gateways[this.indexGateway].defaultToComponentType];
(<FormArray>this.editFlowForm.controls.endpointsData).insert(responseIndex, this.initializeEndpointData(newEndpoint));
this.setTypeLinks(newEndpoint, responseIndex);
const newIndex = responseIndex;
//dummy id's for endpoints
endpoint.id = toIndex;
newEndpoint.id = responseIndex;
endpoint.responseId = this.numberOfResponseEndpoints;
newEndpoint.responseId = endpoint.responseId;
this.active = newIndex.toString();
}
removeResponseEndpoint(endpoint) {
let responseIndex: any;
responseIndex = endpoint.responseId != undefined ? this.endpoints.indexOf(endpoint) + 1 : undefined;
// Find the index of the response endpoint belonging to the to endpoint
if (responseIndex != undefined) {
this.numberOfResponseEndpoints = this.numberOfResponseEndpoints - 1;
endpoint.responseId = undefined;
this.endpoints.splice(responseIndex, 1);
this.endpointsOptions.splice(responseIndex, 1);
this.editFlowForm.removeControl('endpointData' + responseIndex);
(<FormArray>this.editFlowForm.controls.endpointsData).removeAt(responseIndex);
}
}
openModal(templateRef: TemplateRef<any>) {
this.modalRef = this.modalService.open(templateRef);
}
openTestConnectionModal(templateRef: TemplateRef<any>) {
this.initializeTestConnectionForm();
this.testConnectionMessage = '';
this.modalRef = this.modalService.open(templateRef);
}
cancelModal(): void {
if (this.modalRef) {
this.modalRef.dismiss();
this.modalRef = null;
}
}
testConnection() {
this.testConnectionMessage = '<i class="fa fa-refresh fa-spin fa-fw"></i><span class="sr-only"></span>Testing...';
this.connectionHost = <FormGroup>this.testConnectionForm.controls.connectionHost.value;
this.connectionPort = <FormGroup>this.testConnectionForm.controls.connectionPort.value;
this.connectionTimeout = <FormGroup>this.testConnectionForm.controls.connectionTimeout.value;
this.flowService
.testConnection(this.flow.gatewayId, this.connectionHost, this.connectionPort, this.connectionTimeout)
.subscribe(result => {
this.testConnectionMessage = result.body;
});
}
previousState() {
window.history.back();
}
ngOnDestroy() {
this.subscription.unsubscribe();
this.eventManager.destroy(this.eventSubscriber);
}
registerChangeInFlows() {
this.eventSubscriber = this.eventManager.subscribe('flowListModification', response => this.load(this.flow.id));
}
createOrEditHeader(endpoint, formHeader: FormControl) {
endpoint.headerId = formHeader.value;
if (typeof endpoint.headerId === 'undefined' || endpoint.headerId === null || !endpoint.headerId) {
let modalRef = this.headerPopupService.open(HeaderDialogComponent as Component);
modalRef.then(res => {
res.result.then(
result => {
this.setHeader(endpoint, result.id, formHeader);
},
reason => {
this.setHeader(endpoint, reason.id, formHeader);
}
);
});
} else {
const modalRef = this.headerPopupService.open(HeaderDialogComponent as Component, endpoint.headerId);
modalRef.then(res => {
// Success
res.result.then(
result => {
this.setHeader(endpoint, result.id, formHeader);
},
reason => {
this.setHeader(endpoint, reason.id, formHeader);
}
);
});
}
}
createOrEditRoute(endpoint, formRoute: FormControl) {
endpoint.routeId = formRoute.value;
if (typeof endpoint.routeId === 'undefined' || endpoint.routeId === null || !endpoint.routeId) {
let modalRef = this.routePopupService.open(RouteDialogComponent as Component);
modalRef.then(res => {
res.result.then(
result => {
this.setRoute(endpoint, result.id, formRoute);
},
reason => {
this.setRoute(endpoint, reason.id, formRoute);
}
);
});
} else {
const modalRef = this.routePopupService.open(RouteDialogComponent as Component, endpoint.routeId);
modalRef.then(res => {
// Success
res.result.then(
result => {
this.setRoute(endpoint, result.id, formRoute);
},
reason => {
this.setRoute(endpoint, reason.id, formRoute);
}
);
});
}
}
createOrEditService(endpoint, serviceType: string, formService: FormControl) {
endpoint.serviceId = formService.value;
if (typeof endpoint.serviceId === 'undefined' || endpoint.serviceId === null || !endpoint.serviceId) {
const modalRef = this.servicePopupService.open(ServiceDialogComponent as Component);
modalRef.then(res => {
// Success
res.componentInstance.serviceType = serviceType;
res.result.then(
result => {
this.setService(endpoint, result.id, formService);
},
reason => {
this.setService(endpoint, reason.id, formService);
}
);
});
} else {
const modalRef = this.servicePopupService.open(ServiceDialogComponent as Component, endpoint.serviceId);
modalRef.then(res => {
res.componentInstance.serviceType = serviceType;
res.result.then(
result => {
this.setService(endpoint, result.id, formService);
},
reason => {
//this.setService(endpoint, reason.id, formService);
}
);
});
}
}
setHeader(endpoint, id, formHeader: FormControl) {
this.headerService.getAllHeaders().subscribe(
res => {
this.headers = res.body;
this.headerCreated = this.headers.length > 0;
endpoint.headerId = id;
if (formHeader.value === null) {
formHeader.patchValue(id);
}
endpoint = null;
},
res => this.onError(res.body)
);
}
setRoute(endpoint, id, formRoute: FormControl) {
this.routeService.getAllRoutes().subscribe(
res => {
this.routes = res.body;
this.routeCreated = this.routes.length > 0;
endpoint.routeId = id;
if (formRoute.value === null) {
formRoute.patchValue(id);
}
endpoint = null;
},
res => this.onError(res.body)
);
}
setService(endpoint, id, formService: FormControl) {
this.serviceService.getAllServices().subscribe(
res => {
this.services = res.body;
this.serviceCreated = this.services.length > 0;
endpoint.serviceId = id;
formService.patchValue(id);
this.filterServices(endpoint, formService);
},
res => this.onError(res.body)
);
}
handleErrorWhileCreatingFlow(flowId?: number, endpointId?: number) {
if (flowId !== null) {
this.flowService.delete(flowId);
}
if (endpointId !== null) {
this.endpointService.delete(endpointId);
}
this.savingFlowFailed = true;
this.isSaving = false;
}
export(flow: IFlow) {
this.flowService.exportFlowConfiguration(flow);
}
save() {
this.setDataFromForm();
this.setOptions();
this.setVersion();
this.savingFlowFailed = false;
this.savingFlowSuccess = false;
let goToOverview = true;
if (!this.editFlowForm.valid) {
return;
}
if (this.checkUniqueEndpoints()) {
return;
}
if (!!this.flow.id) {
this.endpoints.forEach(endpoint => {
endpoint.flowId = this.flow.id;
});
this.flowService.update(this.flow).subscribe(flow => {
this.flow = flow.body;
const updateEndpoints = this.endpointService.updateMultiple(this.endpoints);
updateEndpoints.subscribe(results => {
this.endpoints = results.body.concat();
if (!goToOverview) {
this.updateForm();
}
this.endpointService.findByFlowId(this.flow.id).subscribe(data => {
let endpoints = data.body;
endpoints = endpoints.filter(e => {
const s = this.endpoints.find(t => t.id === e.id);
if (typeof s === 'undefined') {
return true;
} else {
return s.id !== e.id;
}
});
if (endpoints.length > 0) {
endpoints.forEach(element => {
this.endpointService.delete(element.id).subscribe(
r => {
const y = r;
},
err => {
const e = err;
}
);
});
}
});
this.savingFlowSuccess = true;
this.isSaving = false;
if (goToOverview) {
this.router.navigate(['/']);
}
});
});
} else {
if (this.singleGateway) {
this.flow.gatewayId = this.gateways[0].id;
}
this.flowService.create(this.flow).subscribe(
flowUpdated => {
this.flow = flowUpdated.body;
this.endpoints.forEach(endpoint => {
endpoint.flowId = this.flow.id;
});
this.endpointService.createMultiple(this.endpoints).subscribe(
toRes => {
this.endpoints = toRes.body;
this.updateForm();
this.finished = true;
this.savingFlowSuccess = true;
this.isSaving = false;
if (goToOverview) {
this.router.navigate(['/']);
}
},
() => {
this.handleErrorWhileCreatingFlow(this.flow.id, this.endpoint.id);
}
);
},
() => {
this.handleErrorWhileCreatingFlow(this.flow.id, this.endpoint.id);
}
);
}
}
checkUniqueEndpoints() {
if (this.savingCheckEndpoints) {
this.savingCheckEndpoints = false;
const uniqueEndpoints = [...new Map(this.endpoints.map(item => [item['uri'], item])).values()];
if (this.endpoints.length !== uniqueEndpoints.length) {
this.notUniqueUriMessage = `Endpoint Uri's are not unique (check for possible loops).`;
return true;
}
}
return false;
}
setDataFromForm() {
const flowControls = this.editFlowForm.controls;
flowControls.name.markAsTouched();
flowControls.name.updateValueAndValidity();
this.flow.id = flowControls.id.value;
this.flow.name = flowControls.name.value;
this.flow.notes = flowControls.notes.value;
this.flow.autoStart = flowControls.autoStart.value;
this.flow.assimblyHeaders = flowControls.assimblyHeaders.value;
this.flow.offLoading = flowControls.offloading.value;
this.flow.parallelProcessing = flowControls.parallelProcessing.value;
this.flow.maximumRedeliveries = flowControls.maximumRedeliveries.value;
this.flow.redeliveryDelay = flowControls.redeliveryDelay.value;
this.flow.logLevel = flowControls.logLevel.value;
this.flow.gatewayId = flowControls.gateway.value;
(<FormArray>flowControls.endpointsData).controls.forEach((endpoint, index) => {
this.setDataFromFormOnEndpoint(this.endpoints[index], (<FormGroup>endpoint).controls);
});
}
setDataFromFormOnEndpoint(endpoint, formEndpointData) {
formEndpointData.uri.setValidators([Validators.required]);
formEndpointData.uri.updateValueAndValidity();
endpoint.id = formEndpointData.id.value;
endpoint.componentType = formEndpointData.componentType.value;
endpoint.uri = formEndpointData.uri.value;
endpoint.headerId = formEndpointData.header.value;
endpoint.routeId = formEndpointData.route.value;
endpoint.serviceId = formEndpointData.service.value;
}
setVersion() {
let now = moment();
if (this.flow.id) {
this.flow.version = this.flow.version + 1;
this.flow.lastModified = now;
} else {
this.flow.version = 1;
this.flow.created = now;
this.flow.lastModified = now;
}
}
//Get currrent scroll position
findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while ((obj = obj.offsetParent));
return curtop;
}
}
goBack() {
window.history.back();
}
setInvalidUriMessage(endpointName: string) {
this.invalidUriMessage = `Uri for ${endpointName} is not valid.`;
setTimeout(() => {
this.invalidUriMessage = '';
}, 15000);
}
formatUri(endpointOptions, endpoint, formEndpoint): string {
if (formEndpoint.controls.componentType.value === null) {
return;
}
let formOptions = <FormArray>formEndpoint.controls.options;
this.setEndpointOptions(endpointOptions, endpoint, formOptions);
return `${formEndpoint.controls.componentType.value.toLowerCase()}://${formEndpoint.controls.uri.value}${
!endpoint.options ? '' : endpoint.options
}`;
}
validateTypeAndUri(endpoint: FormGroup) {
endpoint.controls.componentType.markAsTouched();
endpoint.controls.uri.markAsTouched();
}
markAsUntouchedTypeAndUri(endpoint: FormGroup) {
endpoint.controls.componentType.markAsUntouched();
endpoint.controls.uri.markAsUntouched();
}
private subscribeToSaveResponse(result: Observable<Flow>) {
result.subscribe(
(res: Flow) => this.onSaveSuccess(res),
(res: Response) => this.onSaveError()
);
}
private onSaveSuccess(result: Flow) {
this.eventManager.broadcast({ name: 'flowListModification', content: 'OK' });
this.isSaving = false;
}
private onSaveError() {
this.isSaving = false;
}
private onError(error) {
this.jhiAlertService.error(error.message, null, null);
}
private decycle(obj, stack = []) {
if (!obj || typeof obj !== 'object') return obj;
if (stack.includes(obj)) return null;
let s = stack.concat([obj]);
return Array.isArray(obj)
? obj.map(x => this.decycle(x, s))
: Object.entries(Object.entries(obj).map(([k, v]) => [k, this.decycle(v, s)]));
}
}
export class Option {
constructor(public key?: string, public value?: string) {}
}
export class TypeLinks {
constructor(public name: string, public assimblyTypeLink: string, public camelTypeLink: string) {}
} | the_stack |
import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { expressionLanguageConfiguration, expressionLanguageMonarch } from './expression-language/expression-language.monarch';
import { ModelingTypesService } from './modeling-types.service';
@Injectable({
providedIn: 'root'
})
export class ExpressionsEditorService {
static wordRegex = /((\w+((\.?\w+){0,1}(\[\S+\]){0,1}(\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)){0,1})*)|\W)/g;
static wordRegexSignature = /\w+((\.?\w+){0,1}(\[\S+\]){0,1}(\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)){0,1})*/g;
private typeTranslation: string;
constructor(private translateService: TranslateService, private modelingTypesService: ModelingTypesService) {
this.typeTranslation = this.translateService.instant('SDK.VARIABLES_EDITOR.TABLE.COLUMN_TYPE');
}
static getTypeName(
model: monaco.editor.ITextModel,
position: monaco.Position,
parameters: any[],
modelingTypesService: ModelingTypesService,
offset = 0
): string {
const lineBeforeCursor = model.getValueInRange({
startLineNumber: position.lineNumber,
startColumn: 0,
endLineNumber: position.lineNumber,
endColumn: position.column
});
const words = lineBeforeCursor.match(ExpressionsEditorService.wordRegex);
let typeName: string = null;
if (words) {
const activeTyping = words[words.length - 1 - offset];
typeName = ExpressionsEditorService.getTypeNameOfWord(activeTyping, parameters, modelingTypesService, offset);
}
return typeName;
}
static getTypeNameOfWord(word: string, parameters: any[], modelingTypesService: ModelingTypesService, offset = 0): string {
const parts = word?.split('.') || [];
let typeName: string = null;
for (let index = 0; index < (parts.length - 1 + offset); index++) {
const element = parts[index];
if (element.trim().length > 0) {
const array = element.match(/([a-z][\w]*)\[(\S)*\]/);
const method = element.match(/([a-z][\w]*)\((\S|\s)*\)/);
const arrayAfterMethod = element.match(/([a-z][\w]*)\((\S|\s)*\)\[(\S)*\]/);
if (array) {
if (!typeName) {
typeName = parameters.find(parameter => parameter.name === array[1])?.type;
typeName = modelingTypesService.getType(typeName)?.collectionOf || 'json';
} else {
typeName = modelingTypesService.getType(typeName)?.collectionOf || 'json';
}
} else if (typeName && arrayAfterMethod) {
typeName = modelingTypesService.getType(typeName).methods?.filter(registeredMethod => !!registeredMethod)
.find(registeredMethod => registeredMethod.signature.startsWith(arrayAfterMethod[1]))?.type;
typeName = modelingTypesService.getType(typeName)?.collectionOf || 'json';
} else if (typeName && method) {
typeName = modelingTypesService.getType(typeName).methods?.filter(registeredMethod => !!registeredMethod)
.find(registeredMethod => registeredMethod.signature.startsWith(method[1]))?.type;
} else {
if (!typeName) {
typeName = parameters.find(parameter => parameter.name === element)?.type;
} else {
typeName = modelingTypesService.getType(typeName).properties?.filter(property => !!property)
.find(property => property.property === element)?.type;
}
}
}
if (!typeName) {
break;
}
}
return typeName;
}
static getActiveParameter(model: monaco.editor.ITextModel, position: monaco.Position): number {
const lineBeforeCursor = model.getValueInRange({
startLineNumber: position.lineNumber,
startColumn: 0,
endLineNumber: position.lineNumber,
endColumn: position.column
});
const words = lineBeforeCursor.replace('\t', '').split(' ');
const activeTyping = words[words.length - 1];
return (activeTyping.match(/\,(?=([^"\\]*(\\.|"([^"\\]*\\.)*[^"\\]*"))*[^"]*$)/g) || []).length;
}
static getHoverCard(typeName: string, word: string, range: any, typeTranslation: string, modelingTypesService: ModelingTypesService): any {
let hoverCard;
if (typeName) {
const methodHover = modelingTypesService.getType(typeName).methods?.
filter(method => !!method).find(method => method.signature === word);
const propertyHover = modelingTypesService.getType(typeName).properties?.
filter(property => !!property).find(property => property.property === word);
if (methodHover) {
hoverCard = {
range,
contents: [{ value: `*${methodHover.signature}*` }]
};
if (methodHover.documentation) {
hoverCard.contents.push({ value: methodHover.documentation });
}
hoverCard.contents.push({ value: typeTranslation + ': ' + methodHover.type });
} else if (propertyHover) {
hoverCard = {
range,
contents: [{ value: `*${propertyHover.property}*` }]
};
if (propertyHover.documentation) {
hoverCard.contents.push({ value: propertyHover.documentation });
}
hoverCard.contents.push({ value: typeTranslation + ': ' + propertyHover.type });
}
}
return hoverCard;
}
/**
* Initializes the monaco editor language for an instance of an expression editor identified by the language
* @arg language - the identifier of the language. Each expression editor must have a different language as it includes the autocompletion for the available variables there
* @arg parameters - the variables that can be used inside the expressions
* @arg hostLanguage - the language of the editor. For example if host language is 'text/html' the editor will colourize everything as html,
* except the ${...} content that will be colourized as an expression (and will have the autocompletion). **By default this is null**
* @arg highlightAllText - If there is no **hostLanguage**, then we can tell the language to colorize only the text inside ${...} (*by default*)
* or all the text (by setting this to ***true***)
*/
initExpressionEditor(language: string, parameters: any[], hostLanguage: string = null, highlightAllText = false) {
const languages = monaco.languages.getLanguages();
if (languages.findIndex(lang => lang.id === language) < 0) {
monaco.languages.register({ id: language });
monaco.languages.setMonarchTokensProvider(language, this.getMonarchLanguageDefinition(parameters, hostLanguage, highlightAllText));
monaco.languages.setLanguageConfiguration(language, expressionLanguageConfiguration as monaco.languages.LanguageConfiguration);
this.registerCompletionProviderForKeywords(language);
this.registerCompletionProviderForMethodsAndProperties(language, this.modelingTypesService, parameters);
this.registerSignatureProviderForMethods(language, this.modelingTypesService, parameters);
this.registerHoverProviderForMethodsAndProperties(language, this.modelingTypesService, parameters, this.typeTranslation);
}
if (parameters) {
this.registerCompletionProviderForVariables(language, parameters);
this.registerHoverProviderForVariables(language, parameters, this.typeTranslation);
}
}
colorizeElement(element: HTMLElement, options?: monaco.editor.IColorizerElementOptions) {
monaco.editor.colorizeElement(element, options || {});
}
private registerCompletionProviderForKeywords(language: string) {
monaco.languages.registerCompletionItemProvider(language, {
provideCompletionItems: (model, position) => {
const word = model.getWordAtPosition(position) || model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const suggestions = [];
if (word.startColumn === 1 || model.getLineContent(position.lineNumber).substr(position.column - 2, 1) === '.') {
expressionLanguageMonarch.keywords.forEach(keyword => {
suggestions.push({
label: keyword,
insertText: keyword,
kind: monaco.languages.CompletionItemKind.Keyword,
range: range,
});
});
}
return { suggestions };
}
});
}
private registerCompletionProviderForVariables(language: string, parameters: any[]) {
monaco.languages.registerCompletionItemProvider(language, {
provideCompletionItems: (model, position) => {
const word = model.getWordAtPosition(position) || model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const suggestions = [];
if (word.startColumn === 1 || model.getLineContent(position.lineNumber).substr(position.column - 2, 1) !== '.') {
parameters.forEach(parameter => {
suggestions.push({
label: parameter.name,
detail: parameter.type,
kind: monaco.languages.CompletionItemKind.Variable,
insertText: parameter.name,
documentation: parameter.markup || parameter.description,
range: range,
});
});
}
return { suggestions };
}
});
}
private registerCompletionProviderForMethodsAndProperties(language: string, modelingTypesService: ModelingTypesService, parameters: any[]) {
monaco.languages.registerCompletionItemProvider(language, {
triggerCharacters: ['.'],
provideCompletionItems: (model, position) => {
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
let suggestions = [];
const offset = word.word.length === 0 ? 1 : 0;
const typeName: string = ExpressionsEditorService.getTypeName(model, position, parameters, modelingTypesService, offset);
if (typeName) {
suggestions = suggestions.concat(modelingTypesService.getMethodsSuggestionsByType(typeName));
suggestions = suggestions.concat(modelingTypesService.getPropertiesSuggestionsByType(typeName));
}
suggestions.map(suggestion => suggestion.range = range);
return { suggestions };
}
});
}
private registerSignatureProviderForMethods(language: string, modelingTypesService: ModelingTypesService, parameters: any[]) {
monaco.languages.registerSignatureHelpProvider(language, {
signatureHelpTriggerCharacters: ['(', ','],
signatureHelpRetriggerCharacters: [],
provideSignatureHelp: (model, position, token) => {
const word = model.getWordUntilPosition(position);
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
let signatures = [];
const activeParameter = ExpressionsEditorService.getActiveParameter(model, position);
let activeSignature = 0;
const lineBeforeCursor = model.getValueInRange({
startLineNumber: position.lineNumber,
startColumn: 0,
endLineNumber: position.lineNumber,
endColumn: position.column
});
const words = lineBeforeCursor.match(ExpressionsEditorService.wordRegexSignature);
if (words) {
const offset = word.word.length > 0 ? activeParameter + 1 : activeParameter;
const activeTyping = words[words.length - 1 - offset];
const typeName: string = ExpressionsEditorService.getTypeNameOfWord(activeTyping, parameters, modelingTypesService);
if (typeName) {
const parts = activeTyping.split('.');
const activeMethodSignature = parts[parts.length - 1];
signatures = modelingTypesService.getSignatureHelperByType(typeName)
.filter(signature => signature.method.signature.startsWith(activeMethodSignature));
activeSignature = signatures.findIndex(signature => signature.parameters?.length > activeParameter) || 0;
}
}
signatures.map(signature => signature.range = range);
return {
activeParameter,
activeSignature,
signatures
};
}
});
}
private registerHoverProviderForVariables(language: string, parameters: any[], typeTranslation: string) {
monaco.languages.registerHoverProvider(language, {
provideHover: function (model, position) {
const word = model.getWordAtPosition(position);
let hoverCard;
if (word) {
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const variableName = word.word;
const variable = parameters?.find(parameter => parameter.name === variableName);
if (variable) {
hoverCard = {
range,
contents: [{ value: `*${variable.name}*` }]
};
if (variable.markdown) {
hoverCard.contents.push({ value: variable.markdown });
} else {
if (variable.description) {
hoverCard.contents.push({ value: variable.description });
}
hoverCard.contents.push({ value: typeTranslation + ': ' + variable.type });
}
}
}
return hoverCard;
}
});
}
private registerHoverProviderForMethodsAndProperties(
language: string,
modelingTypesService: ModelingTypesService,
parameters: any[],
typeTranslation: string
) {
monaco.languages.registerHoverProvider(language, {
provideHover: function (model, position) {
const word = model.getWordAtPosition(position);
let hoverCard;
if (word) {
const range = {
startLineNumber: position.lineNumber,
endLineNumber: position.lineNumber,
startColumn: word.startColumn,
endColumn: word.endColumn
};
const typeName: string = ExpressionsEditorService.getTypeName(model, position, parameters, modelingTypesService);
hoverCard = ExpressionsEditorService.getHoverCard(typeName, word.word, range, typeTranslation, modelingTypesService);
}
return hoverCard;
}
});
}
private getMonarchLanguageDefinition(parameters: any, hostLanguage: string, highlightAllText: boolean): monaco.languages.IMonarchLanguage {
const languageDef = { ...expressionLanguageMonarch, variables: [], defaultToken: '' };
parameters?.forEach(parameter => {
languageDef.variables.push(parameter.name);
});
if (hostLanguage) {
languageDef.defaultToken = 'string';
languageDef.tokenizer.root = [[/[\s|\S]/, { token: '@rematch', next: '@hostLanguage', nextEmbedded: hostLanguage }]];
languageDef.tokenizer.hostLanguage = [
[/"(\s)*\$\{/, { token: '@rematch', next: '@expLanguageInDoubleQuoteString', nextEmbedded: '@pop', bracket: '@open' }],
[/'(\s)*\$\{/, { token: '@rematch', next: '@expLanguageInSingleQuoteString', nextEmbedded: '@pop', bracket: '@open' }],
[/\$\{/, { token: 'expLang', next: '@expLanguageCounting', nextEmbedded: '@pop', bracket: '@open' }],
[/[\s|\S]/, { token: '', next: '@hostLanguage', nextEmbedded: hostLanguage, bracket: undefined }]
];
} else {
if (highlightAllText) {
languageDef.tokenizer.root = [{ include: 'common' }];
} else {
languageDef.tokenizer.root = [{ include: 'expLanguageStart' }];
}
}
return languageDef as monaco.languages.IMonarchLanguage;
}
} | the_stack |
module android.widget {
import Context = android.content.Context;
import Resources = android.content.res.Resources;
import PixelFormat = android.graphics.PixelFormat;
import Handler = android.os.Handler;
import Log = android.util.Log;
import Gravity = android.view.Gravity;
import LayoutInflater = android.view.LayoutInflater;
import View = android.view.View;
import OnClickListener = android.view.View.OnClickListener;
import WindowManager = android.view.WindowManager;
import Window = android.view.Window;
import TextView = android.widget.TextView;
import Runnable = java.lang.Runnable;
/**
* A toast is a view containing a quick little message for the user. The toast class
* helps you create and show those.
* {@more}
*
* <p>
* When the view is shown to the user, appears as a floating view over the
* application. It will never receive focus. The user will probably be in the
* middle of typing something else. The idea is to be as unobtrusive as
* possible, while still showing the user the information you want them to see.
* Two examples are the volume control, and the brief message saying that your
* settings have been saved.
* <p>
* The easiest way to use this class is to call one of the static methods that constructs
* everything you need and returns a new Toast object.
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about creating Toast notifications, read the
* <a href="{@docRoot}guide/topics/ui/notifiers/toasts.html">Toast Notifications</a> developer
* guide.</p>
* </div>
*/
export class Toast {
static TAG:string = "Toast";
static localLOGV:boolean = false;
/**
* Show the view or text notification for a short period of time. This time
* could be user-definable. This is the default.
* @see #setDuration
*/
static LENGTH_SHORT:number = 0;
/**
* Show the view or text notification for a long period of time. This time
* could be user-definable.
* @see #setDuration
*/
static LENGTH_LONG:number = 1;
mContext:Context;
mTN:Toast.TN;
mDuration:number = 0;
mNextView:View;
private mHandler = new Handler();
private mDelayHide:Runnable = (()=> {
const inner_this = this;
return {
run() {
inner_this.mTN.hide();
}
}
})();
/**
* Construct an empty Toast object. You must call {@link #setView} before you
* can call {@link #show}.
*
* @param context The context to use. Usually your {@link android.app.Application}
* or {@link android.app.Activity} object.
*/
constructor(context:Context) {
this.mContext = context;
this.mTN = new Toast.TN();
this.mTN.mY = context.getResources().getDisplayMetrics().density * 64;
this.mTN.mGravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
}
/**
* Show the view for the specified duration.
*/
show():void {
if (this.mNextView == null) {
throw Error(`new RuntimeException("setView must have been called")`);
}
let tn:Toast.TN = this.mTN;
tn.mNextView = this.mNextView;
tn.show();
this.mHandler.removeCallbacks(this.mDelayHide);
let showDuration = this.mDuration === Toast.LENGTH_LONG ? 3500 : (this.mDuration === Toast.LENGTH_SHORT ? 2000 : this.mDuration);
this.mHandler.postDelayed(this.mDelayHide, showDuration);
}
/**
* Close the view if it's showing, or don't show it if it isn't showing yet.
* You do not normally have to call this. Normally view will disappear on its own
* after the appropriate duration.
*/
cancel():void {
this.mTN.hide();
}
/**
* Set the view to show.
* @see #getView
*/
setView(view:View):void {
this.mNextView = view;
}
/**
* Return the view.
* @see #setView
*/
getView():View {
return this.mNextView;
}
/**
* Set how long to show the view for.
* @see #LENGTH_SHORT
* @see #LENGTH_LONG
*/
setDuration(duration:number):void {
this.mDuration = duration;
}
/**
* Return the duration.
* @see #setDuration
*/
getDuration():number {
return this.mDuration;
}
///**
// * Set the margins of the view.
// *
// * @param horizontalMargin The horizontal margin, in percentage of the
// * container width, between the container's edges and the
// * notification
// * @param verticalMargin The vertical margin, in percentage of the
// * container height, between the container's edges and the
// * notification
// */
//setMargin(horizontalMargin:number, verticalMargin:number):void {
// this.mTN.mHorizontalMargin = horizontalMargin;
// this.mTN.mVerticalMargin = verticalMargin;
//}
//
///**
// * Return the horizontal margin.
// */
//getHorizontalMargin():number {
// return this.mTN.mHorizontalMargin;
//}
//
///**
// * Return the vertical margin.
// */
//getVerticalMargin():number {
// return this.mTN.mVerticalMargin;
//}
/**
* Set the location at which the notification should appear on the screen.
* @see android.view.Gravity
* @see #getGravity
*/
setGravity(gravity:number, xOffset:number, yOffset:number):void {
this.mTN.mGravity = gravity;
this.mTN.mX = xOffset;
this.mTN.mY = yOffset;
}
/**
* Get the location at which the notification should appear on the screen.
* @see android.view.Gravity
* @see #getGravity
*/
getGravity():number {
return this.mTN.mGravity;
}
/**
* Return the X offset in pixels to apply to the gravity's location.
*/
getXOffset():number {
return this.mTN.mX;
}
/**
* Return the Y offset in pixels to apply to the gravity's location.
*/
getYOffset():number {
return this.mTN.mY;
}
/**
* Make a standard toast that just contains a text view.
*
* @param context The context to use. Usually your {@link android.app.Application}
* or {@link android.app.Activity} object.
* @param text The text to show. Can be formatted text.
* @param duration How long to display the message. Either {@link #LENGTH_SHORT} or
* {@link #LENGTH_LONG}
*
*/
static makeText(context:Context, text:string, duration:number):Toast {
let result:Toast = new Toast(context);
let inflate:LayoutInflater = context.getLayoutInflater();//<LayoutInflater> context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
let v:View = inflate.inflate(android.R.layout.transient_notification, null);
let tv:TextView = <TextView> v.findViewById(android.R.id.message);
tv.setMaxWidth(260 * context.getResources().getDisplayMetrics().density);
tv.setText(text);
result.mNextView = v;
result.mDuration = duration;
return result;
}
///**
// * Make a standard toast that just contains a text view with the text from a resource.
// *
// * @param context The context to use. Usually your {@link android.app.Application}
// * or {@link android.app.Activity} object.
// * @param resId The resource id of the string resource to use. Can be formatted text.
// * @param duration How long to display the message. Either {@link #LENGTH_SHORT} or
// * {@link #LENGTH_LONG}
// *
// * @throws Resources.NotFoundException if the resource can't be found.
// */
//static makeText(context:Context, resId:number, duration:number):Toast {
// return Toast.makeText(context, context.getResources().getText(resId), duration);
//}
///**
// * Update the text in a Toast that was previously created using one of the makeText() methods.
// * @param resId The new text for the Toast.
// */
//setText(resId:number):void {
// this.setText(this.mContext.getText(resId));
//}
/**
* Update the text in a Toast that was previously created using one of the makeText() methods.
* @param s The new text for the Toast.
*/
setText(s:string):void {
if (this.mNextView == null) {
throw Error(`new RuntimeException("This Toast was not created with Toast.makeText()")`);
}
let tv:TextView = <TextView> this.mNextView.findViewById(android.R.id.message);
if (tv == null) {
throw Error(`new RuntimeException("This Toast was not created with Toast.makeText()")`);
}
tv.setText(s);
}
}
export module Toast {
export class TN {
mShow:Runnable = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.handleShow();
}
}
return new _Inner();
})();
mHide:Runnable = (()=> {
const inner_this = this;
class _Inner implements Runnable {
run():void {
inner_this.handleHide();
// Don't do this in handleHide() because it is also invoked by handleShow()
inner_this.mNextView = null;
}
}
return new _Inner();
})();
//private mParams:WindowManager.LayoutParams = new WindowManager.LayoutParams();
mHandler:Handler = new Handler();
mGravity:number = 0;
mX:number = 0;
mY:number = 0;
//mHorizontalMargin:number = 0;
//
//mVerticalMargin:number = 0;
mView:View;
mWindow:Window;
mNextView:View;
mWM:WindowManager;
/**
* schedule handleShow into the right thread
*/
show():void {
if (Toast.localLOGV) Log.v(Toast.TAG, "SHOW: " + this);
this.mHandler.post(this.mShow);
}
/**
* schedule handleHide into the right thread
*/
hide():void {
if (Toast.localLOGV) Log.v(Toast.TAG, "HIDE: " + this);
this.mHandler.post(this.mHide);
}
handleShow():void {
if (Toast.localLOGV) Log.v(Toast.TAG, "HANDLE SHOW: " + this + " mView=" + this.mView + " mNextView=" + this.mNextView);
if (this.mView != this.mNextView) {
// remove the old view if necessary
this.handleHide();
this.mView = this.mNextView;
if (!this.mWindow) {
this.mWindow = new Window(this.mView.getContext().getApplicationContext());
const params:WindowManager.LayoutParams = this.mWindow.getAttributes();
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
//params.format = PixelFormat.TRANSLUCENT;
//params.windowAnimations = com.android.internal.R.style.Animation_Toast;
params.dimAmount = 0;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.leftMargin = params.rightMargin = 36 * this.mView.getContext().getResources().getDisplayMetrics().density;
params.flags =
//WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
this.mWindow.setFloating(true);
this.mWindow.setBackgroundColor(android.graphics.Color.TRANSPARENT);
this.mWindow.setWindowAnimations(android.R.anim.toast_enter, android.R.anim.toast_exit, null, null);
}
const params:WindowManager.LayoutParams = this.mWindow.getAttributes();
this.mWindow.setContentView(this.mView);
let context:Context = this.mView.getContext().getApplicationContext();
//if (context == null) {
// context = this.mView.getContext();
//}
this.mWM = context.getWindowManager();//<WindowManager> context.getSystemService(Context.WINDOW_SERVICE);
// We can resolve the Gravity here by using the Locale for getting
// the layout direction
//const config:Configuration = this.mView.getContext().getResources().getConfiguration();
const gravity:number = Gravity.getAbsoluteGravity(this.mGravity/*, config.getLayoutDirection()*/);
params.gravity = gravity;
//if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.FILL_HORIZONTAL) {
// this.mParams.horizontalWeight = 1.0;
//}
//if ((gravity & Gravity.VERTICAL_GRAVITY_MASK) == Gravity.FILL_VERTICAL) {
// this.mParams.verticalWeight = 1.0;
//}
params.x = this.mX;
params.y = this.mY;
//this.mParams.verticalMargin = this.mVerticalMargin;
//this.mParams.horizontalMargin = this.mHorizontalMargin;
if (this.mWindow.getDecorView().getParent() != null) {
if (Toast.localLOGV) Log.v(Toast.TAG, "REMOVE! " + this.mView + " in " + this);
this.mWM.removeWindow(this.mWindow);
}
if (Toast.localLOGV) Log.v(Toast.TAG, "ADD! " + this.mView + " in " + this);
this.mWM.addWindow(this.mWindow);
//this.trySendAccessibilityEvent();
}
}
//private trySendAccessibilityEvent():void {
// let accessibilityManager:AccessibilityManager = AccessibilityManager.getInstance(this.mView.getContext());
// if (!accessibilityManager.isEnabled()) {
// return;
// }
// // treat toasts as notifications since they are used to
// // announce a transient piece of information to the user
// let event:AccessibilityEvent = AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
// event.setClassName(this.getClass().getName());
// event.setPackageName(this.mView.getContext().getPackageName());
// this.mView.dispatchPopulateAccessibilityEvent(event);
// accessibilityManager.sendAccessibilityEvent(event);
//}
handleHide():void {
if (Toast.localLOGV)
Log.v(Toast.TAG, "HANDLE HIDE: " + this + " mView=" + this.mView);
if (this.mView != null) {
// the view isn't yet added, so let's try not to crash.
if (this.mView.getParent() != null) {
if (Toast.localLOGV) Log.v(Toast.TAG, "REMOVE! " + this.mView + " in " + this);
this.mWM.removeWindow(this.mWindow);
}
this.mView = null;
}
}
}
}
} | the_stack |
import { expect } from "chai";
import "mocha";
import {
checkForLeaks,
commonExportsFromInstance,
CommonTestExports,
createHeapSymbol,
createString,
getString,
IoEvent,
IoTest,
loadWasm,
} from "./common";
interface TestExports extends CommonTestExports {
memory: WebAssembly.Memory;
gHeap: () => number;
gTrue: () => number;
gFalse: () => number;
environmentInit: (heap: number, outer: number) => number;
stringToNumberImpl: (str: number, radius: number) => number;
shortStrEq: (str: number, shortStr: number, shortStrLen: number) => number;
atom: (token: number) => number;
stringToDatum: (str: number) => number;
read: () => number;
eval: (env: number, expr: number) => number;
registerBuiltins: (heap: number, env: number) => void;
print: (ptr: number) => void;
}
function exportsFromInstance(instance: WebAssembly.Instance): TestExports {
return {
...commonExportsFromInstance(instance),
memory: instance.exports.memory as WebAssembly.Memory,
gHeap: () => (instance.exports.gHeap as WebAssembly.Global).value as number,
gTrue: () => (instance.exports.gTrue as WebAssembly.Global).value as number,
gFalse: () =>
(instance.exports.gFalse as WebAssembly.Global).value as number,
environmentInit: instance.exports.environmentInit as (
heap: number,
outer: number
) => number,
stringToNumberImpl: instance.exports.stringToNumberImpl as (
str: number,
radix: number
) => number,
shortStrEq: instance.exports.shortStrEq as (
str: number,
shortStr: number,
shortStrLen: number
) => number,
atom: instance.exports.atom as (token: number) => number,
stringToDatum: instance.exports.stringToDatum as (ptr: number) => number,
read: instance.exports.read as () => number,
eval: instance.exports.eval as (env: number, expr: number) => number,
registerBuiltins: instance.exports.registerBuiltins as (
heap: number,
env: number
) => void,
print: instance.exports.print as (ptr: number) => void,
};
}
describe("runtime wasm", () => {
const io = new IoTest();
const wasm = loadWasm({ io: io.module });
let exports: TestExports;
const written: string[] = [];
const writeHandler = (evt: IoEvent) => {
if (evt.data) {
written.push(evt.data);
}
return true;
};
before(async () => {
const instance = await wasm;
exports = exportsFromInstance(instance);
io.exports = exports;
io.addEventListener("write", writeHandler);
});
beforeEach(() => {
exports.mallocInit();
exports.runtimeInit();
});
after(() => {
io.removeEventListener("write", writeHandler);
});
afterEach(() => {
if (written.length) {
console.log(written.splice(0, written.length).join(""));
}
exports.runtimeCleanup();
checkForLeaks(exports);
});
it("converts strings to numbers", () => {
const kTestNumbers: { str: string; ex: number }[] = [
{ str: "1", ex: 1 },
{ str: "#b1", ex: 1 },
{ str: "#o1", ex: 1 },
{ str: "#d1", ex: 1 },
{ str: "#x1", ex: 1 },
{ str: "#b10010010110", ex: 0b10010010110 },
{ str: "#o1234", ex: 0o1234 },
{ str: "#d1234", ex: 1234 },
{ str: "#x1234", ex: 0x1234 },
{ str: "#xabef", ex: 0xabef },
{ str: "#xABEF", ex: 0xabef },
{ str: "-42", ex: -42 },
{ str: "#d-42", ex: -42 },
{ str: "#x-42", ex: -0x42 },
{ str: "#e8", ex: 8 },
];
for (const { str, ex } of kTestNumbers) {
const strPtr = createString(exports, str);
const strHeapPtr = exports.heapAlloc(exports.gHeap(), 7, strPtr, 0);
const numHeapPtr = exports.stringToNumberImpl(strHeapPtr, 10);
const words = new Int32Array(
exports.memory.buffer.slice(numHeapPtr, numHeapPtr + 12)
);
expect(words[0]).to.equal(
4,
`string->number(${str}) return value should be an integer`
);
expect(words[1]).to.equal(
ex,
`this should be the numeric value of '${str}'`
);
if (ex >= 0) {
expect(words[2]).to.equal(
0,
`string->number(${str}) This should be the sign extension of a positive 32 bit integer`
);
} else {
expect(words[2]).to.equal(
-1,
`string->number(${str}) This should be the sign extension of a negative 32 bit integer`
);
}
}
const kTestInvalidNumbers: [string, string][] = [
["1#x", "#f"],
["1_200", "#f"],
["1,200", "#f"],
["--2", "#f"],
["#b107", "#f"],
["#o108", "#f"],
["#x1G", "#f"],
["#d1e", "#f"],
];
for (const [str, exp] of kTestInvalidNumbers) {
const strPtr = createString(exports, str);
const strHeapPtr = exports.heapAlloc(exports.gHeap(), 7, strPtr, 0);
const numHeapPtr = exports.stringToNumberImpl(strHeapPtr, 10);
exports.print(numHeapPtr);
expect(written.splice(0, written.length).join("")).to.equal(exp);
// const words = new Int32Array(
// exports.memory.buffer.slice(numHeapPtr, numHeapPtr + 12)
// );
// expect(words[0]).to.equal(
// 2,
// `string->number(${str}) return value should be a boolean`
// );
// expect(words[1]).to.equal(
// 0,
// `string->number(${str}) return value should be false`
// );
// expect(numHeapPtr).to.equal(
// exports.gFalse(),
// `should use the global false value`
// );
}
});
it("can compare tiny strings", () => {
const kTestStrings: {
str: string;
bytes: number;
len: number;
ex: boolean;
}[] = [
{ str: "(", bytes: 0x28, len: 1, ex: true },
{ str: ")", bytes: 0x29, len: 1, ex: true },
{ str: "foo", bytes: 0x6f6f66, len: 3, ex: true },
{ str: "€", bytes: 0xac82e2, len: 3, ex: true },
{ str: "bar", bytes: 0x6162, len: 2, ex: false },
{ str: "bar", bytes: 0x726162, len: 3, ex: true },
{ str: "bar", bytes: 0x726163, len: 3, ex: false },
];
for (const { str, bytes, len, ex } of kTestStrings) {
const strPtr = createString(exports, str);
expect(exports.shortStrEq(strPtr, bytes, len)).to.equal(
ex ? 1 : 0,
`short-str-eq(${JSON.stringify(str)}, 0x${bytes.toString(
16
)}, ${len}) should return ${ex}`
);
exports.mallocFree(strPtr);
}
const longer = createString(exports, "abcdE");
expect(() => exports.shortStrEq(longer, 0x64636261, 5)).to.throw(
"unreachable"
);
exports.mallocFree(longer);
});
const makeHeapString = (str: string): number => {
const strPtr = createString(exports, str);
return exports.heapAlloc(exports.gHeap(), 0x7, strPtr, 0);
};
it("will make a 'true' atom from #t", () => {
let heapItem = makeHeapString("#t");
let res = exports.atom(heapItem);
let words = new Uint32Array(exports.memory.buffer.slice(res, res + 12));
expect(words[0]).to.equal(2, "#t should make a boolean");
expect(words[1]).to.equal(1, "#t should make a true boolean");
expect(res).to.equal(exports.gTrue());
});
it("will make a 'false' atom from #f", () => {
const heapItem = makeHeapString("#f");
const res = exports.atom(heapItem);
const words = new Uint32Array(exports.memory.buffer.slice(res, res + 12));
expect(words[0]).to.equal(2, "#f should make a boolean");
expect(words[1]).to.equal(0, "#f should make a false boolean");
expect(res).to.equal(exports.gFalse());
});
it("will make an integer atom from #xFF", () => {
const heapItem = makeHeapString("#xFF");
const res = exports.atom(heapItem);
const words = new Uint32Array(exports.memory.buffer.slice(res, res + 12));
expect(words[0]).to.equal(4, "#xFF should make a number");
expect(words[1]).to.equal(0xff, "#xFF be 0xFF");
expect(words[2]).to.equal(0), "#xFF should be 0 in the upper word";
});
it("will make a integer atom from 42", () => {
const heapItem = makeHeapString("42");
const res = exports.atom(heapItem);
const words = new Uint32Array(exports.memory.buffer.slice(res, res + 12));
expect(words[0]).to.equal(4, "42 should make a number");
expect(words[1]).to.equal(42);
expect(words[2]).to.equal(0), "42 should be 0 in the upper word";
});
it('will make a symbol atom from "foo"', () => {
const heapItem = makeHeapString("foo");
let words = new Uint32Array(
exports.memory.buffer.slice(heapItem, heapItem + 12)
);
const fooStr = words[1];
const res = exports.atom(heapItem);
words = new Uint32Array(exports.memory.buffer.slice(res, res + 12));
expect(words[0]).to.equal(6, "foo should make a symbol");
expect(getString(exports, words[1])).to.equal("foo");
expect(words[2]).to.equal(0), "a symbol should have 0 in the upper word";
});
it("string->datum will convert '42' to an integer item", () => {
const input = createString(exports, "42");
const datum = exports.stringToDatum(input);
const words = new Uint32Array(
exports.memory.buffer.slice(datum, datum + 12)
);
expect(words[0]).to.equal(4, "42 should make a number");
expect(words[1]).to.equal(42);
expect(words[2]).to.equal(0), "42 should be 0 in the upper word";
});
it("string->datum will convert real numbers", () => {
const testVectors: { str: string; real: number }[] = [
{ str: "#i43", real: 43 },
{ str: "1.0", real: 1 },
{ str: "+inf.0", real: Infinity },
{ str: "-inf.0", real: -Infinity },
{ str: "+nan.0", real: NaN },
{ str: "-nan.0", real: NaN },
{ str: "1.234", real: 1.234 },
{ str: "6.543e21", real: 6.543e21 },
{ str: "1.234e-56", real: 1.234e-56 },
];
for (const { str, real } of testVectors) {
const input = createString(exports, str);
const datum = exports.stringToDatum(input);
const words = new Uint32Array(
exports.memory.buffer.slice(datum, datum + 12)
);
expect(words[0]).to.equal(
5,
`expecting a floating point number ${str} => ${real}`
);
const numbers = new Float64Array(
exports.memory.buffer.slice(datum + 4, datum + 12)
);
if (isNaN(real)) {
expect(numbers[0]).to.be.NaN;
} else {
expect(numbers[0]).to.equal(real, `Converted from ${str}`);
}
}
});
it("string->datum will convert '()' to a nil item", () => {
const readHandler = (evt: IoEvent) => {
evt.data = ")";
return false;
};
io.addEventListener("read", readHandler);
const input = createString(exports, "(");
const datum = exports.stringToDatum(input);
const words = new Uint32Array(
exports.memory.buffer.slice(datum, datum + 12)
);
expect(words[0]).to.equal(1, "() should make a nil datum");
io.removeEventListener("read", readHandler);
});
it("string->datum will convert '(1 2 3)' to a three item list", () => {
const tokens = ["1 2 3 )"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const input = createString(exports, "(");
const datum = exports.stringToDatum(input);
let words = new Uint32Array(exports.memory.buffer.slice(datum, datum + 12));
const items: number[] = [];
while (true) {
expect(words[0] & 0x1f).to.equal(3, "should be a cons cell");
const car = words[1];
const carWords = new Uint32Array(
exports.memory.buffer.slice(car, car + 12)
);
expect(carWords[0]).to.equal(4);
items.push(carWords[1]);
const cdr = words[2];
words = new Uint32Array(exports.memory.buffer.slice(cdr, cdr + 12));
if (words[0] == 1) {
// nil cdr means end of list
break;
}
}
expect(items).to.have.ordered.members([1, 2, 3]);
io.removeEventListener("read", readHandler);
});
it("string->datum will convert '(1 . 3)' to a cons cell", () => {
const tokens = ["1 . 3 )"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const input = createString(exports, "(");
const datum = exports.stringToDatum(input);
let words = new Uint32Array(exports.memory.buffer.slice(datum, datum + 12));
expect(words[0] & 0x1f).to.equal(3, "should be a cons cell");
const car = words[1];
const carWords = new Uint32Array(
exports.memory.buffer.slice(car, car + 12)
);
expect(carWords[0]).to.equal(4, "first item should be an integer");
expect(carWords[1]).to.equal(1, "first item should be 1");
const cdr = words[2];
const cdrWords = new Uint32Array(
exports.memory.buffer.slice(cdr, cdr + 12)
);
expect(cdrWords[0]).to.equal(4, "second item should be an integer");
expect(cdrWords[1]).to.equal(3, "second item should be 3");
io.removeEventListener("read", readHandler);
});
it("read will read '(1 2 3)' as a three item list", () => {
const tokens = ["(1 2 ", " 3 )"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const datum = exports.read();
let words = new Uint32Array(exports.memory.buffer.slice(datum, datum + 12));
const items: number[] = [];
while (true) {
expect(words[0] & 0x1f).to.equal(3, "should be a cons cell");
const car = words[1];
const carWords = new Uint32Array(
exports.memory.buffer.slice(car, car + 12)
);
expect(carWords[0]).to.equal(4);
items.push(carWords[1]);
const cdr = words[2];
words = new Uint32Array(exports.memory.buffer.slice(cdr, cdr + 12));
if (words[0] == 1) {
// nil cdr means end of list
break;
}
}
expect(items).to.have.ordered.members([1, 2, 3]);
io.removeEventListener("read", readHandler);
});
it("evals numbers to themselves", () => {
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = exports.heapAlloc(exports.gHeap(), 4, 1234, 0);
const result = exports.eval(env, datum);
expect(exports.eval(env, datum)).to.equal(
datum,
"numbers should eval to themselves"
);
});
it("evals symbols to builtins via environment lookup", () => {
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = createHeapSymbol(exports, "+");
const result = exports.eval(env, datum);
const words = new Uint32Array(
exports.memory.buffer.slice(result, result + 12)
);
expect(words[0]).to.equal(
11,
"expect the result to be a builtin (type 11)"
);
});
it("can eval simple expressions", () => {
const tokens = ["(+ 1 (* 2 3))"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = exports.read();
const result = exports.eval(env, datum);
const words = new Uint32Array(
exports.memory.buffer.slice(result, result + 12)
);
expect(words[0]).to.equal(4, "result type should be an i64");
expect(words[1]).to.equal(7, "1 + 2 * 3 = 7");
expect(words[2]).to.equal(0);
io.removeEventListener("read", readHandler);
});
it("can choose branches in an if", () => {
const tokens = ["(if #t 3 4)"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = exports.read();
const result = exports.eval(env, datum);
const words = new Uint32Array(
exports.memory.buffer.slice(result, result + 12)
);
expect(words[0]).to.equal(4, "result type should be an i64");
expect(words[1]).to.equal(3, "The true branch should have been taken");
expect(words[2]).to.equal(0);
io.removeEventListener("read", readHandler);
});
it("Handles an if with only a consequent", () => {
const tokens = [
`
(if #t 3)
(if #f 4)
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("3");
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.not.equal("4");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("can assign variables in a let expression", () => {
const tokens = [
`
(let
(
(x 10)
(y 20)
)
(+ x y)
)
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = exports.read();
const result = exports.eval(env, datum);
const words = new Uint32Array(
exports.memory.buffer.slice(result, result + 12)
);
expect(words[0]).to.equal(4, "result type should be an i64");
expect(words[1]).to.equal(30, "inner x and y should be 30");
expect(words[2]).to.equal(0);
io.removeEventListener("read", readHandler);
});
it("can evaluate a lambda", () => {
const tokens = ["((lambda (x) (+ x x)) 4)"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
const datum = exports.read();
const result = exports.eval(env, datum);
const words = new Uint32Array(
exports.memory.buffer.slice(result, result + 12)
);
expect(words[0]).to.equal(4, "result type should be an i64");
expect(words[1]).to.equal(8, "x + x should be 8");
expect(words[2]).to.equal(0);
io.removeEventListener("read", readHandler);
});
it("can evaluate a lambda with a single formal", () => {
const tokens = ["((lambda x x) 3 4 5 6)"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("(3 4 5 6)");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("can evaluate a lambda with a dotted formal list", () => {
const tokens = ["((lambda (x y . z) z) 3 4 5 6)"];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("(5 6)");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("applies the correct closure for lambda", () => {
const tokens = [
`
(let ((x 2))
(let ((fn (lambda (y) (+ x y))))
(let ((x 3))
(fn 4)
)
)
)
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("6");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("quote returns input as a datum", () => {
const tokens = [
`
(quote (+ 1 2))
(quote a)
'(+ 1 2)
'foo
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("(+ 1 2)", "(quote (+ 1 2))");
written.splice(0, written.length);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("a", "(quote a)");
written.splice(0, written.length);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("(+ 1 2)", "'(+ 1 2)");
written.splice(0, written.length);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("foo", "'foo");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("define sets a value in the environment", () => {
const tokens = [
`
(define x 42)
x
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
written.splice(0, written.length);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("42", "x should now be 42");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
it("define sets a lambda in the environment", () => {
const tokens = [
`
(define (add x y) (+ x y))
(add 2 3)
`,
];
const readHandler = (evt: IoEvent) => {
evt.data = tokens.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
exports.print(exports.eval(env, exports.read()));
written.splice(0, written.length);
exports.print(exports.eval(env, exports.read()));
expect(written.join("")).to.equal("5", "2 + 3 = 5");
written.splice(0, written.length);
io.removeEventListener("read", readHandler);
});
const testExpectations = (
inputs: string[],
outputs: (undefined | string)[]
) => {
const readHandler = (evt: IoEvent) => {
evt.data = inputs.shift();
return false;
};
io.addEventListener("read", readHandler);
const env = exports.environmentInit(exports.gHeap(), 0);
exports.registerBuiltins(exports.gHeap(), env);
while (inputs.length) {
const input = inputs[0];
exports.print(exports.eval(env, exports.read()));
const expected = outputs.shift();
if (typeof expected === "string") {
const output = written.join("");
expect(output).to.equal(
expected,
`"${input}" should evaluate to "${expected}"`
);
}
written.splice(0, written.length);
}
io.removeEventListener("read", readHandler);
};
it("allows set! to update a definition", () => {
const inputs = ["(define x 2)", "(+ x 1)", "(set! x 4)", "(+ x 1)"];
const outputs = [undefined, "3", undefined, "5"];
testExpectations(inputs, outputs);
});
it("returns an error when read fails, and can resume reading", () => {
const inputs = ["(+ 1 2"];
const outputs = ["<error eof>"];
testExpectations(inputs, outputs);
inputs.push(")");
outputs.push("3");
testExpectations(inputs, outputs);
});
}); | the_stack |
import * as vscode from "vscode";
import { ColorThemeKind, workspace } from "vscode";
import { colorCombos, IColorCombo } from "./colors";
import { glo } from "./extension";
// Possible color values are almost (Please see the notes below) all CSS color/gradient values.
// ---- 'transparent' (or any rgba/hsla... value with partial transparency) - as itself or as inside gradient, works fine for borders, but for backgrounds, transparency is problematic, so 'transparent' will be the color of editor background.
// ---- 'none' is the same as 'transparent', but 'none' works only as itself, not as inside gradient.
// ---- 'neutral' (or undefined, null, false, '', ) means it can be overriden by any other setting. If nothing overrides it, then it should be transparent (Or editor background).
export const editorBackgroundFormula = "var(--vscode-editor-background)";
export const makeInnerKitchenNotation = (
possiblyLegitColor: any, // it may be gradient
tempTransparent?: "back",
): string => {
// !!! IMPORTANT !!!
// In order to be able to use gradient in borders,
// new rendering function uses background property with
// padding-box (for background) and border-box (for border) values.
// CSS background with padding-box and border-box values
// does not work if any of them is solid color.
// for example, this works fine:
/*
background:
linear-gradient(red, red) padding-box,
linear-gradient(green, green) border-box;
*/
// but this does not work:
/*
background:
red padding-box,
green border-box;
*/
// So, instead of sending solid color, maybe we should always
// convert it as linear-gradient notation.
if (typeof possiblyLegitColor !== "string") {
return "neutral";
}
const trimmed = possiblyLegitColor.trim();
if (trimmed === "" || trimmed === "neutral") {
return "neutral";
}
if (["none", "transparent"].includes(trimmed)) {
if (tempTransparent === "back") {
return `linear-gradient(to right, ${editorBackgroundFormula}, ${editorBackgroundFormula})`;
} else {
return `linear-gradient(to right, ${"transparent"}, ${"transparent"})`;
}
}
if (trimmed.includes(`url(`)) {
return trimmed;
}
if (trimmed.includes("gradient")) {
return trimmed;
} else {
return `linear-gradient(to right, ${trimmed}, ${trimmed})`;
}
};
export enum AdvancedColoringFields {
// eslint-disable-next-line @typescript-eslint/naming-convention
fromD0ToInward_All = "fromD0ToInward_All",
// eslint-disable-next-line @typescript-eslint/naming-convention
fromD0ToInward_FocusTree = "fromD0ToInward_FocusTree",
//
//
// eslint-disable-next-line @typescript-eslint/naming-convention
fromFocusToOutward_FocusTree = "fromFocusToOutward_FocusTree",
// eslint-disable-next-line @typescript-eslint/naming-convention
fromFocusToOutward_All = "fromFocusToOutward_All",
//
//
// eslint-disable-next-line @typescript-eslint/naming-convention
fromFocusToInward_All = "fromFocusToInward_All",
}
export interface IOneChainOfColors {
priority: number;
sequence: string[];
}
export interface IAdvancedColoringChain {
borders: IOneChainOfColors | undefined;
backgrounds: IOneChainOfColors | undefined;
}
export const defaultsForAdvancedColoringOptions = {
[AdvancedColoringFields.fromD0ToInward_All]: [10, 0, 1, 1],
[AdvancedColoringFields.fromFocusToOutward_All]: [20, 0, 0, 1],
[AdvancedColoringFields.fromD0ToInward_FocusTree]: [30, 0, 1, 1],
[AdvancedColoringFields.fromFocusToOutward_FocusTree]: [40, 0, 1, 1],
[AdvancedColoringFields.fromFocusToInward_All]: [50, 0, 0, 1],
};
const generateOneChainOfColorsForEachDepth = (
myString: any, // e.g. '50,0,0,0; hsl(0, 0%, 100%, 0.25)>red>blue'
// where first number relates priority
// Second number relates zero-based index of first item of first loop, So it splits what should be looped from what should not be looped.
// third number relates loop part reversion:
//---- 0: original,
//---- 1: reversed,
// fourth number relates looping strategy:
//---- 0: all the continuation items to be 'neutral', 'neutral' means it will be overriden by any other setting.
//---- 1: Only the last item will be looped. Yes, it will ignore the second option;
//---- 2: loop as forward,
//---- 3: loop as pair of forward and backward,
// type "!" to disable the sequence, like this: '!50,0,0,0; hsl(0, 0%, 100%, 0.25)>red>blue'
// kind: keyof typeof defaultsForAdvancedColoringOptions, // maybe not needed
tempTransparent?: "back",
): { priority: number; sequence: string[] } | undefined => {
if (typeof myString !== "string") {
return undefined;
}
let tr = myString.trim();
if (!tr || tr[0] === "!") {
return undefined;
}
const trL = tr.length;
if (tr[trL - 1] === ">") {
tr = tr.slice(0, trL - 1);
}
const optionsAndColorsAsTwoStrings = tr.split(";").map((x) => x.trim());
const optionsSequenceRaw = optionsAndColorsAsTwoStrings[0]
.split(",")
.map((x) => x.trim());
if (
optionsSequenceRaw.length !== 4 ||
optionsSequenceRaw.some((x) => x === "")
) {
return undefined;
}
const optionsSequence = optionsSequenceRaw.map((x) => Number(x));
for (let i = 0; i < optionsSequence.length; i += 1) {
if (i === 0) {
const prio = optionsSequence[i];
if (Number.isNaN(prio)) {
return undefined;
}
continue;
} else if (!Number.isInteger(optionsSequence[i])) {
return undefined;
}
}
const priority = optionsSequence[0];
let loopStartIndex = optionsSequence[1];
const reverseLoop = optionsSequence[2];
const loopingStrategy = optionsSequence[3];
// ------------
const coloringSequence = optionsAndColorsAsTwoStrings[1]
.split(">")
.map((x) => makeInnerKitchenNotation(x.trim(), tempTransparent));
if (
coloringSequence.length === 0 ||
coloringSequence.some((x) => x === "")
) {
return undefined;
}
if ([0, 1].includes(loopingStrategy)) {
loopStartIndex = coloringSequence.length - 1;
}
if (
priority < -1000000 ||
priority > 1000000 ||
reverseLoop < 0 ||
reverseLoop > 1 ||
loopingStrategy < 0 ||
loopingStrategy > 3 ||
loopStartIndex < 0 ||
loopStartIndex > coloringSequence.length - 1
) {
return undefined;
}
// ..........................
// Now we have optionsSequence and coloringSequence
// ============
// ===================
const nonLoopPart = coloringSequence.slice(0, loopStartIndex);
const loopPart = coloringSequence.slice(
loopStartIndex,
coloringSequence.length,
);
const reversedOrNotLoopPart =
reverseLoop === 0 ? [...loopPart] : [...loopPart].reverse();
const loopLen = reversedOrNotLoopPart.length;
const legitSequence = [...nonLoopPart, ...reversedOrNotLoopPart];
const leLen = legitSequence.length;
const lengthOfDepths = glo.maxDepth + 2; // because glo.maxDepth is as minus 1
if (lengthOfDepths < 1) {
return undefined;
}
const finalArrayOfColors: string[] = [];
if (loopingStrategy === 0) {
// the rest are neutral
finalArrayOfColors.push(...legitSequence);
// the rest will be undefined, so they will be neutral
} else if (loopingStrategy === 1) {
//1: the rest are last item
finalArrayOfColors.push(...legitSequence);
const lastItem = legitSequence[leLen - 1];
for (let i = leLen; i <= lengthOfDepths - 1; i += 1) {
finalArrayOfColors.push(lastItem);
}
} else if (loopingStrategy === 2) {
// 2: loop as forward
finalArrayOfColors.push(...nonLoopPart);
while (finalArrayOfColors.length < lengthOfDepths) {
finalArrayOfColors.push(...[...reversedOrNotLoopPart]);
}
finalArrayOfColors.length = lengthOfDepths;
} else if (loopingStrategy === 3) {
//3: loop as pair of forward and backward
finalArrayOfColors.push(...nonLoopPart);
const inner = reversedOrNotLoopPart.slice(1, loopLen - 1);
const innerRev = [...inner].reverse();
const head = reversedOrNotLoopPart[0];
const tail = reversedOrNotLoopPart[loopLen - 1];
while (finalArrayOfColors.length < lengthOfDepths) {
finalArrayOfColors.push(head, ...inner, tail, ...innerRev);
}
finalArrayOfColors.length = lengthOfDepths;
}
return { priority, sequence: finalArrayOfColors };
};
const chooseColorCombo = (
selectedCombo: string | undefined,
darkCombo: string | undefined,
lightCombo: string | undefined,
highContrastCombo: string | undefined,
): string | undefined => {
const currVscodeThemeKind = vscode.window.activeColorTheme.kind;
const isTruthy = (combo?: string) => {
if (combo && combo.toLowerCase() !== "none") {
return true;
} else {
return false;
}
};
let resultCombo = selectedCombo;
if (isTruthy(darkCombo) && currVscodeThemeKind === ColorThemeKind.Dark) {
resultCombo = darkCombo;
// console.log("dark kind");
} else if (
isTruthy(lightCombo) &&
currVscodeThemeKind === ColorThemeKind.Light
) {
resultCombo = lightCombo;
// console.log("light king");
} else if (
isTruthy(highContrastCombo) &&
currVscodeThemeKind === ColorThemeKind.HighContrast
) {
resultCombo = highContrastCombo;
// console.log("HC king");
}
// console.log("resultCombo:", resultCombo);
return resultCombo;
};
export const applyAllBlockmanSettings = () => {
const blockmanConfig = workspace.getConfiguration("blockman");
const bc = blockmanConfig;
// =============
const candLineHeight: number | undefined = bc.get("n01LineHeight");
if (
typeof candLineHeight === "number" &&
candLineHeight >= 2 &&
candLineHeight < 130
) {
// glo.eachCharFrameHeight = candLineHeight;
}
// =============
const candEachCharFrameWidth: number | undefined = bc.get(
"n02EachCharFrameWidth",
);
if (
typeof candEachCharFrameWidth === "number" &&
candEachCharFrameWidth >= 2 &&
candEachCharFrameWidth < 130
) {
// glo.eachCharFrameWidth = candEachCharFrameWidth;
}
// =============
const candMaxDepth: number | undefined = bc.get("n03MaxDepth");
if (typeof candMaxDepth === "number" && candMaxDepth >= -1) {
glo.maxDepth = Math.floor(candMaxDepth - 1);
// glo.maxDepth = 100;
}
// ============= Coloring
const selectedColorComboName: string | undefined = bc.get(
"n04ColorComboPreset",
);
const selectedColorComboNameForDarkTheme: string | undefined = bc.get(
"n04Sub01ColorComboPresetForDarkTheme",
);
const selectedColorComboNameForLightTheme: string | undefined = bc.get(
"n04Sub02ColorComboPresetForLightTheme",
);
const selectedColorComboNameForHighContrastTheme: string | undefined =
bc.get("n04Sub03ColorComboPresetForHighContrastTheme");
// console.log("selectedColorComboName:", selectedColorComboName);
let thisColorCombo: IColorCombo | undefined = undefined;
let chosenColorCombo = chooseColorCombo(
selectedColorComboName,
selectedColorComboNameForDarkTheme,
selectedColorComboNameForLightTheme,
selectedColorComboNameForHighContrastTheme,
);
if (chosenColorCombo) {
thisColorCombo = colorCombos.find(
(combo) => combo.name === chosenColorCombo,
);
}
const customColorOfDepth0: string | undefined = bc.get(
"n05CustomColorOfDepth0",
);
const customColorOfDepth1: string | undefined = bc.get(
"n06CustomColorOfDepth1",
);
const customColorOfDepth2: string | undefined = bc.get(
"n07CustomColorOfDepth2",
);
const customColorOfDepth3: string | undefined = bc.get(
"n08CustomColorOfDepth3",
);
const customColorOfDepth4: string | undefined = bc.get(
"n09CustomColorOfDepth4",
);
const customColorOfDepth5: string | undefined = bc.get(
"n10CustomColorOfDepth5",
);
const customColorOfDepth6: string | undefined = bc.get(
"n11CustomColorOfDepth6",
);
const customColorOfDepth7: string | undefined = bc.get(
"n12CustomColorOfDepth7",
);
const customColorOfDepth8: string | undefined = bc.get(
"n13CustomColorOfDepth8",
);
const customColorOfDepth9: string | undefined = bc.get(
"n14CustomColorOfDepth9",
);
const customColorOfDepth10: string | undefined = bc.get(
"n15CustomColorOfDepth10",
);
const customColorsOnEachDepth: (string | undefined)[] = [
customColorOfDepth0,
customColorOfDepth1,
customColorOfDepth2,
customColorOfDepth3,
customColorOfDepth4,
customColorOfDepth5,
customColorOfDepth6,
customColorOfDepth7,
customColorOfDepth8,
customColorOfDepth9,
customColorOfDepth10,
];
const customColorOfFocusedBlock: string | undefined = bc.get(
"n17CustomColorOfFocusedBlock",
);
const customColorOfFocusedBlockBorder: string | undefined = bc.get(
"n18CustomColorOfFocusedBlockBorder",
);
const customColorOfBlockBorder: string | undefined = bc.get(
"n19CustomColorOfBlockBorder",
);
const customColorOfDepth0Border: string | undefined = bc.get(
"n20CustomColorOfDepth0Border",
);
if (thisColorCombo) {
glo.coloring.onEachDepth = thisColorCombo.onEachDepth.map(
(color) => color,
); // important to copy the array, using map() or using [...array]
glo.coloring.focusedBlock = thisColorCombo.focusedBlock;
glo.coloring.border = thisColorCombo.border;
glo.coloring.borderOfDepth0 = thisColorCombo.borderOfDepth0;
glo.coloring.borderOfFocusedBlock = thisColorCombo.borderOfFocusedBlock;
}
customColorsOnEachDepth.map((color, i) => {
if (color && color.trim()) {
// glo.coloring.onEachDepth[i] = color;
glo.coloring.onEachDepth[i] = color;
}
});
if (customColorOfFocusedBlock && customColorOfFocusedBlock.trim()) {
glo.coloring.focusedBlock = customColorOfFocusedBlock;
}
if (
customColorOfFocusedBlockBorder &&
customColorOfFocusedBlockBorder.trim()
) {
glo.coloring.borderOfFocusedBlock = customColorOfFocusedBlockBorder;
}
if (customColorOfBlockBorder && customColorOfBlockBorder.trim()) {
glo.coloring.border = customColorOfBlockBorder;
}
if (customColorOfDepth0Border && customColorOfDepth0Border.trim()) {
glo.coloring.borderOfDepth0 = customColorOfDepth0Border;
}
// ===========
const enableFocus: boolean | undefined = bc.get("n16EnableFocus");
if (enableFocus) {
glo.enableFocus = true;
} else if (enableFocus === false) {
glo.enableFocus = false;
}
// ===========
const candBorderRadius: number | undefined = bc.get("n21BorderRadius");
if (typeof candBorderRadius === "number" && candBorderRadius >= 0) {
glo.borderRadius = candBorderRadius;
}
// ===========
const analyzeCurlyBrackets: boolean | undefined = bc.get(
"n22AnalyzeCurlyBrackets",
);
if (analyzeCurlyBrackets) {
glo.analyzeCurlyBrackets = true;
} else if (analyzeCurlyBrackets === false) {
glo.analyzeCurlyBrackets = false;
}
// ===========
const analyzeSquareBrackets: boolean | undefined = bc.get(
"n23AnalyzeSquareBrackets",
);
if (analyzeSquareBrackets) {
glo.analyzeSquareBrackets = true;
} else if (analyzeSquareBrackets === false) {
glo.analyzeSquareBrackets = false;
}
// ===========
const analyzeRoundBrackets: boolean | undefined = bc.get(
"n24AnalyzeRoundBrackets",
);
if (analyzeRoundBrackets) {
glo.analyzeRoundBrackets = true;
} else if (analyzeRoundBrackets === false) {
glo.analyzeRoundBrackets = false;
}
// ===========
const analyzeTags: boolean | undefined = bc.get("n25AnalyzeTags");
if (analyzeTags) {
glo.analyzeTags = true;
} else if (analyzeTags === false) {
glo.analyzeTags = false;
}
// ===========
const analyzeIndentDedentTokens: boolean | undefined = bc.get(
"n26AnalyzeIndentDedentTokens",
);
if (analyzeIndentDedentTokens) {
glo.analyzeIndentDedentTokens = true;
} else if (analyzeIndentDedentTokens === false) {
glo.analyzeIndentDedentTokens = false;
}
// ===========
const alsoRenderBlocksInsideSingleLineAreas: boolean | undefined = bc.get(
"n27AlsoRenderBlocksInsideSingleLineAreas",
);
if (alsoRenderBlocksInsideSingleLineAreas) {
glo.renderInSingleLineAreas = true;
} else if (alsoRenderBlocksInsideSingleLineAreas === false) {
glo.renderInSingleLineAreas = false;
}
// ==============
const timeToWaitBeforeRerenderAfterLastChangeEvent: number | undefined =
bc.get("n28TimeToWaitBeforeRerenderAfterLastChangeEvent");
if (
typeof timeToWaitBeforeRerenderAfterLastChangeEvent === "number" &&
timeToWaitBeforeRerenderAfterLastChangeEvent >= 0 &&
timeToWaitBeforeRerenderAfterLastChangeEvent < 10
) {
glo.renderTimerForChange =
timeToWaitBeforeRerenderAfterLastChangeEvent * 1000;
}
// ==============
const timeToWaitBeforeRerenderAfterlastFocusEvent: number | undefined =
bc.get("n29TimeToWaitBeforeRerenderAfterLastFocusEvent");
if (
typeof timeToWaitBeforeRerenderAfterlastFocusEvent === "number" &&
timeToWaitBeforeRerenderAfterlastFocusEvent >= 0 &&
timeToWaitBeforeRerenderAfterlastFocusEvent < 10
) {
glo.renderTimerForFocus =
timeToWaitBeforeRerenderAfterlastFocusEvent * 1000;
}
// ==============
const timeToWaitBeforeRerenderAfterlastScrollEvent: number | undefined =
bc.get("n30TimeToWaitBeforeRerenderAfterLastScrollEvent");
// console.log("iissss:", timeToWaitBeforeRerenderAfterlastScrollEvent);
if (
typeof timeToWaitBeforeRerenderAfterlastScrollEvent === "number" &&
timeToWaitBeforeRerenderAfterlastScrollEvent >= 0 &&
timeToWaitBeforeRerenderAfterlastScrollEvent < 10
) {
glo.renderTimerForScroll =
timeToWaitBeforeRerenderAfterlastScrollEvent * 1000;
}
// ==============
const renderIncrementBeforeAndAfterVisibleRange: number | undefined =
bc.get("n31RenderIncrementBeforeAndAfterVisibleRange");
// console.log("iissss:", timeToWaitBeforeRerenderAfterlastScrollEvent);
if (
typeof renderIncrementBeforeAndAfterVisibleRange === "number" &&
renderIncrementBeforeAndAfterVisibleRange >= -200 &&
renderIncrementBeforeAndAfterVisibleRange <= 200
) {
glo.renderIncBeforeAfterVisRange = Math.floor(
renderIncrementBeforeAndAfterVisibleRange,
);
}
const customBlackListOfFileFormats: string | undefined = bc.get(
"n32BlackListOfFileFormats",
);
// console.log(glo.coloring.border);
if (typeof customBlackListOfFileFormats === "string") {
const stringWithoutSpaces = customBlackListOfFileFormats.replace(
/ /g,
``,
);
const stringWithoutSpacesAndTabs = stringWithoutSpaces.replace(/ /g, ``);
if (stringWithoutSpacesAndTabs) {
const mySplitArr = stringWithoutSpacesAndTabs.split(",");
glo.blackListOfFileFormats = mySplitArr;
} else {
glo.blackListOfFileFormats = [];
}
}
// ! IMPORTANT
glo.coloring.border = makeInnerKitchenNotation(glo.coloring.border);
glo.coloring.borderOfDepth0 = makeInnerKitchenNotation(
glo.coloring.borderOfDepth0,
);
glo.coloring.borderOfFocusedBlock = makeInnerKitchenNotation(
glo.coloring.borderOfFocusedBlock,
);
glo.coloring.focusedBlock = makeInnerKitchenNotation(
glo.coloring.focusedBlock,
"back",
);
glo.coloring.onEachDepth = glo.coloring.onEachDepth.map((color) =>
makeInnerKitchenNotation(color, "back"),
);
// console.log(">>>>>>>>>>>>>", glo.coloring.focusedBlock);
const adCoFromDepth0ToInwardForAllBorders: string | undefined = bc.get(
"n33A01B1FromDepth0ToInwardForAllBorders",
);
const adCoFromDepth0ToInwardForAllBackgrounds: string | undefined = bc.get(
"n33A01B2FromDepth0ToInwardForAllBackgrounds",
);
// --------------------
const adCoFromFocusToOutwardForAllBorders: string | undefined = bc.get(
"n33A02B1FromFocusToOutwardForAllBorders",
);
const adCoFromFocusToOutwardForAllBackgrounds: string | undefined = bc.get(
"n33A02B2FromFocusToOutwardForAllBackgrounds",
);
// --------------------
const adCoFromDepth0ToInwardForFocusTreeBorders: string | undefined =
bc.get("n33A03B1FromDepth0ToInwardForFocusTreeBorders");
const adCoFromDepth0ToInwardForFocusTreeBackgrounds: string | undefined =
bc.get("n33A03B2FromDepth0ToInwardForFocusTreeBackgrounds");
// --------------------
const adCoFromFocusToOutwardForFocusTreeBorders: string | undefined =
bc.get("n33A04B1FromFocusToOutwardForFocusTreeBorders");
const adCoFromFocusToOutwardForFocusTreeBackgrounds: string | undefined =
bc.get("n33A04B2FromFocusToOutwardForFocusTreeBackgrounds");
// --------------------
const adCoFromFocusToInwardForAllBorders: string | undefined = bc.get(
"n33A05B1FromFocusToInwardForAllBorders",
);
const adCoFromFocusToInwardForAllBackgrounds: string | undefined = bc.get(
"n33A05B2FromFocusToInwardForAllBackgrounds",
);
// =======================
// =======================
// -----
const advancedColoringSettingsOfBorders = [
{
val: adCoFromDepth0ToInwardForAllBorders,
kind: AdvancedColoringFields.fromD0ToInward_All,
},
{
val: adCoFromFocusToOutwardForAllBorders,
kind: AdvancedColoringFields.fromFocusToOutward_All,
},
{
val: adCoFromDepth0ToInwardForFocusTreeBorders,
kind: AdvancedColoringFields.fromD0ToInward_FocusTree,
},
{
val: adCoFromFocusToOutwardForFocusTreeBorders,
kind: AdvancedColoringFields.fromFocusToOutward_FocusTree,
},
{
val: adCoFromFocusToInwardForAllBorders,
kind: AdvancedColoringFields.fromFocusToInward_All,
},
];
const advancedColoringSettingsOfBackgrounds = [
{
val: adCoFromDepth0ToInwardForAllBackgrounds,
kind: AdvancedColoringFields.fromD0ToInward_All,
},
{
val: adCoFromFocusToOutwardForAllBackgrounds,
kind: AdvancedColoringFields.fromFocusToOutward_All,
},
{
val: adCoFromDepth0ToInwardForFocusTreeBackgrounds,
kind: AdvancedColoringFields.fromD0ToInward_FocusTree,
},
{
val: adCoFromFocusToOutwardForFocusTreeBackgrounds,
kind: AdvancedColoringFields.fromFocusToOutward_FocusTree,
},
{
val: adCoFromFocusToInwardForAllBackgrounds,
kind: AdvancedColoringFields.fromFocusToInward_All,
},
];
const processAC = (
arr: {
val: string | undefined;
kind: AdvancedColoringFields;
}[],
tempTransparent?: "back",
): {
priority: number;
sequence: string[];
kind: AdvancedColoringFields;
}[] => {
return arr
.map((x) => ({
kind: x.kind,
val: generateOneChainOfColorsForEachDepth(
x.val,
tempTransparent,
),
}))
.filter((x) => !!x.val)
.map((x) => ({
priority: x.val!.priority,
sequence: x.val!.sequence,
kind: x.kind,
}))
.sort((a, b) => b.priority - a.priority); // descending order
};
glo.coloring.advanced.forBorders = processAC(
advancedColoringSettingsOfBorders,
);
glo.coloring.advanced.forBackgrounds = processAC(
advancedColoringSettingsOfBackgrounds,
"back",
);
// ..........
}; | the_stack |
import React, { FC } from 'react';
import { Row, Col } from 'antd';
import {
StepBackwardOutlined,
StepForwardOutlined,
FastBackwardOutlined,
FastForwardOutlined,
ShrinkOutlined,
ArrowsAltOutlined,
DownOutlined,
UpOutlined,
LeftOutlined,
RightOutlined,
CaretUpOutlined,
CaretDownOutlined,
CaretLeftOutlined,
CaretRightOutlined,
UpCircleOutlined,
DownCircleOutlined,
LeftCircleOutlined,
RightCircleOutlined,
DoubleRightOutlined,
DoubleLeftOutlined,
VerticalLeftOutlined,
VerticalRightOutlined,
VerticalAlignTopOutlined,
VerticalAlignMiddleOutlined,
VerticalAlignBottomOutlined,
ForwardOutlined,
BackwardOutlined,
RollbackOutlined,
EnterOutlined,
RetweetOutlined,
SwapOutlined,
SwapLeftOutlined,
SwapRightOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
ArrowLeftOutlined,
ArrowRightOutlined,
PlayCircleOutlined,
UpSquareOutlined,
DownSquareOutlined,
LeftSquareOutlined,
RightSquareOutlined,
LoginOutlined,
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
BorderBottomOutlined,
BorderHorizontalOutlined,
BorderInnerOutlined,
BorderOuterOutlined,
BorderLeftOutlined,
BorderRightOutlined,
BorderTopOutlined,
BorderVerticleOutlined,
PicCenterOutlined,
PicLeftOutlined,
PicRightOutlined,
RadiusBottomleftOutlined,
RadiusBottomrightOutlined,
RadiusUpleftOutlined,
RadiusUprightOutlined,
FullscreenOutlined,
FullscreenExitOutlined,
QuestionOutlined,
QuestionCircleOutlined,
PlusOutlined,
PlusCircleOutlined,
PauseOutlined,
PauseCircleOutlined,
MinusOutlined,
MinusCircleOutlined,
PlusSquareOutlined,
MinusSquareOutlined,
InfoOutlined,
InfoCircleOutlined,
ExclamationOutlined,
ExclamationCircleOutlined,
CloseOutlined,
CloseCircleOutlined,
CloseSquareOutlined,
CheckOutlined,
CheckCircleOutlined,
CheckSquareOutlined,
ClockCircleOutlined,
WarningOutlined,
IssuesCloseOutlined,
StopOutlined,
EditOutlined,
FormOutlined,
CopyOutlined,
ScissorOutlined,
DeleteOutlined,
SnippetsOutlined,
DiffOutlined,
HighlightOutlined,
AlignCenterOutlined,
AlignLeftOutlined,
AlignRightOutlined,
BgColorsOutlined,
BoldOutlined,
ItalicOutlined,
UnderlineOutlined,
StrikethroughOutlined,
RedoOutlined,
UndoOutlined,
ZoomInOutlined,
ZoomOutOutlined,
FontColorsOutlined,
FontSizeOutlined,
LineHeightOutlined,
DashOutlined,
SmallDashOutlined,
SortAscendingOutlined,
SortDescendingOutlined,
DragOutlined,
OrderedListOutlined,
UnorderedListOutlined,
RadiusSettingOutlined,
ColumnWidthOutlined,
ColumnHeightOutlined,
AreaChartOutlined,
PieChartOutlined,
BarChartOutlined,
DotChartOutlined,
LineChartOutlined,
RadarChartOutlined,
HeatMapOutlined,
FallOutlined,
RiseOutlined,
StockOutlined,
BoxPlotOutlined,
FundOutlined,
SlidersOutlined,
AndroidOutlined,
AppleOutlined,
WindowsOutlined,
IeOutlined,
ChromeOutlined,
GithubOutlined,
AliwangwangOutlined,
DingdingOutlined,
WeiboSquareOutlined,
WeiboCircleOutlined,
TaobaoCircleOutlined,
Html5Outlined,
WeiboOutlined,
TwitterOutlined,
WechatOutlined,
YoutubeOutlined,
AlipayCircleOutlined,
TaobaoOutlined,
SkypeOutlined,
QqOutlined,
MediumWorkmarkOutlined,
GitlabOutlined,
MediumOutlined,
LinkedinOutlined,
GooglePlusOutlined,
DropboxOutlined,
FacebookOutlined,
CodepenOutlined,
CodeSandboxOutlined,
AmazonOutlined,
GoogleOutlined,
CodepenCircleOutlined,
AlipayOutlined,
AntDesignOutlined,
AntCloudOutlined,
AliyunOutlined,
ZhihuOutlined,
SlackOutlined,
SlackSquareOutlined,
BehanceOutlined,
BehanceSquareOutlined,
DribbbleOutlined,
DribbbleSquareOutlined,
InstagramOutlined,
YuqueOutlined,
AlibabaOutlined,
YahooOutlined,
RedditOutlined,
SketchOutlined,
AccountBookOutlined,
AimOutlined,
AlertOutlined,
ApartmentOutlined,
ApiOutlined,
AppstoreAddOutlined,
AppstoreOutlined,
AudioOutlined,
AudioMutedOutlined,
AuditOutlined,
BankOutlined,
BarcodeOutlined,
BarsOutlined,
BellOutlined,
BlockOutlined,
BookOutlined,
BorderOutlined,
BorderlessTableOutlined,
BranchesOutlined,
BugOutlined,
BuildOutlined,
BulbOutlined,
CalculatorOutlined,
CalendarOutlined,
CameraOutlined,
CarOutlined,
CarryOutOutlined,
CiCircleOutlined,
CiOutlined,
ClearOutlined,
CloudDownloadOutlined,
CloudOutlined,
CloudServerOutlined,
CloudSyncOutlined,
CloudUploadOutlined,
ClusterOutlined,
CodeOutlined,
CoffeeOutlined,
CommentOutlined,
CompassOutlined,
CompressOutlined,
ConsoleSqlOutlined,
ContactsOutlined,
ContainerOutlined,
ControlOutlined,
CopyrightCircleOutlined,
CopyrightOutlined,
CreditCardOutlined,
CrownOutlined,
CustomerServiceOutlined,
DashboardOutlined,
DatabaseOutlined,
DeleteColumnOutlined,
DeleteRowOutlined,
DeliveredProcedureOutlined,
DeploymentUnitOutlined,
DesktopOutlined,
DingtalkOutlined,
DisconnectOutlined,
DislikeOutlined,
DollarCircleOutlined,
DollarOutlined,
DownloadOutlined,
EllipsisOutlined,
EnvironmentOutlined,
EuroCircleOutlined,
EuroOutlined,
ExceptionOutlined,
ExpandAltOutlined,
ExpandOutlined,
ExperimentOutlined,
ExportOutlined,
EyeOutlined,
EyeInvisibleOutlined,
FieldBinaryOutlined,
FieldNumberOutlined,
FieldStringOutlined,
FieldTimeOutlined,
FileAddOutlined,
FileDoneOutlined,
FileExcelOutlined,
FileExclamationOutlined,
FileOutlined,
FileGifOutlined,
FileImageOutlined,
FileJpgOutlined,
FileMarkdownOutlined,
FilePdfOutlined,
FilePptOutlined,
FileProtectOutlined,
FileSearchOutlined,
FileSyncOutlined,
FileTextOutlined,
FileUnknownOutlined,
FileWordOutlined,
FileZipOutlined,
FilterOutlined,
FireOutlined,
FlagOutlined,
FolderAddOutlined,
FolderOutlined,
FolderOpenOutlined,
FolderViewOutlined,
ForkOutlined,
FormatPainterOutlined,
FrownOutlined,
FunctionOutlined,
FundProjectionScreenOutlined,
FundViewOutlined,
FunnelPlotOutlined,
GatewayOutlined,
GifOutlined,
GiftOutlined,
GlobalOutlined,
GoldOutlined,
GroupOutlined,
HddOutlined,
HeartOutlined,
HistoryOutlined,
HomeOutlined,
HourglassOutlined,
IdcardOutlined,
ImportOutlined,
InboxOutlined,
InsertRowAboveOutlined,
InsertRowBelowOutlined,
InsertRowLeftOutlined,
InsertRowRightOutlined,
InsuranceOutlined,
InteractionOutlined,
KeyOutlined,
LaptopOutlined,
LayoutOutlined,
LikeOutlined,
LineOutlined,
LinkOutlined,
Loading3QuartersOutlined,
LoadingOutlined,
LockOutlined,
MacCommandOutlined,
MailOutlined,
ManOutlined,
MedicineBoxOutlined,
MehOutlined,
MenuOutlined,
MergeCellsOutlined,
MessageOutlined,
MobileOutlined,
MoneyCollectOutlined,
MonitorOutlined,
MoreOutlined,
NodeCollapseOutlined,
NodeExpandOutlined,
NodeIndexOutlined,
NotificationOutlined,
NumberOutlined,
OneToOneOutlined,
PaperClipOutlined,
PartitionOutlined,
PayCircleOutlined,
PercentageOutlined,
PhoneOutlined,
PictureOutlined,
PlaySquareOutlined,
PoundCircleOutlined,
PoundOutlined,
PoweroffOutlined,
PrinterOutlined,
ProfileOutlined,
ProjectOutlined,
PropertySafetyOutlined,
PullRequestOutlined,
PushpinOutlined,
QrcodeOutlined,
ReadOutlined,
ReconciliationOutlined,
RedEnvelopeOutlined,
ReloadOutlined,
RestOutlined,
RobotOutlined,
RocketOutlined,
RotateLeftOutlined,
RotateRightOutlined,
SafetyCertificateOutlined,
SafetyOutlined,
SaveOutlined,
ScanOutlined,
ScheduleOutlined,
SearchOutlined,
SecurityScanOutlined,
SelectOutlined,
SendOutlined,
SettingOutlined,
ShakeOutlined,
ShareAltOutlined,
ShopOutlined,
ShoppingCartOutlined,
ShoppingOutlined,
SisternodeOutlined,
SkinOutlined,
SmileOutlined,
SolutionOutlined,
SoundOutlined,
SplitCellsOutlined,
StarOutlined,
SubnodeOutlined,
SwitcherOutlined,
SyncOutlined,
TableOutlined,
TabletOutlined,
TagOutlined,
TagsOutlined,
TeamOutlined,
ThunderboltOutlined,
ToTopOutlined,
ToolOutlined,
TrademarkCircleOutlined,
TrademarkOutlined,
TransactionOutlined,
TranslationOutlined,
TrophyOutlined,
UngroupOutlined,
UnlockOutlined,
UploadOutlined,
UsbOutlined,
UserAddOutlined,
UserDeleteOutlined,
UserOutlined,
UserSwitchOutlined,
UsergroupAddOutlined,
UsergroupDeleteOutlined,
VerifiedOutlined,
VideoCameraAddOutlined,
VideoCameraOutlined,
WalletOutlined,
WhatsAppOutlined,
WifiOutlined,
WomanOutlined,
} from '@ant-design/icons';
// import styles from './style.less';
const IconSymbol: FC = () => {
return (
<Row>
{/*<CaretUpOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/1.CaretUpOutlined'}*/}
{/*/>*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.MailOutlined'}*/}
{/*/>*/}
{/*<StepBackwardOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
{/*/>*/}
{/*<StepForwardOutlined*/}
{/* className="icon"*/}
{/* symbolName={'1.General/2.Icons/2.StepBackwardOutlined'}*/}
{/*/>*/}
<StepForwardOutlined />
<ShrinkOutlined />
<ArrowsAltOutlined />
<DownOutlined />
<UpOutlined />
<LeftOutlined />
<RightOutlined />
<CaretUpOutlined />
<CaretDownOutlined />
<CaretLeftOutlined />
<CaretRightOutlined />
<VerticalAlignTopOutlined />
<RollbackOutlined />
<FastBackwardOutlined />
<FastForwardOutlined />
<DoubleRightOutlined />
<DoubleLeftOutlined />
<VerticalLeftOutlined />
<VerticalRightOutlined />
<VerticalAlignMiddleOutlined />
<VerticalAlignBottomOutlined />
<ForwardOutlined />
<BackwardOutlined />
<EnterOutlined />
<RetweetOutlined />
<SwapOutlined />
<SwapLeftOutlined />
<SwapRightOutlined />
<ArrowUpOutlined />
<ArrowDownOutlined />
<ArrowLeftOutlined />
<ArrowRightOutlined />
<LoginOutlined />
<LogoutOutlined />
<MenuFoldOutlined />
<MenuUnfoldOutlined />
<BorderBottomOutlined />
<BorderHorizontalOutlined />
<BorderInnerOutlined />
<BorderOuterOutlined />
<BorderLeftOutlined />
<BorderRightOutlined />
<BorderTopOutlined />
<BorderVerticleOutlined />
<PicCenterOutlined />
<PicLeftOutlined />
<PicRightOutlined />
<RadiusBottomleftOutlined />
<RadiusBottomrightOutlined />
<RadiusUpleftOutlined />
<RadiusUprightOutlined />
<FullscreenOutlined />
<FullscreenExitOutlined />
<QuestionOutlined />
<PauseOutlined />
<MinusOutlined />
<PauseCircleOutlined />
<InfoOutlined />
<CloseOutlined />
<ExclamationOutlined />
<CheckOutlined />
<WarningOutlined />
<IssuesCloseOutlined />
<StopOutlined />
<EditOutlined />
<CopyOutlined />
<ScissorOutlined />
<DeleteOutlined />
<SnippetsOutlined />
<DiffOutlined />
<HighlightOutlined />
<AlignCenterOutlined />
<AlignLeftOutlined />
<AlignRightOutlined />
<BgColorsOutlined />
<BoldOutlined />
<ItalicOutlined />
<UnderlineOutlined />
<StrikethroughOutlined />
<RedoOutlined />
<UndoOutlined />
<ZoomInOutlined />
<ZoomOutOutlined />
<FontColorsOutlined />
<FontSizeOutlined />
<LineHeightOutlined />
<SortAscendingOutlined />
<SortDescendingOutlined />
<DragOutlined />
<OrderedListOutlined />
<UnorderedListOutlined />
<RadiusSettingOutlined />
<ColumnWidthOutlined />
<ColumnHeightOutlined />
<AreaChartOutlined />
<PieChartOutlined />
<BarChartOutlined />
<DotChartOutlined />
<LineChartOutlined />
<RadarChartOutlined />
<HeatMapOutlined />
<FallOutlined />
<RiseOutlined />
<StockOutlined />
<BoxPlotOutlined />
<FundOutlined />
<SlidersOutlined />
<AndroidOutlined />
<AppleOutlined />
<WindowsOutlined />
<IeOutlined />
<ChromeOutlined />
<GithubOutlined />
<AliwangwangOutlined />
<DingdingOutlined />
<WeiboSquareOutlined />
<WeiboCircleOutlined />
<TaobaoCircleOutlined />
<Html5Outlined />
<WeiboOutlined />
<TwitterOutlined />
<WechatOutlined />
<AlipayCircleOutlined />
<TaobaoOutlined />
<SkypeOutlined />
<FacebookOutlined />
<CodepenOutlined />
<CodeSandboxOutlined />
<AmazonOutlined />
<GoogleOutlined />
<AlipayOutlined />
<AntDesignOutlined />
<AntCloudOutlined />
<ZhihuOutlined />
<SlackOutlined />
<SlackSquareOutlined />
<BehanceSquareOutlined />
<DribbbleOutlined />
<DribbbleSquareOutlined />
<InstagramOutlined />
<YuqueOutlined />
<AlibabaOutlined />
<YahooOutlined />
<RedditOutlined />
<SketchOutlined />
<AccountBookOutlined />
<AlertOutlined />
<ApartmentOutlined />
<ApiOutlined />
<QqOutlined />
<MediumWorkmarkOutlined />
<GitlabOutlined />
<MediumOutlined />
<GooglePlusOutlined />
<AppstoreAddOutlined />
<AppstoreOutlined />
<AudioOutlined />
<AudioMutedOutlined />
<AuditOutlined />
<BankOutlined />
<BarcodeOutlined />
<BarsOutlined />
<BellOutlined />
<BlockOutlined />
<BookOutlined />
<BorderOutlined />
<BranchesOutlined />
<BuildOutlined />
<BulbOutlined />
<CalculatorOutlined />
<CalendarOutlined />
<CameraOutlined />
<CarOutlined />
<CarryOutOutlined />
<CiCircleOutlined />
<CiOutlined />
<CloudOutlined />
<ClearOutlined />
<ClusterOutlined />
<CodeOutlined />
<CoffeeOutlined />
<CompassOutlined />
<CompressOutlined />
<ContactsOutlined />
<ContainerOutlined />
<ControlOutlined />
<CopyrightCircleOutlined />
<CopyrightOutlined />
<CreditCardOutlined />
<CrownOutlined />
<CustomerServiceOutlined />
<DashboardOutlined />
<DatabaseOutlined />
<DeleteColumnOutlined />
<DeleteRowOutlined />
<DisconnectOutlined />
<DislikeOutlined />
<DollarCircleOutlined />
<DollarOutlined />
<DownloadOutlined />
<EllipsisOutlined />
<EnvironmentOutlined />
<EuroCircleOutlined />
<EuroOutlined />
<ExceptionOutlined />
<ExpandAltOutlined />
<ExpandOutlined />
<ExperimentOutlined />
<ExportOutlined />
<EyeOutlined />
<FieldBinaryOutlined />
<FieldNumberOutlined />
<FieldStringOutlined />
<DesktopOutlined />
<DingtalkOutlined />
<FileAddOutlined />
<FileDoneOutlined />
<FileExcelOutlined />
<FileExclamationOutlined />
<FileOutlined />
<FileImageOutlined />
<FileJpgOutlined />
<FileMarkdownOutlined />
<FilePdfOutlined />
<FilePptOutlined />
<FileProtectOutlined />
<FileSearchOutlined />
<FileSyncOutlined />
<FileTextOutlined />
<FileUnknownOutlined />
<FileWordOutlined />
<FilterOutlined />
<FireOutlined />
<FlagOutlined />
<FolderAddOutlined />
<FolderOutlined />
<FolderOpenOutlined />
<ForkOutlined />
<FormatPainterOutlined />
<FrownOutlined />
<FunctionOutlined />
<FunnelPlotOutlined />
<GatewayOutlined />
<GifOutlined />
<GiftOutlined />
<GlobalOutlined />
<GoldOutlined />
<GroupOutlined />
<HddOutlined />
<HeartOutlined />
<HistoryOutlined />
<HomeOutlined />
<HourglassOutlined />
<IdcardOutlined />
<ImportOutlined />
<InboxOutlined />
<InsertRowAboveOutlined />
<InsertRowBelowOutlined />
<InsertRowLeftOutlined />
<InsertRowRightOutlined />
<InsuranceOutlined />
<InteractionOutlined />
<KeyOutlined />
<LaptopOutlined />
<LayoutOutlined />
<LikeOutlined />
<LineOutlined />
<LinkOutlined />
<Loading3QuartersOutlined />
<LoadingOutlined />
<LockOutlined />
<MailOutlined />
<ManOutlined />
<MedicineBoxOutlined />
<MehOutlined />
<MenuOutlined />
<MergeCellsOutlined />
<MessageOutlined />
<MobileOutlined />
<MoneyCollectOutlined />
<MonitorOutlined />
<MoreOutlined />
<NodeCollapseOutlined />
<NodeExpandOutlined />
<NodeIndexOutlined />
<NotificationOutlined />
<NumberOutlined />
<PaperClipOutlined />
<PartitionOutlined />
<PayCircleOutlined />
<PercentageOutlined />
<PhoneOutlined />
<PictureOutlined />
<PoundCircleOutlined />
<PoundOutlined />
<PoweroffOutlined />
<PrinterOutlined />
<ProfileOutlined />
<ProjectOutlined />
<PropertySafetyOutlined />
<PullRequestOutlined />
<PushpinOutlined />
<QrcodeOutlined />
<ReadOutlined />
<ReconciliationOutlined />
<RedEnvelopeOutlined />
<ReloadOutlined />
<RestOutlined />
<RobotOutlined />
<RocketOutlined />
<SafetyCertificateOutlined />
<SafetyOutlined />
<ScanOutlined />
<ScheduleOutlined />
<SearchOutlined />
<SecurityScanOutlined />
<SelectOutlined />
<SendOutlined />
<SettingOutlined />
<ShakeOutlined />
<ShareAltOutlined />
<ShopOutlined />
<ShoppingCartOutlined />
<ShoppingOutlined />
<SisternodeOutlined />
<SkinOutlined />
<SmileOutlined />
<SolutionOutlined />
<SoundOutlined />
<SplitCellsOutlined />
<StarOutlined />
<SubnodeOutlined />
<SyncOutlined />
<TableOutlined />
<TabletOutlined />
<TagOutlined />
<TagsOutlined />
<TeamOutlined />
<ThunderboltOutlined />
<ToTopOutlined />
<ToolOutlined />
<TrademarkCircleOutlined />
<TrademarkOutlined />
<TransactionOutlined />
<TrophyOutlined />
<UngroupOutlined />
<UnlockOutlined />
<UploadOutlined />
<UsbOutlined />
<UserAddOutlined />
<UserDeleteOutlined />
<UserOutlined />
<UserSwitchOutlined />
<UsergroupAddOutlined />
<UsergroupDeleteOutlined />
<VideoCameraOutlined />
<WalletOutlined />
<WifiOutlined />
<BorderlessTableOutlined />
<WomanOutlined />
<BehanceOutlined />
<DropboxOutlined />
<DeploymentUnitOutlined />
<UpCircleOutlined />
<DownCircleOutlined />
<LeftCircleOutlined />
<RightCircleOutlined />
<UpSquareOutlined />
<DownSquareOutlined />
<LeftSquareOutlined />
<RightSquareOutlined />
<PlayCircleOutlined />
<QuestionCircleOutlined />
<PlusCircleOutlined />
<PlusSquareOutlined />
<MinusSquareOutlined />
<MinusCircleOutlined />
<InfoCircleOutlined />
<ExclamationCircleOutlined />
<CloseCircleOutlined />
<CloseSquareOutlined />
<CheckCircleOutlined />
<CheckSquareOutlined />
<ClockCircleOutlined />
<FormOutlined />
<DashOutlined />
<SmallDashOutlined />
<YoutubeOutlined />
<CodepenCircleOutlined />
<AliyunOutlined />
<PlusOutlined />
<LinkedinOutlined />
<AimOutlined />
<BugOutlined />
<CloudDownloadOutlined />
<CloudServerOutlined />
<CloudSyncOutlined />
<CloudUploadOutlined />
<CommentOutlined />
<ConsoleSqlOutlined />
<EyeInvisibleOutlined />
<FileGifOutlined />
<DeliveredProcedureOutlined />
<FieldTimeOutlined />
<FileZipOutlined />
<FolderViewOutlined />
<FundProjectionScreenOutlined />
<FundViewOutlined />
<MacCommandOutlined />
<PlaySquareOutlined />
<OneToOneOutlined />
<RotateLeftOutlined />
<RotateRightOutlined />
<SaveOutlined />
<SwitcherOutlined />
<TranslationOutlined />
<VerifiedOutlined />
<VideoCameraAddOutlined />
<WhatsAppOutlined />
{/*</Col>*/}
</Row>
);
};
export default IconSymbol; | the_stack |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, settled } from '@ember/test-helpers';
import type { TestContext as BaseContext } from 'ember-test-helpers';
import Service, { inject as service } from '@ember/service';
import { hbs } from 'ember-cli-htmlbars';
import Modifier, { ModifierArgs } from 'ember-modifier';
import ClassBasedModifier from 'ember-modifier';
// `any` required for the inference to work correctly here
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ConstructorFor<C> = new (...args: any[]) => C;
type Factory = (
callback: (hookName: string, instance: ClassBasedModifier) => void
) => ConstructorFor<ClassBasedModifier>;
interface HookSetup {
name: string;
insert: boolean;
update: boolean;
destroy: boolean;
element: boolean;
factory: Factory;
}
interface Context extends BaseContext {
instance: null | ClassBasedModifier;
assertCalled(
shouldCall: boolean,
assertion: () => void | Promise<void>
): Promise<void>;
hook(assertions: (instance: ClassBasedModifier) => void): void;
}
function testHook({
name,
insert,
update,
destroy,
element,
factory,
}: HookSetup): void {
module(`\`${name}\` hook`, function (hooks) {
hooks.beforeEach(function (this: Context, assert) {
this.instance = null;
let called = (): void => {
assert.ok(false, `\`${name}\` hook was called unexpectedly`);
};
this.hook = (assertions) => {
const callback = (
hookName: string,
instance: ClassBasedModifier
): void => {
this.instance = instance;
if (hookName === name) {
called();
assert.strictEqual(
instance.isDestroying,
name === 'willDestroy',
'isDestroying'
);
assert.strictEqual(instance.isDestroyed, false, 'isDestroyed');
assertions(instance);
}
};
this.owner.register('modifier:songbird', factory(callback));
};
this.assertCalled = async (shouldCall, callback) => {
let count = 0;
const _called = called;
if (shouldCall) {
called = () => count++;
}
try {
await callback();
} finally {
if (shouldCall) {
assert.equal(
count,
1,
`Expected \`${name}\` hook to be called exactly once`
);
}
called = _called;
}
};
});
hooks.afterEach(async function (this: Context, assert) {
await settled();
assert.strictEqual(this.instance?.isDestroying, true, 'isDestroying');
assert.strictEqual(this.instance?.isDestroyed, true, 'isDestroyed');
});
if (element) {
test('it has access to the DOM element', async function (this: Context, assert) {
this.hook((instance) => {
assert.equal(instance.element.tagName, 'H1', 'this.element.tagName');
assert.equal(instance.element.id, 'expected', 'this.element.id');
});
assert.step('no-op render');
await this.assertCalled(false, async () => {
this.setProperties({
isShowing: false,
foo: 'foo',
});
await render(hbs`
{{#if this.isShowing}}
<h1 id="expected" {{songbird this.foo}}>Hello</h1>
{{/if}}
`);
});
assert.step('insert');
await this.assertCalled(insert, () => {
this.set('isShowing', true);
});
assert.step('update');
await this.assertCalled(update, () => {
this.set('foo', 'FOO');
});
assert.step('destroy');
await this.assertCalled(destroy, () => {
this.set('isShowing', false);
});
assert.verifySteps(['no-op render', 'insert', 'update', 'destroy']);
});
} else {
test('it does not have access to the DOM element', async function (this: Context, assert) {
this.hook((instance) => {
assert.strictEqual(instance.element, null, 'this.element');
});
assert.step('no-op render');
await this.assertCalled(false, async () => {
this.setProperties({
isShowing: false,
foo: 'foo',
});
await render(hbs`
{{#if this.isShowing}}
<h1 id="expected" {{songbird this.foo}}>Hello</h1>
{{/if}}
`);
});
assert.step('insert');
await this.assertCalled(insert, () => {
this.set('isShowing', true);
});
assert.step('update');
await this.assertCalled(update, () => {
this.set('foo', 'FOO');
});
assert.step('destroy');
await this.assertCalled(destroy, () => {
this.set('isShowing', false);
});
assert.verifySteps(['no-op render', 'insert', 'update', 'destroy']);
});
}
test('has access to positional arguments', async function (this: Context, assert) {
let expected: string[];
this.hook((instance) => {
assert.deepEqual(
instance.args.positional,
expected,
'this.args.positional'
);
});
assert.step('no-op render');
await this.assertCalled(false, async () => {
this.setProperties({
isShowing: false,
foo: 'foo',
bar: 'bar',
});
await render(hbs`
{{#if this.isShowing}}
<h1 id="expected" {{songbird this.foo this.bar}}>Hello</h1>
{{/if}}
`);
});
assert.step('insert');
expected = ['foo', 'bar'];
await this.assertCalled(insert, () => {
this.set('isShowing', true);
});
assert.step('update 1');
expected = ['FOO', 'bar'];
await this.assertCalled(update, () => {
this.set('foo', 'FOO');
});
assert.step('update 2');
expected = ['FOO', 'BAR'];
await this.assertCalled(update, () => {
this.set('bar', 'BAR');
});
assert.step('destroy');
await this.assertCalled(destroy, () => {
this.set('isShowing', false);
});
assert.verifySteps([
'no-op render',
'insert',
'update 1',
'update 2',
'destroy',
]);
});
test('has access to named arguments', async function (this: Context, assert) {
let expected: Record<string, string>;
this.hook((instance) => {
assert.deepEqual(
{ ...instance.args.named },
expected,
'this.args.named'
);
});
assert.step('no-op render');
await this.assertCalled(false, async () => {
this.setProperties({
isShowing: false,
foo: 'foo',
bar: 'bar',
});
await render(hbs`
{{#if this.isShowing}}
<h1 id="expected" {{songbird foo=this.foo bar=this.bar}}>Hello</h1>
{{/if}}
`);
});
assert.step('insert');
expected = { foo: 'foo', bar: 'bar' };
await this.assertCalled(insert, () => {
this.set('isShowing', true);
});
assert.step('update 1');
expected = { foo: 'FOO', bar: 'bar' };
await this.assertCalled(update, () => {
this.set('foo', 'FOO');
});
assert.step('update 2');
expected = { foo: 'FOO', bar: 'BAR' };
await this.assertCalled(update, () => {
this.set('bar', 'BAR');
});
assert.step('destroy');
await this.assertCalled(destroy, () => {
this.set('isShowing', false);
});
assert.verifySteps([
'no-op render',
'insert',
'update 1',
'update 2',
'destroy',
]);
});
});
}
function testHooksOrdering(factory: Factory): void {
module('hooks ordering', function () {
test('hooks are fired in the right order', async function (assert) {
let actualHooks: undefined | string[];
const callback = (name: string): void => {
if (actualHooks) {
actualHooks.push(name);
} else {
assert.ok(false, `\`${name}\` hook was called unexpectedly`);
}
};
async function assertHooks(
expectedHooks: string[],
callback: () => void | Promise<void>
): Promise<void> {
actualHooks = [];
try {
await callback();
} finally {
assert.deepEqual(actualHooks, expectedHooks, 'hooks');
actualHooks = undefined;
}
}
this.owner.register('modifier:songbird', factory(callback));
assert.step('no-op render');
await assertHooks([], async () => {
this.setProperties({
isShowing: false,
foo: 'foo',
bar: 'bar',
});
await render(hbs`
{{#if this.isShowing}}
<h1 id="expected" {{songbird this.foo bar=this.bar}}>Hello</h1>
{{/if}}
`);
});
assert.step('insert');
await assertHooks(
['constructor', 'didReceiveArguments', 'didInstall'],
() => {
this.set('isShowing', true);
}
);
assert.step('update 1');
await assertHooks(['didUpdateArguments', 'didReceiveArguments'], () => {
this.set('foo', 'FOO');
});
assert.step('update 2');
await assertHooks(['didUpdateArguments', 'didReceiveArguments'], () => {
this.set('bar', 'BAR');
});
assert.step('destroy');
await assertHooks(['willDestroy'], () => {
this.set('isShowing', false);
});
assert.verifySteps([
'no-op render',
'insert',
'update 1',
'update 2',
'destroy',
]);
});
});
}
function testHooks(factory: Factory): void {
testHook({
name: 'constructor',
insert: true,
update: false,
destroy: false,
element: false,
factory,
});
testHook({
name: 'didReceiveArguments',
insert: true,
update: true,
destroy: false,
element: true,
factory,
});
testHook({
name: 'didUpdateArguments',
insert: false,
update: true,
destroy: false,
element: true,
factory,
});
testHook({
name: 'didInstall',
insert: true,
update: false,
destroy: false,
element: true,
factory,
});
testHook({
name: 'willDestroy',
insert: false,
update: false,
destroy: true,
element: true,
factory,
});
testHooksOrdering(factory);
}
module(
'Integration | Modifier Manager | class-based modifier',
function (hooks) {
setupRenderingTest(hooks);
testHooks(
(callback) =>
class NativeModifier extends Modifier {
constructor(owner: unknown, args: ModifierArgs) {
super(owner, args);
callback('constructor', this);
}
didReceiveArguments(): void {
callback('didReceiveArguments', this);
}
didUpdateArguments(): void {
callback('didUpdateArguments', this);
}
didInstall(): void {
callback('didInstall', this);
}
willDestroy(): void {
callback('willDestroy', this);
}
}
);
module('service injection', function () {
test('can participate in ember dependency injection', async function (this: Context, assert) {
let called = false;
class Foo extends Service {
isFooService = true;
}
class Bar extends Service {
isBarService = true;
}
this.owner.register('service:foo', Foo);
this.owner.register('service:bar', Bar);
class NativeModifier extends Modifier {
@service foo!: Foo;
// SAFETY: we're not using the registry here for convenience, because we
// cannot extend it anywhere but at the top level of the module. The
// cast is safe because of the registration of `service:bar` above.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@service('bar' as any) baz!: Bar;
constructor(owner: unknown, args: ModifierArgs) {
super(owner, args);
called = true;
assert.strictEqual(
this.foo.isFooService,
true,
'this.foo.isFooService'
);
assert.strictEqual(
this.baz.isBarService,
true,
'this.baz.isBarService'
);
}
}
this.owner.register('modifier:songbird', NativeModifier);
await render(hbs`<h1 {{songbird}}>Hello</h1>`);
assert.strictEqual(called, true, 'constructor called');
});
});
}
); | the_stack |
export function bitsToBytes(n: number) {
return n >> 3;
}
export function bytesToBits(n: number) {
return n << 3;
}
export function roundUp(n: number, denom: number) {
return n + (denom - n % denom) % denom;
}
var padLength = function(len: number) {
return bitsToBytes(roundUp(bytesToBits(len) + 1 + 64, 512));
};
// asm.js-style implementation of SHA-1, taken from
// Rusha (https://github.com/srijs/rusha)
//
// As described in the Rusha documentation, this is a textbook
// implementation of SHA-1 with some loop unrolling
//
// Node.js note: The performance of this implementation is very
// much dependent upon the performance of typed arrays in
// the JS engine. Node.js v0.11 performs >2x faster than Node.js v0.10
// due to the use of 'native' typed array support in V8.
var sha1core = function(stdlib: any, foreign: any, heap: any): any {
// FIXME - The 'use asm' directive here causes a
// "'sha1Core' is not a constructor" error when tested
// under Firefox 28. The code is still compiled with asm.js when
// this directive is removed but the code then functions correctly
// so it is commented out.
//
//"use asm";
var H: Int32Array = new stdlib.Int32Array(heap);
function hash(k: number) {
k = k | 0;
var i = 0,
j = 0,
y0 = 0,
z0 = 0,
y1 = 0,
z1 = 0,
y2 = 0,
z2 = 0,
y3 = 0,
z3 = 0,
y4 = 0,
z4 = 0,
t0 = 0,
t1 = 0;
y0 = H[((k + 0) << 2) >> 2] | 0;
y1 = H[((k + 1) << 2) >> 2] | 0;
y2 = H[((k + 2) << 2) >> 2] | 0;
y3 = H[((k + 3) << 2) >> 2] | 0;
y4 = H[((k + 4) << 2) >> 2] | 0;
for (i = 0; (i | 0) < (k | 0); i = (i + 16) | 0) {
z0 = y0;
z1 = y1;
z2 = y2;
z3 = y3;
z4 = y4;
for (j = 0; (j | 0) < 16; j = (j + 1) | 0) {
t1 = H[((i + j) << 2) >> 2] | 0;
t0 =
(((((y0 << 5) | (y0 >>> 27)) + ((y1 & y2) | (~y1 & y3))) |
0) +
((((t1 + y4) | 0) + 1518500249) | 0)) |
0;
y4 = y3;
y3 = y2;
y2 = (y1 << 30) | (y1 >>> 2);
y1 = y0;
y0 = t0;
H[((k + j) << 2) >> 2] = t1;
}
for (j = (k + 16) | 0; (j | 0) < ((k + 20) | 0); j = (j + 1) | 0) {
t1 =
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) <<
1) |
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) >>>
31);
t0 =
(((((y0 << 5) | (y0 >>> 27)) + ((y1 & y2) | (~y1 & y3))) |
0) +
((((t1 + y4) | 0) + 1518500249) | 0)) |
0;
y4 = y3;
y3 = y2;
y2 = (y1 << 30) | (y1 >>> 2);
y1 = y0;
y0 = t0;
H[(j << 2) >> 2] = t1;
}
for (j = (k + 20) | 0; (j | 0) < ((k + 40) | 0); j = (j + 1) | 0) {
t1 =
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) <<
1) |
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) >>>
31);
t0 =
(((((y0 << 5) | (y0 >>> 27)) + (y1 ^ y2 ^ y3)) | 0) +
((((t1 + y4) | 0) + 1859775393) | 0)) |
0;
y4 = y3;
y3 = y2;
y2 = (y1 << 30) | (y1 >>> 2);
y1 = y0;
y0 = t0;
H[(j << 2) >> 2] = t1;
}
for (j = (k + 40) | 0; (j | 0) < ((k + 60) | 0); j = (j + 1) | 0) {
t1 =
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) <<
1) |
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) >>>
31);
t0 =
(((((y0 << 5) | (y0 >>> 27)) +
((y1 & y2) | (y1 & y3) | (y2 & y3))) |
0) +
((((t1 + y4) | 0) - 1894007588) | 0)) |
0;
y4 = y3;
y3 = y2;
y2 = (y1 << 30) | (y1 >>> 2);
y1 = y0;
y0 = t0;
H[(j << 2) >> 2] = t1;
}
for (j = (k + 60) | 0; (j | 0) < ((k + 80) | 0); j = (j + 1) | 0) {
t1 =
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) <<
1) |
((H[((j - 3) << 2) >> 2] ^
H[((j - 8) << 2) >> 2] ^
H[((j - 14) << 2) >> 2] ^
H[((j - 16) << 2) >> 2]) >>>
31);
t0 =
(((((y0 << 5) | (y0 >>> 27)) + (y1 ^ y2 ^ y3)) | 0) +
((((t1 + y4) | 0) - 899497514) | 0)) |
0;
y4 = y3;
y3 = y2;
y2 = (y1 << 30) | (y1 >>> 2);
y1 = y0;
y0 = t0;
H[(j << 2) >> 2] = t1;
}
y0 = (y0 + z0) | 0;
y1 = (y1 + z1) | 0;
y2 = (y2 + z2) | 0;
y3 = (y3 + z3) | 0;
y4 = (y4 + z4) | 0;
}
H[0] = y0;
H[1] = y1;
H[2] = y2;
H[3] = y3;
H[4] = y4;
}
return { hash: hash };
};
/** Generic cryptographic hash interface.
*
* The hash() function takes a typed array
* as input and writes the result to a typed array output buffer
* to avoid allocating a new buffer on each call, this improves
* performance when using the same hashing function large numbers
* of times on short inputs, as is the case in PBKDF2 for example.
*/
export interface Hash {
hash(src: Uint8Array, digest: Int32Array): void;
blockSize(): number;
digestLen(): number;
}
export class SHA1 implements Hash {
private heap32: Int32Array;
private dataView: DataView;
private core: any; // sha1core() instance
constructor() {
this.initHeap(32);
}
blockSize(): number {
return 64;
}
digestLen(): number {
return 20;
}
private initHeap(msgSize: number) {
var WORK_SPACE_LEN = 320;
var heapSize = padLength(msgSize) + WORK_SPACE_LEN;
if (!this.heap32 || heapSize > this.heap32.byteLength) {
this.heap32 = new Int32Array(heapSize >> 2);
this.dataView = new DataView(this.heap32.buffer);
var stdlib = { Int32Array: Int32Array };
this.core = sha1core(
stdlib,
null /* foreign - unused */,
this.heap32.buffer
);
}
}
private static copyMsgToBe32(
dest: Int32Array,
src: Uint8Array,
srcLen: number
) {
var words = (srcLen - 1) / 4 + 1;
for (var word = 0; word < words - 1; word++) {
dest[word] =
(src[word * 4] << 24) |
(src[word * 4 + 1] << 16) |
(src[word * 4 + 2] << 8) |
src[word * 4 + 3];
}
var shift = (srcLen % 4 - 1) * 8;
for (var i = srcLen - srcLen % 4; i < srcLen; i++) {
dest[words - 1] |= src[i] << shift;
shift -= 8;
}
}
hash(src: Uint8Array, digest: Int32Array) {
var srcLen = src.byteLength;
this.initHeap(srcLen);
var paddedLength = padLength(srcLen);
var i = 0;
// pad message with zeroes
for (i = 0; i < paddedLength >> 2; i++) {
this.heap32[i] = 0;
}
// copy message to heap in 32-bit big-endian
// words
SHA1.copyMsgToBe32(this.heap32, src, srcLen);
// append bit '1' to msg
this.heap32[srcLen >> 2] |= 0x80 << (24 - ((srcLen % 4) << 3));
// append message length in bits as a 64bit big-endian int
//this.heap32[(srcLen >> 2) + 2] = bytesToBits(srcLen);
// TODO - Understand where msgLenPos comes from
var msgLenPos = (((srcLen >> 2) + 2) & ~0x0f) + 15;
this.heap32[msgLenPos] = srcLen << 3;
// final message size should now be a multiple of 64 bytes
// (512 bits, 16 i32 words)
// initialize working state - stored at the end of the heap
// after the message
var workSpace = paddedLength >> 2;
this.heap32[workSpace] = 1732584193;
this.heap32[workSpace + 1] = -271733879;
this.heap32[workSpace + 2] = -1732584194;
this.heap32[workSpace + 3] = 271733878;
this.heap32[workSpace + 4] = -1009589776;
// call Rusha core
var msgWords = paddedLength >> 2;
this.core.hash(msgWords);
// copy result to digest
for (i = 0; i < 5; i++) {
digest[i] = this.dataView.getInt32(i << 2, false /* big endian */);
}
}
} | the_stack |
import * as React from "react";
import { mount, configure } from "enzyme";
import * as Adapter from 'enzyme-adapter-react-16';
import { FileBrowser } from "../../../src/controls/filePicker/controls/FileBrowser/FileBrowser";
import { MockFileBrowserService } from "../../mock/services/MockFileBrowserService";
import { IFile } from "../../../src/services/FileBrowserService.types";
import { assert } from "chai";
configure({ adapter: new Adapter() });
describe("<FileBrowser />", ()=>{
test("should render loading animation", async ()=>{
//The purpose of this test is to make sure we will see the loading animation before anything else.
let mockFileBrowserService: MockFileBrowserService = new MockFileBrowserService();
let component = mount(<FileBrowser
fileBrowserService={mockFileBrowserService as any}
libraryUrl=""
folderPath="string"
accepts={[]}
onChange={(filePickerResult) => {}}
onOpenFolder={(folder: IFile) => {}}
/>);
//as in package.json we map spinner to lib-common spinner mount will actually render the whole thing
//so let's try to find our spinner by class name
let spinner = component.getDOMNode().querySelector(".ms-Spinner-circle");
assert.isOk(spinner);
});
test("should load initial data", async ()=>{
//In this test we will call componentDidMount manually
//As mounting in test context will not trigger full component lifecycle we have to do it on our own
//(It won't be a case if we were to use @testing-library/react but this is a topic for another time:) )
let mockFileBrowserService: MockFileBrowserService = new MockFileBrowserService();
//FileBrowser uses getListItems method on fileBrowserService.
//Our mock already provides that method, so let's assign our mock data
mockFileBrowserService.getListItemsResult = {
nextHref: undefined,
items: [{
name: "Test file",
absoluteUrl: "https://test.sharepoint.com/sites/tea-point/Shared Documents/TestFile.docx",
serverRelativeUrl: "/sites/tea-point/Shared Documents/TestFile.docx",
isFolder: false,
modified: "",
fileIcon: "",
fileType: "docx",
// URL required to generate thumbnail preview
spItemUrl: "",
supportsThumbnail: false
},{
name: "Another test file",
absoluteUrl: "https://test.sharepoint.com/sites/tea-point/Shared Documents/AnotherTestFile.docx",
serverRelativeUrl: "/sites/tea-point/Shared Documents/AnotherTestFile.docx",
isFolder: false,
modified: "",
fileIcon: "",
fileType: "docx",
// URL required to generate thumbnail preview
spItemUrl: "",
supportsThumbnail: false
}]
}
//As we also want to validate correct data is passed to getListItem method, let's add some assertion in our mock event
//Don't hesitate to peek the mock definition to check out how it's done.
//To avoid false positives I declare asserted variable.
//It's value will be set to true in event handler and asserted at the end of this test
let asserted = false;
mockFileBrowserService.onGetListItems = (listUrl,folderPath,acceptedExtensions,nextPageParams)=>{
assert.equal(listUrl, "Shared Documents");
assert.equal(folderPath,"/");
assert.deepEqual(acceptedExtensions,["docx","xlsx"]);
//nextPageParams should be falsy in this case
assert.isNotOk(nextPageParams);
asserted = true;
}
let component = mount(<FileBrowser
fileBrowserService={mockFileBrowserService as any}
libraryUrl="Shared Documents"
folderPath="/"
accepts={["docx","xlsx"]}
onChange={(filePickerResult) => {}}
onOpenFolder={(folder: IFile) => {}}
/>);
//You could wonder - why not to test loading animation here instead of the previous test?
//I want to avoid situation in which broken loading animation would affect test for loading data.
//Those are two different functionalities I wish to test separately
//as promised - here we are manually call lifecycle method. Note await keyword.
await component.instance().componentDidMount();
//Now, let's make sure our component is rerendered
component.update();
//And now let's find our rows. Note we are using lib-commonjs to mock details list which allows us to fully render the component
let dataRows = component.getDOMNode().querySelectorAll('[data-automationid="DetailsRowFields"]')
//We expect to have to rows. Content of each should be just the name of the document.
assert.equal(dataRows[0].textContent,"Test file");
assert.equal(dataRows[1].textContent,"Another test file");
//And finally let's make sure we asserted the call to getListItems
assert.isTrue(asserted);
});
test("should handle folder change", async ()=>{
//In this test we want to assert if changing the folder will trigger proper event
//Same as previously we will have to call lifecycle events and click handlers on our own
let mockFileBrowserService: MockFileBrowserService = new MockFileBrowserService();
//First let define first Mock Data
let mockData = {
nextHref: undefined,
items: [{
name: "Test Folder",
absoluteUrl: "https://test.sharepoint.com/sites/tea-point/Shared Documents/Test Folder",
serverRelativeUrl: "/sites/tea-point/Shared Documents/Test Folder",
isFolder: true,
modified: "",
fileIcon: "",
fileType: "folder",
// URL required to generate thumbnail preview
spItemUrl: "",
supportsThumbnail: false
}]
};
mockFileBrowserService.getListItemsResult = mockData;
//Let's mount our component...
//The key to this test is to pass onOpenFolder method that will assert validity of the event
let asserted = false;
let component = mount(<FileBrowser
fileBrowserService={mockFileBrowserService as any}
libraryUrl="Shared Documents"
folderPath="/"
accepts={["docx","xlsx"]}
onChange={(filePickerResult) => {}}
onOpenFolder={(folder: IFile) => {
assert.deepEqual(folder,mockData.items[0]);
asserted = true;
}}
/>);
//...and await relevant event
await component.instance().componentDidMount();
component.update();
//Now we want to mock click event. There are two ways around it. One possibility is to send click event on some element.
//The other one is to call private method of our component with specific argument. In our case, that would be our folder.
//In this case I would lean toward the second option. The first one could fail if exception occur in DetailsList and we don't have to worry about it.
//However I do plan to include test sample with mocking external components (Will be more useful for functional components)
//@ts-ignore
component.instance()._handleItemInvoked(mockData.items[0]);
assert.isTrue(asserted);
});
test("should handle item change", async ()=>{
//In this test we want to assert if selecting a file will trigger proper event
//Same as previously we will have to call lifecycle events and click handlers on our own
let mockFileBrowserService: MockFileBrowserService = new MockFileBrowserService();
//First let define first Mock Data
let mockData = {
nextHref: undefined,
items: [{
name: "Test File",
absoluteUrl: "https://test.sharepoint.com/sites/tea-point/Shared Documents/Test File.docx",
serverRelativeUrl: "/sites/tea-point/Shared Documents/Test File.docx",
isFolder: false,
modified: "",
fileIcon: "",
fileType: "docx",
// URL required to generate thumbnail preview
spItemUrl: "",
supportsThumbnail: false
}]
};
mockFileBrowserService.getListItemsResult = mockData;
//Also let's define our expected file
const expectedFilePicked = {
fileName: "Test File",
fileNameWithoutExtension: "Test File",
fileAbsoluteUrl: "https://test.sharepoint.com/sites/tea-point/Shared Documents/Test File.docx",
spItemUrl: "",
downloadFileContent: null
}
//Let's mount our component...
//The key to this test is to pass onChange method that will assert validity of the event
let asserted = false;
let component = mount(<FileBrowser
fileBrowserService={mockFileBrowserService as any}
libraryUrl="Shared Documents"
folderPath="/"
accepts={["docx","xlsx"]}
onChange={(filePickerResult) => {
assert.deepEqual(filePickerResult,expectedFilePicked);
asserted = true;}}
onOpenFolder={(folder: IFile) => {}}
/>);
//...and await relevant event
await component.instance().componentDidMount();
component.update();
//We can use same approach as in previous test
//@ts-ignore
component.instance()._handleItemInvoked(mockData.items[0]);
assert.isTrue(asserted);
});
}); | the_stack |
// #pragma once
type int = number;
type float = number;
type size_t = number;
import * as ImGui from "imgui-js";
// #include <stdio.h> // sprintf, scanf
// #include <stdint.h> // uint8_t, etc.
// #ifdef _MSC_VER
// #define _PRISizeT "I"
// #define ImSnprintf _snprintf
// #else
// #define _PRISizeT "z"
// #define ImSnprintf snprintf
// #endif
// #ifdef _MSC_VER
// #pragma warning (push)
// #pragma warning (disable: 4996) // warning C4996: 'sprintf': This function or variable may be unsafe.
// #endif
export class MemoryEditor
{
// Settings
Open: boolean; // = true // set to false when DrawWindow() was closed. ignore if not using DrawWindow().
ReadOnly: boolean; // = false // disable any editing.
Cols: int; // = 16 // number of columns to display.
OptShowOptions: boolean; // = true // display options button/context menu. when disabled, options will be locked unless you provide your own UI for them.
OptShowDataPreview: boolean; // = false // display a footer previewing the decimal/binary/hex/float representation of the currently selected bytes.
OptShowHexII: boolean; // = false // display values in HexII representation instead of regular hexadecimal: hide null/zero bytes, ascii values as ".X".
OptShowAscii: boolean; // = true // display ASCII representation on the right side.
OptGreyOutZeroes: boolean; // = true // display null/zero bytes using the TextDisabled color.
OptUpperCaseHex: boolean; // = true // display hexadecimal values as "FF" instead of "ff".
OptMidColsCount: int; // = 8 // set to 0 to disable extra spacing between every mid-cols.
OptAddrDigitsCount: int; // = 0 // number of addr digits to display (default calculated based on maximum displayed addr).
HighlightColor: ImGui.U32; // // background color of highlighted bytes.
public ReadFn: ((data: ArrayBuffer, off: size_t) => size_t) | null; // = 0 // optional handler to read bytes.
public WriteFn: ((data: ArrayBuffer, off: size_t, d: number) => void) | null; // = 0 // optional handler to write bytes.
public HighlightFn: ((data: ArrayBuffer, off: size_t) => boolean) | null; // = 0 // optional handler to return Highlight property (to support non-contiguous highlighting).
// [Internal State]
ContentsWidthChanged: boolean;
DataPreviewAddr: size_t;
DataEditingAddr: size_t;
DataEditingTakeFocus: boolean;
readonly DataInputBuf: ImGui.StringBuffer = new ImGui.StringBuffer(32); /*char[32]*/;
readonly AddrInputBuf: ImGui.StringBuffer = new ImGui.StringBuffer(32); /*char[32]*/;
GotoAddr: size_t;
HighlightMin: size_t; HighlightMax: size_t;
PreviewEndianess: int;
PreviewDataType: ImGui.DataType;
constructor()
{
// Settings
this.Open = true;
this.ReadOnly = false;
this.Cols = 16;
this.OptShowOptions = true;
this.OptShowDataPreview = false;
this.OptShowHexII = false;
this.OptShowAscii = true;
this.OptGreyOutZeroes = true;
this.OptUpperCaseHex = true;
this.OptMidColsCount = 8;
this.OptAddrDigitsCount = 0;
this.HighlightColor = ImGui.COL32(255, 255, 255, 50);
this.ReadFn = null;
this.WriteFn = null;
this.HighlightFn = null;
// State/Internals
this.ContentsWidthChanged = false;
this.DataPreviewAddr = this.DataEditingAddr = <size_t>-1;
this.DataEditingTakeFocus = false;
this.DataInputBuf.buffer = ""; // memset(DataInputBuf, 0, sizeof(DataInputBuf));
this.AddrInputBuf.buffer = ""; // memset(AddrInputBuf, 0, sizeof(AddrInputBuf));
this.GotoAddr = <size_t>-1;
this.HighlightMin = this.HighlightMax = <size_t>-1;
this.PreviewEndianess = 0;
this.PreviewDataType = ImGui.DataType.S32;
}
GotoAddrAndHighlight(addr_min: size_t, addr_max: size_t): void
{
this.GotoAddr = addr_min;
this.HighlightMin = addr_min;
this.HighlightMax = addr_max;
}
CalcSizes(s: MemoryEditor.Sizes, mem_size: size_t, base_display_addr: size_t): void
{
const style: ImGui.Style = ImGui.GetStyle();
s.AddrDigitsCount = this.OptAddrDigitsCount;
if (s.AddrDigitsCount === 0)
for (let /*size_t*/ n = base_display_addr + mem_size - 1; n > 0; n >>= 4)
s.AddrDigitsCount++;
s.LineHeight = ImGui.GetTextLineHeight();
s.GlyphWidth = ImGui.CalcTextSize("F").x + 1; // We assume the font is mono-space
s.HexCellWidth = Math.floor/*(float)(int)*/(s.GlyphWidth * 2.5); // "FF " we include trailing space in the width to easily catch clicks everywhere
s.SpacingBetweenMidCols = Math.floor/*(float)(int)*/(s.HexCellWidth * 0.25); // Every OptMidColsCount columns we add a bit of extra spacing
s.PosHexStart = (s.AddrDigitsCount + 2) * s.GlyphWidth;
s.PosHexEnd = s.PosHexStart + (s.HexCellWidth * this.Cols);
s.PosAsciiStart = s.PosAsciiEnd = s.PosHexEnd;
if (this.OptShowAscii)
{
s.PosAsciiStart = s.PosHexEnd + s.GlyphWidth * 1;
if (this.OptMidColsCount > 0)
s.PosAsciiStart += /*(float)*/((this.Cols + this.OptMidColsCount - 1) / this.OptMidColsCount) * s.SpacingBetweenMidCols;
s.PosAsciiEnd = s.PosAsciiStart + this.Cols * s.GlyphWidth;
}
s.WindowWidth = s.PosAsciiEnd + style.ScrollbarSize + style.WindowPadding.x * 2 + s.GlyphWidth;
}
// Standalone Memory Editor window
public DrawWindow(title: string, mem_data: ArrayBuffer, mem_size: number = mem_data.byteLength, base_display_addr: number = 0x0000): void
{
const s: MemoryEditor.Sizes = new MemoryEditor.Sizes();
this.CalcSizes(s, mem_size, base_display_addr);
ImGui.SetNextWindowSizeConstraints(new ImGui.Vec2(0.0, 0.0), new ImGui.Vec2(s.WindowWidth, Number.MAX_VALUE));
this.Open = true;
if (ImGui.Begin(title, (_ = this.Open) => this.Open = _, ImGui.WindowFlags.NoScrollbar))
{
if (ImGui.IsWindowHovered(ImGui.HoveredFlags.RootAndChildWindows) && ImGui.IsMouseReleased(ImGui.MouseButton.Right))
ImGui.OpenPopup("context");
this.DrawContents(mem_data, mem_size, base_display_addr);
if (this.ContentsWidthChanged)
{
this.CalcSizes(s, mem_size, base_display_addr);
ImGui.SetWindowSize(new ImGui.Vec2(s.WindowWidth, ImGui.GetWindowSize().y));
}
}
ImGui.End();
}
// Memory Editor contents only
// void DrawContents(void* mem_data_void, size_t mem_size, size_t base_display_addr = 0x0000)
public DrawContents(mem_data: ArrayBuffer, mem_size: number = mem_data.byteLength, base_display_addr: number = 0x0000): void
{
if (this.Cols < 1)
this.Cols = 1;
// ImU8* mem_data = (ImU8*)mem_data_void;
const s: MemoryEditor.Sizes = new MemoryEditor.Sizes();
this.CalcSizes(s, mem_size, base_display_addr);
const style: ImGui.Style = ImGui.GetStyle();
// We begin into our scrolling region with the 'ImGui.WindowFlags.NoMove' in order to prevent click from moving the window.
// This is used as a facility since our main click detection code doesn't assign an ActiveId so the click would normally be caught as a window-move.
const height_separator: float = style.ItemSpacing.y;
let footer_height: float = 0;
if (this.OptShowOptions)
footer_height += height_separator + ImGui.GetFrameHeightWithSpacing() * 1;
if (this.OptShowDataPreview)
footer_height += height_separator + ImGui.GetFrameHeightWithSpacing() * 1 + ImGui.GetTextLineHeightWithSpacing() * 3;
ImGui.BeginChild("##scrolling", new ImGui.Vec2(0, -footer_height), false, ImGui.WindowFlags.NoMove | ImGui.WindowFlags.NoNav);
const draw_list: ImGui.DrawList = ImGui.GetWindowDrawList();
ImGui.PushStyleVar(ImGui.StyleVar.FramePadding, new ImGui.Vec2(0, 0));
ImGui.PushStyleVar(ImGui.StyleVar.ItemSpacing, new ImGui.Vec2(0, 0));
// We are not really using the clipper API correctly here, because we rely on visible_start_addr/visible_end_addr for our scrolling function.
const line_total_count: int = 0|/*(int)*/((mem_size + this.Cols - 1) / this.Cols);
// ImGuiListClipper clipper;
const clipper = new ImGui.ListClipper();
clipper.Begin(line_total_count, s.LineHeight);
clipper.Step();
const visible_start_addr: size_t = clipper.DisplayStart * this.Cols;
const visible_end_addr: size_t = clipper.DisplayEnd * this.Cols;
let data_next: boolean = false;
if (this.ReadOnly || this.DataEditingAddr >= mem_size)
this.DataEditingAddr = <size_t>-1;
if (this.DataPreviewAddr >= mem_size)
this.DataPreviewAddr = <size_t>-1;
const preview_data_type_size: size_t = this.OptShowDataPreview ? this.DataTypeGetSize(this.PreviewDataType) : 0;
let data_editing_addr_backup: size_t = this.DataEditingAddr;
let data_editing_addr_next: size_t = <size_t>-1;
if (this.DataEditingAddr !== <size_t>-1)
{
// Move cursor but only apply on next frame so scrolling with be synchronized (because currently we can't change the scrolling while the window is being rendered)
if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGui.Key.UpArrow)) && this.DataEditingAddr >= <size_t>this.Cols) { data_editing_addr_next = this.DataEditingAddr - this.Cols; this.DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGui.Key.DownArrow)) && this.DataEditingAddr < mem_size - this.Cols) { data_editing_addr_next = this.DataEditingAddr + this.Cols; this.DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGui.Key.LeftArrow)) && this.DataEditingAddr > 0) { data_editing_addr_next = this.DataEditingAddr - 1; this.DataEditingTakeFocus = true; }
else if (ImGui.IsKeyPressed(ImGui.GetKeyIndex(ImGui.Key.RightArrow)) && this.DataEditingAddr < mem_size - 1) { data_editing_addr_next = this.DataEditingAddr + 1; this.DataEditingTakeFocus = true; }
}
if (data_editing_addr_next !== <size_t>-1 && (data_editing_addr_next / this.Cols) !== (data_editing_addr_backup / this.Cols))
{
// Track cursor movements
const scroll_offset: int = (/*(int)*/(data_editing_addr_next / this.Cols) - /*(int)*/(data_editing_addr_backup / this.Cols));
const scroll_desired: boolean = (scroll_offset < 0 && data_editing_addr_next < visible_start_addr + this.Cols * 2) || (scroll_offset > 0 && data_editing_addr_next > visible_end_addr - this.Cols * 2);
if (scroll_desired)
ImGui.SetScrollY(ImGui.GetScrollY() + scroll_offset * s.LineHeight);
}
// Draw vertical separator
const window_pos: ImGui.Vec2 = ImGui.GetWindowPos();
if (this.OptShowAscii)
draw_list.AddLine(new ImGui.Vec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y), new ImGui.Vec2(window_pos.x + s.PosAsciiStart - s.GlyphWidth, window_pos.y + 9999), ImGui.GetColorU32(ImGui.Col.Border));
const color_text: ImGui.U32 = ImGui.GetColorU32(ImGui.Col.Text);
const color_disabled: ImGui.U32 = this.OptGreyOutZeroes ? ImGui.GetColorU32(ImGui.Col.TextDisabled) : color_text;
// const char* format_address = this.OptUpperCaseHex ? "%0*" _PRISizeT "X: " : "%0*" _PRISizeT "x: ";
const format_address = (n: number, a: number): string => {
let s = a.toString(16).padStart(n, "0");
if (this.OptUpperCaseHex) { s = s.toUpperCase(); }
return s;
};
// const char* format_data = this.OptUpperCaseHex ? "%0*" _PRISizeT "X" : "%0*" _PRISizeT "x";
const format_data = (n: number, a: number): string => {
let s = a.toString(16).padStart(n, "0");
if (this.OptUpperCaseHex) { s = s.toUpperCase(); }
return s;
};
// const char* format_byte = this.OptUpperCaseHex ? "%02X" : "%02x";
const format_byte = (b: number): string => {
let s = b.toString(16).padStart(2, "0");
if (this.OptUpperCaseHex) { s = s.toUpperCase(); }
return s;
};
// const char* format_byte_space = this.OptUpperCaseHex ? "%02X " : "%02x ";
const format_byte_space = (b: number): string => {
return `${format_byte(b)} `;
}
for (let /*int*/ line_i = clipper.DisplayStart; line_i < clipper.DisplayEnd; line_i++) // display only visible lines
{
let addr: size_t = <size_t>(line_i * this.Cols);
// ImGui.Text(format_address, s.AddrDigitsCount, base_display_addr + addr);
ImGui.Text(format_address(s.AddrDigitsCount, base_display_addr + addr));
// Draw Hexadecimal
for (let /*int*/ n = 0; n < this.Cols && addr < mem_size; n++, addr++)
{
let byte_pos_x: float = s.PosHexStart + s.HexCellWidth * n;
if (this.OptMidColsCount > 0)
byte_pos_x += /*(float)*/(n / this.OptMidColsCount) * s.SpacingBetweenMidCols;
ImGui.SameLine(byte_pos_x);
// Draw highlight
const is_highlight_from_user_range: boolean = (addr >= this.HighlightMin && addr < this.HighlightMax);
const is_highlight_from_user_func: boolean = (this.HighlightFn !== null && this.HighlightFn(mem_data, addr));
const is_highlight_from_preview: boolean = (addr >= this.DataPreviewAddr && addr < this.DataPreviewAddr + preview_data_type_size);
if (is_highlight_from_user_range || is_highlight_from_user_func || is_highlight_from_preview)
{
const pos: ImGui.Vec2 = ImGui.GetCursorScreenPos();
let highlight_width: float = s.GlyphWidth * 2;
const is_next_byte_highlighted: boolean = (addr + 1 < mem_size) && ((this.HighlightMax !== <size_t>-1 && addr + 1 < this.HighlightMax) || (this.HighlightFn !== null && this.HighlightFn(mem_data, addr + 1)));
if (is_next_byte_highlighted || (n + 1 === this.Cols))
{
highlight_width = s.HexCellWidth;
if (this.OptMidColsCount > 0 && n > 0 && (n + 1) < this.Cols && ((n + 1) % this.OptMidColsCount) === 0)
highlight_width += s.SpacingBetweenMidCols;
}
draw_list.AddRectFilled(pos, new ImGui.Vec2(pos.x + highlight_width, pos.y + s.LineHeight), this.HighlightColor);
}
if (this.DataEditingAddr === addr)
{
// Display text input on current byte
let data_write: boolean = false;
ImGui.PushID(/*(void*)*/addr);
if (this.DataEditingTakeFocus)
{
ImGui.SetKeyboardFocusHere();
ImGui.CaptureKeyboardFromApp(true);
// sprintf(AddrInputBuf, format_data, s.AddrDigitsCount, base_display_addr + addr);
this.AddrInputBuf.buffer = format_data(s.AddrDigitsCount, base_display_addr + addr);
// sprintf(DataInputBuf, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
this.DataInputBuf.buffer = format_byte(this.ReadFn ? this.ReadFn(mem_data, addr) : new Uint8Array(mem_data)[addr]);
}
ImGui.PushItemWidth(s.GlyphWidth * 2);
class UserData
{
// FIXME: We should have a way to retrieve the text edit cursor position more easily in the API, this is rather tedious. This is such a ugly mess we may be better off not using InputText() at all here.
static Callback(data: ImGui.InputTextCallbackData<UserData>)
{
const user_data: UserData | null = data.UserData;
ImGui.ASSERT(user_data !== null);
if (!data.HasSelection())
user_data.CursorPos = data.CursorPos;
if (data.SelectionStart === 0 && data.SelectionEnd === data.BufTextLen)
{
// When not editing a byte, always rewrite its content (this is a bit tricky, since InputText technically "owns" the master copy of the buffer we edit it in there)
data.DeleteChars(0, data.BufTextLen);
data.InsertChars(0, user_data.CurrentBufOverwrite.buffer);
data.SelectionStart = 0;
data.SelectionEnd = 2;
data.CursorPos = 0;
}
return 0;
}
readonly CurrentBufOverwrite: ImGui.StringBuffer = new ImGui.StringBuffer(3); // Input
CursorPos: number = 0; // Output
}
const user_data: UserData = new UserData();
user_data.CursorPos = -1;
// sprintf(user_data.CurrentBufOverwrite, format_byte, ReadFn ? ReadFn(mem_data, addr) : mem_data[addr]);
user_data.CurrentBufOverwrite.buffer = format_byte(this.ReadFn ? this.ReadFn(mem_data, addr) : new Uint8Array(mem_data)[addr]);
const flags: ImGui.InputTextFlags = ImGui.InputTextFlags.CharsHexadecimal | ImGui.InputTextFlags.EnterReturnsTrue | ImGui.InputTextFlags.AutoSelectAll | ImGui.InputTextFlags.NoHorizontalScroll | ImGui.InputTextFlags.AlwaysInsertMode | ImGui.InputTextFlags.CallbackAlways;
if (ImGui.InputText("##data", this.DataInputBuf, 32, flags, UserData.Callback, user_data))
data_write = data_next = true;
else if (!this.DataEditingTakeFocus && !ImGui.IsItemActive())
this.DataEditingAddr = data_editing_addr_next = <size_t>-1;
this.DataEditingTakeFocus = false;
ImGui.PopItemWidth();
if (user_data.CursorPos >= 2)
data_write = data_next = true;
if (data_editing_addr_next !== <size_t>-1)
data_write = data_next = false;
// unsigned int data_input_value = 0;
let data_input_value: number/*unsigned int*/ = 0;
// if (data_write && sscanf(DataInputBuf, "%X", &data_input_value) === 1)
if (data_write && Number.isInteger(data_input_value = parseInt(this.DataInputBuf.buffer, 16)))
{
if (this.WriteFn)
this.WriteFn(mem_data, addr, /*(ImU8)*/data_input_value);
else
// mem_data[addr] = (ImU8)data_input_value;
new Uint8Array(mem_data)[addr] = data_input_value;
}
ImGui.PopID();
}
else
{
// NB: The trailing space is not visible but ensure there's no gap that the mouse cannot click on.
// ImU8 b = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
const b: number/*ImU8*/ = this.ReadFn ? this.ReadFn(mem_data, addr) : new Uint8Array(mem_data)[addr];
if (this.OptShowHexII)
{
if ((b >= 32 && b < 128))
// ImGui.Text(".%c ", b);
ImGui.Text(`.${String.fromCharCode(b)} `);
else if (b === 0xFF && this.OptGreyOutZeroes)
ImGui.TextDisabled("## ");
else if (b === 0x00)
ImGui.Text(" ");
else
ImGui.Text(format_byte_space(b));
}
else
{
if (b === 0 && this.OptGreyOutZeroes)
ImGui.TextDisabled("00 ");
else
ImGui.Text(format_byte_space(b));
}
if (!this.ReadOnly && ImGui.IsItemHovered() && ImGui.IsMouseClicked(0))
{
this.DataEditingTakeFocus = true;
data_editing_addr_next = addr;
}
}
}
if (this.OptShowAscii)
{
// Draw ASCII values
ImGui.SameLine(s.PosAsciiStart);
const pos: ImGui.Vec2 = ImGui.GetCursorScreenPos();
addr = line_i * this.Cols;
ImGui.PushID(line_i);
if (ImGui.InvisibleButton("ascii", new ImGui.Vec2(s.PosAsciiEnd - s.PosAsciiStart, s.LineHeight)))
{
this.DataEditingAddr = this.DataPreviewAddr = addr + <size_t>((ImGui.GetIO().MousePos.x - pos.x) / s.GlyphWidth);
this.DataEditingTakeFocus = true;
}
ImGui.PopID();
for (let /*int*/ n = 0; n < this.Cols && addr < mem_size; n++, addr++)
{
if (addr === this.DataEditingAddr)
{
draw_list.AddRectFilled(pos, new ImGui.Vec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui.GetColorU32(ImGui.Col.FrameBg));
draw_list.AddRectFilled(pos, new ImGui.Vec2(pos.x + s.GlyphWidth, pos.y + s.LineHeight), ImGui.GetColorU32(ImGui.Col.TextSelectedBg));
}
// unsigned char c = ReadFn ? ReadFn(mem_data, addr) : mem_data[addr];
const c: number = this.ReadFn ? this.ReadFn(mem_data, addr) : new Uint8Array(mem_data)[addr];
// char display_c = (c < 32 || c >= 128) ? '.' : c;
const display_c: string = (c < 32 || c >= 128) ? "." : String.fromCharCode(c);
// draw_list.AddText(pos, (display_c === c) ? color_text : color_disabled, &display_c, &display_c + 1);
draw_list.AddText(pos, (display_c === ".") ? color_disabled : color_text, display_c);
pos.x += s.GlyphWidth;
}
}
}
ImGui.ASSERT(clipper.Step() === false);
clipper.End();
ImGui.PopStyleVar(2);
ImGui.EndChild();
if (data_next && this.DataEditingAddr < mem_size)
{
this.DataEditingAddr = this.DataPreviewAddr = this.DataEditingAddr + 1;
this.DataEditingTakeFocus = true;
}
else if (data_editing_addr_next !== <size_t>-1)
{
this.DataEditingAddr = this.DataPreviewAddr = data_editing_addr_next;
}
const lock_show_data_preview: boolean = this.OptShowDataPreview;
if (this.OptShowOptions)
{
ImGui.Separator();
this.DrawOptionsLine(s, mem_data, mem_size, base_display_addr);
}
if (lock_show_data_preview)
{
ImGui.Separator();
this.DrawPreviewLine(s, mem_data, mem_size, base_display_addr);
}
// Notify the main window of our ideal child content size (FIXME: we are missing an API to get the contents size from the child)
ImGui.SetCursorPosX(s.WindowWidth);
}
DrawOptionsLine(s: MemoryEditor.Sizes, mem_data: ArrayBuffer, mem_size: size_t, base_display_addr: size_t): void
{
// IM_UNUSED(mem_data);
const style: ImGui.Style = ImGui.GetStyle();
// const char* format_range = OptUpperCaseHex ? "Range %0*" _PRISizeT "X..%0*" _PRISizeT "X" : "Range %0*" _PRISizeT "x..%0*" _PRISizeT "x";
const format_range = (n_min: number, a_min: number, n_max: number, a_max: number): string => {
let s_min = a_min.toString(16).padStart(n_min, "0");
let s_max = a_max.toString(16).padStart(n_max, "0");
if (this.OptUpperCaseHex) {
s_min = s_min.toUpperCase();
s_max = s_max.toUpperCase();
}
return `Range ${s_min}..${s_max}`;
};
// Options menu
if (ImGui.Button("Options"))
ImGui.OpenPopup("context");
if (ImGui.BeginPopup("context"))
{
ImGui.PushItemWidth(56);
if (ImGui.DragInt("##cols", (_ = this.Cols) => this.Cols = _, 0.2, 4, 32, "%d cols")) { this.ContentsWidthChanged = true; if (this.Cols < 1) this.Cols = 1; }
ImGui.PopItemWidth();
ImGui.Checkbox("Show Data Preview", (_ = this.OptShowDataPreview) => this.OptShowDataPreview = _);
ImGui.Checkbox("Show HexII", (_ = this.OptShowHexII) => this.OptShowHexII = _);
if (ImGui.Checkbox("Show Ascii", (_ = this.OptShowAscii) => this.OptShowAscii = _)) { this.ContentsWidthChanged = true; }
ImGui.Checkbox("Grey out zeroes", (_ = this.OptGreyOutZeroes) => this.OptGreyOutZeroes = _);
ImGui.Checkbox("Uppercase Hex", (_ = this.OptUpperCaseHex) => this.OptUpperCaseHex = _);
ImGui.EndPopup();
}
ImGui.SameLine();
// ImGui.Text(format_range, s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1);
ImGui.Text(format_range(s.AddrDigitsCount, base_display_addr, s.AddrDigitsCount, base_display_addr + mem_size - 1));
ImGui.SameLine();
ImGui.PushItemWidth((s.AddrDigitsCount + 1) * s.GlyphWidth + style.FramePadding.x * 2.0);
if (ImGui.InputText("##addr", this.AddrInputBuf, 32, ImGui.InputTextFlags.CharsHexadecimal | ImGui.InputTextFlags.EnterReturnsTrue))
{
// size_t goto_addr;
let goto_addr: size_t;
// if (sscanf(AddrInputBuf, "%" _PRISizeT "X", &goto_addr) === 1)
if (Number.isInteger(goto_addr = parseInt(this.AddrInputBuf.buffer, 16)))
{
this.GotoAddr = goto_addr - base_display_addr;
this.HighlightMin = this.HighlightMax = <size_t>-1;
}
}
ImGui.PopItemWidth();
if (this.GotoAddr !== <size_t>-1)
{
if (this.GotoAddr < mem_size)
{
ImGui.BeginChild("##scrolling");
ImGui.SetScrollFromPosY(ImGui.GetCursorStartPos().y + (this.GotoAddr / this.Cols) * ImGui.GetTextLineHeight());
ImGui.EndChild();
this.DataEditingAddr = this.DataPreviewAddr = this.GotoAddr;
this.DataEditingTakeFocus = true;
}
this.GotoAddr = <size_t>-1;
}
}
// void DrawPreviewLine(const Sizes& s, void* mem_data_void, size_t mem_size, size_t base_display_addr)
DrawPreviewLine(s: MemoryEditor.Sizes, mem_data: ArrayBuffer, mem_size: size_t, base_display_addr: size_t): void
{
// IM_UNUSED(base_display_addr);
// ImU8* mem_data = (ImU8*)mem_data_void;
const style: ImGui.Style = ImGui.GetStyle();
ImGui.AlignTextToFramePadding();
ImGui.Text("Preview as:");
ImGui.SameLine();
ImGui.PushItemWidth((s.GlyphWidth * 10.0) + style.FramePadding.x * 2.0 + style.ItemInnerSpacing.x);
if (ImGui.BeginCombo("##combo_type", this.DataTypeGetDesc(this.PreviewDataType), ImGui.ComboFlags.HeightLargest))
{
for (let /*int*/ n = 0; n < ImGui.DataType.COUNT; n++)
if (ImGui.Selectable(this.DataTypeGetDesc(<ImGui.DataType>n), this.PreviewDataType === n))
this.PreviewDataType = <ImGui.DataType>n;
ImGui.EndCombo();
}
ImGui.PopItemWidth();
ImGui.SameLine();
ImGui.PushItemWidth((s.GlyphWidth * 6.0) + style.FramePadding.x * 2.0 + style.ItemInnerSpacing.x);
ImGui.Combo("##combo_endianess", (_ = this.PreviewEndianess) => this.PreviewEndianess = _, "LE\0BE\0\0");
ImGui.PopItemWidth();
// char buf[128] = "";
const buf: ImGui.StringBuffer = new ImGui.StringBuffer(128);
const x: float = s.GlyphWidth * 6.0;
const has_value: boolean = this.DataPreviewAddr !== <size_t>-1;
if (has_value)
this.DrawPreviewData(this.DataPreviewAddr, mem_data, mem_size, this.PreviewDataType, MemoryEditor.DataFormat.Dec, buf, <size_t>ImGui.ARRAYSIZE(buf));
ImGui.Text("Dec"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value ? buf.buffer : "N/A");
if (has_value)
this.DrawPreviewData(this.DataPreviewAddr, mem_data, mem_size, this.PreviewDataType, MemoryEditor.DataFormat.Hex, buf, <size_t>ImGui.ARRAYSIZE(buf));
ImGui.Text("Hex"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value ? buf.buffer : "N/A");
if (has_value)
this.DrawPreviewData(this.DataPreviewAddr, mem_data, mem_size, this.PreviewDataType, MemoryEditor.DataFormat.Bin, buf, <size_t>ImGui.ARRAYSIZE(buf));
// buf[ImGui.ARRAYSIZE(buf) - 1] = 0;
ImGui.Text("Bin"); ImGui.SameLine(x); ImGui.TextUnformatted(has_value ? buf.buffer : "N/A");
}
// Utilities for Data Preview
DataTypeGetDesc(data_type: ImGui.DataType): string
{
const descs: string[] = [ "Int8", "Uint8", "Int16", "Uint16", "Int32", "Uint32", "Int64", "Uint64", "Float", "Double" ];
ImGui.ASSERT(data_type >= 0 && data_type < ImGui.DataType.COUNT);
return descs[data_type];
}
DataTypeGetSize(data_type: ImGui.DataType): size_t
{
const sizes: size_t[] = [ 1, 1, 2, 2, 4, 4, 8, 8, /*sizeof(float)*/4, /*sizeof(double)*/8 ];
ImGui.ASSERT(data_type >= 0 && data_type < ImGui.DataType.COUNT);
return sizes[data_type];
}
DataFormatGetDesc(data_format: MemoryEditor.DataFormat): string
{
const descs: string[] = [ "Bin", "Dec", "Hex" ];
ImGui.ASSERT(data_format >= 0 && data_format < MemoryEditor.DataFormat.COUNT);
return descs[data_format];
}
IsBigEndian(): boolean {
// uint16_t x = 1;
const x = new Uint16Array([1]);
// char c[2];
// memcpy(c, &x, 2);
const c = new Int8Array(x.buffer);
return c[0] !== 0;
}
// static void* EndianessCopyBigEndian(void* _dst, void* _src, size_t s, int is_little_endian)
// {
// if (is_little_endian)
// {
// uint8_t* dst = (uint8_t*)_dst;
// uint8_t* src = (uint8_t*)_src + s - 1;
// for (int i = 0, n = (int)s; i < n; ++i)
// memcpy(dst++, src--, 1);
// return _dst;
// }
// else
// {
// return memcpy(_dst, _src, s);
// }
// }
// static void* EndianessCopyLittleEndian(void* _dst, void* _src, size_t s, int is_little_endian)
// {
// if (is_little_endian)
// {
// return memcpy(_dst, _src, s);
// }
// else
// {
// uint8_t* dst = (uint8_t*)_dst;
// uint8_t* src = (uint8_t*)_src + s - 1;
// for (int i = 0, n = (int)s; i < n; ++i)
// memcpy(dst++, src--, 1);
// return _dst;
// }
// }
// void* EndianessCopy(void* dst, void* src, size_t size) const
// {
// static void* (*fp)(void*, void*, size_t, int) = null;
// if (fp === null)
// fp = IsBigEndian() ? EndianessCopyBigEndian : EndianessCopyLittleEndian;
// return fp(dst, src, size, PreviewEndianess);
// }
// const char* FormatBinary(const uint8_t* buf, int width) const
// {
// ImGui.ASSERT(width <= 64);
// size_t out_n = 0;
// static char out_buf[64 + 8 + 1];
// int n = width / 8;
// for (int j = n - 1; j >= 0; --j)
// {
// for (int i = 0; i < 8; ++i)
// out_buf[out_n++] = (buf[j] & (1 << (7 - i))) ? '1' : '0';
// out_buf[out_n++] = ' ';
// }
// ImGui.ASSERT(out_n < ImGui.ARRAYSIZE(out_buf));
// out_buf[out_n] = 0;
// return out_buf;
// }
// [Internal]
DrawPreviewData(addr: size_t, mem_data: ArrayBuffer, mem_size: size_t, data_type: ImGui.DataType, data_format: MemoryEditor.DataFormat, out_buf: ImGui.StringBuffer, out_buf_size: size_t): void
{
// uint8_t buf[8];
const buf = new Uint8Array(8);
const elem_size: size_t = this.DataTypeGetSize(data_type);
const size: size_t = addr + elem_size > mem_size ? mem_size - addr : elem_size;
if (this.ReadFn)
for (let /*int*/ i = 0, n = /*(int)*/size; i < n; ++i)
buf[i] = this.ReadFn(mem_data, addr + i);
else
// memcpy(buf, mem_data + addr, size);
buf.set(new Uint8Array(mem_data, addr, size));
if (this.PreviewEndianess) { new Uint8Array(buf.buffer, 0, size).reverse(); }
if (data_format === MemoryEditor.DataFormat.Bin)
{
// uint8_t binbuf[8];
// EndianessCopy(binbuf, buf, size);
// ImSnprintf(out_buf, out_buf_size, "%s", FormatBinary(binbuf, (int)size * 8));
out_buf.buffer = "";
for (let i = 0; i < size; ++i) {
out_buf.buffer += buf[i].toString(2).padStart(8, "0") + " ";
}
return;
}
// out_buf[0] = 0;
out_buf.buffer = "";
switch (data_type)
{
case ImGui.DataType.S8:
{
// int8_t int8 = 0;
// EndianessCopy(&int8, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%hhd", int8); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", int8 & 0xFF); return; }
const int8 = new Int8Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = int8[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${int8[0].toString(16).padStart(2, "0")}`; return; }
break;
}
case ImGui.DataType.U8:
{
// uint8_t uint8 = 0;
// EndianessCopy(&uint8, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%hhu", uint8); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%02x", uint8 & 0XFF); return; }
const uint8 = new Uint8Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = uint8[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${uint8[0].toString(16).padStart(2, "0")}`; return; }
break;
}
case ImGui.DataType.S16:
{
// int16_t int16 = 0;
// EndianessCopy(&int16, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%hd", int16); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", int16 & 0xFFFF); return; }
const int16 = new Int16Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = int16[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${int16[0].toString(16).padStart(4, "0")}`; return; }
break;
}
case ImGui.DataType.U16:
{
// uint16_t uint16 = 0;
// EndianessCopy(&uint16, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%hu", uint16); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%04x", uint16 & 0xFFFF); return; }
const uint16 = new Uint16Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = uint16[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${uint16[0].toString(16).padStart(4, "0")}`; return; }
break;
}
case ImGui.DataType.S32:
{
// int32_t int32 = 0;
// EndianessCopy(&int32, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%d", int32); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", int32); return; }
const int32 = new Int32Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = int32[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${int32[0].toString(16).padStart(8, "0")}`; return; }
break;
}
case ImGui.DataType.U32:
{
// uint32_t uint32 = 0;
// EndianessCopy(&uint32, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%u", uint32); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%08x", uint32); return; }
const uint32 = new Uint32Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = uint32[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${uint32[0].toString(16).padStart(8, "0")}`; return; }
break;
}
case ImGui.DataType.S64:
{
// int64_t int64 = 0;
// EndianessCopy(&int64, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%lld", (long long)int64); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)int64); return; }
const int64 = new BigInt64Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = int64[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${int64[0].toString(16).padStart(16, "0")}`; return; }
break;
}
case ImGui.DataType.U64:
{
// uint64_t uint64 = 0;
// EndianessCopy(&uint64, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%llu", (long long)uint64); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "0x%016llx", (long long)uint64); return; }
const uint64 = new BigUint64Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = uint64[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${uint64[0].toString(16).padStart(16, "0")}`; return; }
break;
}
case ImGui.DataType.Float:
{
// float float32 = 0.0f;
// EndianessCopy(&float32, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float32); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float32); return; }
const float32 = new Float32Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = float32[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${float32[0].toString(16)}`; return; }
break;
}
case ImGui.DataType.Double:
{
// double float64 = 0.0;
// EndianessCopy(&float64, buf, size);
// if (data_format === MemoryEditor.DataFormat.Dec) { ImSnprintf(out_buf, out_buf_size, "%f", float64); return; }
// if (data_format === MemoryEditor.DataFormat.Hex) { ImSnprintf(out_buf, out_buf_size, "%a", float64); return; }
const float64 = new Float64Array(buf.buffer);
if (data_format === MemoryEditor.DataFormat.Dec) { out_buf.buffer = float64[0].toString(); return; }
if (data_format === MemoryEditor.DataFormat.Hex) { out_buf.buffer = `0x${float64[0].toString(16)}`; return; }
break;
}
case ImGui.DataType.COUNT:
break;
} // Switch
// ImGui.ASSERT(0); // Shouldn't reach
}
}
export namespace MemoryEditor {
export enum DataFormat
{
Bin = 0,
Dec = 1,
Hex = 2,
COUNT
}
export class Sizes
{
AddrDigitsCount: int = 0;
LineHeight: float = 0.0;
GlyphWidth: float = 0.0;
HexCellWidth: float = 0.0;
SpacingBetweenMidCols: float = 0.0;
PosHexStart: float = 0.0;
PosHexEnd: float = 0.0;
PosAsciiStart: float = 0.0;
PosAsciiEnd: float = 0.0;
WindowWidth: float = 0.0;
// Sizes() { memset(this, 0, sizeof(*this)); }
}
}
// #undef _PRISizeT
// #undef ImSnprintf
// #ifdef _MSC_VER
// #pragma warning (pop)
// #endif | the_stack |
import type { Context, Plugin } from "graphile-build";
import type {
PgClass,
PgProc,
PgType,
QueryBuilder,
SQL,
} from "graphile-build-pg";
import type {
GraphQLInputFieldConfigMap,
GraphQLInputType,
GraphQLType,
} from "graphql";
import { BackwardRelationSpec } from "./PgConnectionArgFilterBackwardRelationsPlugin";
const PgConnectionArgFilterPlugin: Plugin = (
builder,
{
connectionFilterAllowedFieldTypes,
connectionFilterArrays,
connectionFilterSetofFunctions,
connectionFilterAllowNullInput,
connectionFilterAllowEmptyObjectInput,
}
) => {
// Add `filter` input argument to connection and simple collection types
builder.hook(
"GraphQLObjectType:fields:field:args",
(args, build, context) => {
const {
extend,
newWithHooks,
getTypeByName,
inflection,
pgGetGqlTypeByTypeIdAndModifier,
pgOmit: omit,
connectionFilterResolve,
connectionFilterType,
} = build;
const {
scope: {
isPgFieldConnection,
isPgFieldSimpleCollection,
pgFieldIntrospection: source,
},
addArgDataGenerator,
field,
Self,
} = context as Context<GraphQLInputFieldConfigMap> & {
scope: {
pgFieldIntrospection: PgClass | PgProc;
isPgConnectionFilter?: boolean;
};
};
const shouldAddFilter = isPgFieldConnection || isPgFieldSimpleCollection;
if (!shouldAddFilter) return args;
if (!source) return args;
if (omit(source, "filter")) return args;
if (source.kind === "procedure") {
if (!(source.tags.filterable || connectionFilterSetofFunctions)) {
return args;
}
}
const returnTypeId =
source.kind === "class" ? source.type.id : source.returnTypeId;
const returnType =
source.kind === "class"
? source.type
: (build.pgIntrospectionResultsByKind.type as PgType[]).find(
(t) => t.id === returnTypeId
);
if (!returnType) {
return args;
}
const isRecordLike = returnTypeId === "2249";
const nodeTypeName = isRecordLike
? inflection.recordFunctionReturnType(source)
: pgGetGqlTypeByTypeIdAndModifier(returnTypeId, null).name;
const filterTypeName = inflection.filterType(nodeTypeName);
const nodeType = getTypeByName(nodeTypeName);
if (!nodeType) {
return args;
}
const nodeSource =
source.kind === "procedure" && returnType.class
? returnType.class
: source;
const FilterType = connectionFilterType(
newWithHooks,
filterTypeName,
nodeSource,
nodeTypeName
);
if (!FilterType) {
return args;
}
// Generate SQL where clause from filter argument
addArgDataGenerator(function connectionFilter(args: any) {
return {
pgQuery: (queryBuilder: QueryBuilder) => {
if (Object.prototype.hasOwnProperty.call(args, "filter")) {
const sqlFragment = connectionFilterResolve(
args.filter,
queryBuilder.getTableAlias(),
filterTypeName,
queryBuilder,
returnType,
null
);
if (sqlFragment != null) {
queryBuilder.where(sqlFragment);
}
}
},
};
});
return extend(
args,
{
filter: {
description:
"A filter to be used in determining which values should be returned by the collection.",
type: FilterType,
},
},
`Adding connection filter arg to field '${field.name}' of '${Self.name}'`
);
}
);
builder.hook("build", (build) => {
const {
extend,
graphql: { getNamedType, GraphQLInputObjectType, GraphQLList },
inflection,
pgIntrospectionResultsByKind: introspectionResultsByKind,
pgGetGqlInputTypeByTypeIdAndModifier,
pgGetGqlTypeByTypeIdAndModifier,
pgSql: sql,
} = build;
const connectionFilterResolvers: { [typeName: string]: any } = {};
const connectionFilterTypesByTypeName: {
[typeName: string]: any;
} = {};
const handleNullInput = () => {
if (!connectionFilterAllowNullInput) {
throw new Error(
"Null literals are forbidden in filter argument input."
);
}
return null;
};
const handleEmptyObjectInput = () => {
if (!connectionFilterAllowEmptyObjectInput) {
throw new Error(
"Empty objects are forbidden in filter argument input."
);
}
return null;
};
const isEmptyObject = (obj: any) =>
typeof obj === "object" &&
obj !== null &&
!Array.isArray(obj) &&
Object.keys(obj).length === 0;
const connectionFilterRegisterResolver = (
typeName: string,
fieldName: string,
resolve: any
) => {
connectionFilterResolvers[typeName] = extend(
connectionFilterResolvers[typeName] || {},
{ [fieldName]: resolve }
);
};
const connectionFilterResolve = (
obj: any,
sourceAlias: SQL,
typeName: string,
queryBuilder: QueryBuilder,
pgType: PgType,
pgTypeModifier: number,
parentFieldName: string,
parentFieldInfo: { backwardRelationSpec: BackwardRelationSpec }
) => {
if (obj == null) return handleNullInput();
if (isEmptyObject(obj)) return handleEmptyObjectInput();
const sqlFragments = Object.entries(obj)
.map(([key, value]) => {
if (value == null) return handleNullInput();
if (isEmptyObject(value)) return handleEmptyObjectInput();
const resolversByFieldName = connectionFilterResolvers[typeName];
if (resolversByFieldName && resolversByFieldName[key]) {
return resolversByFieldName[key]({
sourceAlias,
fieldName: key,
fieldValue: value,
queryBuilder,
pgType,
pgTypeModifier,
parentFieldName,
parentFieldInfo,
});
}
throw new Error(`Unable to resolve filter field '${key}'`);
})
.filter((x) => x != null);
return sqlFragments.length === 0
? null
: sql.query`(${sql.join(sqlFragments, ") and (")})`;
};
// Get or create types like IntFilter, StringFilter, etc.
const connectionFilterOperatorsType = (
newWithHooks: any,
pgTypeId: number,
pgTypeModifier: number
) => {
const pgType = introspectionResultsByKind.typeById[pgTypeId];
const allowedPgTypeTypes = ["b", "d", "e", "r"];
if (!allowedPgTypeTypes.includes(pgType.type)) {
// Not a base, domain, enum, or range type? Skip.
return null;
}
// Perform some checks on the simple type (after removing array/range/domain wrappers)
const pgGetNonArrayType = (pgType: PgType) =>
pgType.isPgArray && pgType.arrayItemType
? pgType.arrayItemType
: pgType;
const pgGetNonRangeType = (pgType: PgType) =>
(pgType as any).rangeSubTypeId
? introspectionResultsByKind.typeById[(pgType as any).rangeSubTypeId]
: pgType;
const pgGetNonDomainType = (pgType: PgType) =>
pgType.type === "d" && pgType.domainBaseTypeId
? introspectionResultsByKind.typeById[pgType.domainBaseTypeId]
: pgType;
const pgGetSimpleType = (pgType: PgType) =>
pgGetNonDomainType(pgGetNonRangeType(pgGetNonArrayType(pgType)));
const pgSimpleType = pgGetSimpleType(pgType);
if (!pgSimpleType) return null;
if (
!(
pgSimpleType.type === "e" ||
(pgSimpleType.type === "b" && !pgSimpleType.isPgArray)
)
) {
// Haven't found an enum type or a non-array base type? Skip.
return null;
}
if (pgSimpleType.name === "json") {
// The PG `json` type has no valid operators.
// Skip filter type creation to allow the proper
// operators to be exposed for PG `jsonb` types.
return null;
}
// Establish field type and field input type
const fieldType:
| GraphQLType
| undefined = pgGetGqlTypeByTypeIdAndModifier(pgTypeId, pgTypeModifier);
if (!fieldType) return null;
const fieldInputType:
| GraphQLType
| undefined = pgGetGqlInputTypeByTypeIdAndModifier(
pgTypeId,
pgTypeModifier
);
if (!fieldInputType) return null;
// Avoid exposing filter operators on unrecognized types that PostGraphile handles as Strings
const namedType = getNamedType(fieldType);
const namedInputType = getNamedType(fieldInputType);
const actualStringPgTypeIds = [
"1042", // bpchar
"18", // char
"19", // name
"25", // text
"1043", // varchar
];
// Include citext as recognized String type
const citextPgType = (introspectionResultsByKind.type as PgType[]).find(
(t) => t.name === "citext"
);
if (citextPgType) {
actualStringPgTypeIds.push(citextPgType.id);
}
if (
namedInputType &&
namedInputType.name === "String" &&
!actualStringPgTypeIds.includes(pgSimpleType.id)
) {
// Not a real string type? Skip.
return null;
}
// Respect `connectionFilterAllowedFieldTypes` config option
if (
connectionFilterAllowedFieldTypes &&
!connectionFilterAllowedFieldTypes.includes(namedType.name)
) {
return null;
}
const pgConnectionFilterOperatorsCategory = pgType.isPgArray
? "Array"
: pgType.rangeSubTypeId
? "Range"
: pgType.type === "e"
? "Enum"
: pgType.type === "d"
? "Domain"
: "Scalar";
// Respect `connectionFilterArrays` config option
if (
pgConnectionFilterOperatorsCategory === "Array" &&
!connectionFilterArrays
) {
return null;
}
const rangeElementInputType = pgType.rangeSubTypeId
? pgGetGqlInputTypeByTypeIdAndModifier(
pgType.rangeSubTypeId,
pgTypeModifier
)
: null;
const domainBaseType =
pgType.type === "d"
? pgGetGqlTypeByTypeIdAndModifier(
pgType.domainBaseTypeId,
pgType.domainTypeModifier
)
: null;
const isListType = fieldType instanceof GraphQLList;
const operatorsTypeName = isListType
? inflection.filterFieldListType(namedType.name)
: inflection.filterFieldType(namedType.name);
const existingType = connectionFilterTypesByTypeName[operatorsTypeName];
if (existingType) {
if (
typeof existingType._fields === "object" &&
Object.keys(existingType._fields).length === 0
) {
// Existing type is fully defined and
// there are no fields, so don't return a type
return null;
}
// Existing type isn't fully defined or is
// fully defined with fields, so return it
return existingType;
}
return newWithHooks(
GraphQLInputObjectType,
{
name: operatorsTypeName,
description: `A filter to be used against ${namedType.name}${
isListType ? " List" : ""
} fields. All fields are combined with a logical ‘and.’`,
},
{
isPgConnectionFilterOperators: true,
pgConnectionFilterOperatorsCategory,
fieldType,
fieldInputType,
rangeElementInputType,
domainBaseType,
},
true
);
};
const connectionFilterType = (
newWithHooks: any,
filterTypeName: string,
source: PgClass | PgProc,
nodeTypeName: string
) => {
const existingType = connectionFilterTypesByTypeName[filterTypeName];
if (existingType) {
if (
typeof existingType._fields === "object" &&
Object.keys(existingType._fields).length === 0
) {
// Existing type is fully defined and
// there are no fields, so don't return a type
return null;
}
// Existing type isn't fully defined or is
// fully defined with fields, so return it
return existingType;
}
return newWithHooks(
GraphQLInputObjectType,
{
description: `A filter to be used against \`${nodeTypeName}\` object types. All fields are combined with a logical ‘and.’`,
name: filterTypeName,
},
{
pgIntrospection: source,
isPgConnectionFilter: true,
},
true
);
};
const escapeLikeWildcards = (input: string) => {
if ("string" !== typeof input) {
throw new Error("Non-string input was provided to escapeLikeWildcards");
} else {
return input.split("%").join("\\%").split("_").join("\\_");
}
};
const addConnectionFilterOperator: AddConnectionFilterOperator = (
typeNames,
operatorName,
description,
resolveType,
resolve,
options = {}
) => {
if (!typeNames) {
const msg = `Missing first argument 'typeNames' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!operatorName) {
const msg = `Missing second argument 'operatorName' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!resolveType) {
const msg = `Missing fourth argument 'resolveType' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
if (!resolve) {
const msg = `Missing fifth argument 'resolve' in call to 'addConnectionFilterOperator' for operator '${operatorName}'`;
throw new Error(msg);
}
const { connectionFilterScalarOperators } = build;
const gqlTypeNames = Array.isArray(typeNames) ? typeNames : [typeNames];
for (const gqlTypeName of gqlTypeNames) {
if (!connectionFilterScalarOperators[gqlTypeName]) {
connectionFilterScalarOperators[gqlTypeName] = {};
}
if (connectionFilterScalarOperators[gqlTypeName][operatorName]) {
const msg = `Operator '${operatorName}' already exists for type '${gqlTypeName}'.`;
throw new Error(msg);
}
connectionFilterScalarOperators[gqlTypeName][operatorName] = {
description,
resolveType,
resolve,
// These functions may exist on `options`: resolveSqlIdentifier, resolveSqlValue, resolveInput
...options,
};
}
};
return extend(build, {
connectionFilterTypesByTypeName,
connectionFilterRegisterResolver,
connectionFilterResolve,
connectionFilterOperatorsType,
connectionFilterType,
escapeLikeWildcards,
addConnectionFilterOperator,
});
});
};
export interface ConnectionFilterResolver {
(input: {
sourceAlias: SQL;
fieldName: string;
fieldValue?: unknown;
queryBuilder: QueryBuilder;
pgType: PgType;
pgTypeModifier: number | null;
parentFieldName: string;
parentFieldInfo?: { backwardRelationSpec?: BackwardRelationSpec };
}): SQL | null;
}
export interface AddConnectionFilterOperator {
(
typeNames: string | string[],
operatorName: string,
description: string | null,
resolveType: (
fieldInputType: GraphQLInputType,
rangeElementInputType: GraphQLInputType
) => GraphQLType,
resolve: (
sqlIdentifier: SQL,
sqlValue: SQL,
input: unknown,
parentFieldName: string,
queryBuilder: QueryBuilder
) => SQL | null,
options?: {
resolveInput?: (input: unknown) => unknown;
resolveSqlIdentifier?: (
sqlIdentifier: SQL,
pgType: PgType,
pgTypeModifier: number | null
) => SQL;
resolveSqlValue?: (
input: unknown,
pgType: PgType,
pgTypeModifier: number | null,
resolveListItemSqlValue?: any
) => SQL | null;
}
): void;
}
export default PgConnectionArgFilterPlugin; | the_stack |
// based on https://github.com/jorgebucaran/ultradom
export interface VElement {
nodeName: string
attributes: VAttributes
children: VNode[]
key?: string | number
}
export type VNode = VElement | string | number
export interface VAttributes extends VLifecycle {
key?: string | number
}
// pickle mod
export interface VLifecycle {
onAttached? (el: Element, attrs? : VAttributes) : void
onBeforeUpdate? (el: Element, attrs?: VAttributes) : void
onUpdated? (el: Element, attrs?: VAttributes) : void
onBeforeRemove? (el: Element) : Promise<void>
onRemoved? (el: Element) : void
}
// pickle mod
export function isVElement(vnode?: VNode): vnode is VElement {
return vnode && vnode["attributes"]
}
// pickle mod
function squash (children:any[]) {
var squashed: any[] = []
for (var x of children)
if (!Array.isArray(x)) {
if (x !== null && x !== undefined)
squashed.push (x)
}
else
for (var y of squash (x)) // pickle mod: overly recursive?
squashed.push (y)
return squashed
}
export function createVElement(name: string | Function, attributes: VAttributes, ...children: any[]): VElement
{
children = squash (children)
return typeof name === "function"
? name(attributes || {}, children)
: {
nodeName: name,
attributes: attributes || {},
children: children,
key: attributes && attributes.key
}
}
export function patch (velement: VElement, element?: Element) {
var lifecycleCallbacks: (() => void)[] = []
element = <Element> patchElement(
element && (<any>element).parentNode,
element,
element && (<any>element).node == null
? recycleElement(element, [].map)
: element && (<any>element).node,
velement,
lifecycleCallbacks,
element != null && (<any>element).node == null // is recycling
)
element["node"] = velement // pickle mod
while (lifecycleCallbacks.length)
lifecycleCallbacks.pop()!() // pickle mod
return element
}
function recycleElement(element: Element, map: Function) {
return {
nodeName: element.nodeName.toLowerCase(),
attributes: {},
children: map.call(element.childNodes, function (element: Element) {
return element.nodeType === 3 // Node.TEXT_NODE
? element.nodeValue
: recycleElement(element, map)
})
}
}
export function merge (dominant: any, recessive: any) { // pickle mod
var obj = {}
for (var i in recessive) obj[i] = recessive[i]
for (var i in dominant) obj[i] = dominant[i]
return obj
}
function getKey(node: VNode) {
return isVElement(node) ? node.key : null
}
// pickle mods (needs to work with qt browser)
function updateAttribute(element: Element, name: string, value: any, oldValue: any, isSVG: boolean) {
if (name === "key")
return
if (typeof value === "function")
element[name] = value
else if (value != null && value !== false)
element.setAttribute(name, value)
if (value == null || value === false)
element.removeAttribute(name)
}
function createNode(vnode: VNode, callbacks: any[], isSVG: boolean) {
var node =
typeof vnode === "string" || typeof vnode === "number"
? document.createTextNode("" + vnode) // pickle mod
: (isSVG = (isSVG || vnode.nodeName === "svg"))
? document.createElementNS("http://www.w3.org/2000/svg", vnode.nodeName)
: document.createElement(vnode.nodeName)
if (isVElement(vnode)) { // pickle mod
var attributes = vnode.attributes
if (attributes) {
if (attributes.onAttached) {
callbacks.push(function () {
attributes.onAttached!(<Element>node, attributes) // pickle mod
})
}
for (var i = 0; i < vnode.children.length; i++) {
node.appendChild(createNode(vnode.children[i], callbacks, isSVG))
}
for (var name in attributes) {
updateAttribute(<Element>node, name, attributes[name], null, isSVG)
}
}
}
return node
}
function updateElement(
element: Element,
oldAttributes: VAttributes,
attributes: VAttributes,
callbacks: any[],
isRecycling: boolean,
isSVG: boolean
) {
for (var name in merge (attributes, oldAttributes)) {
if (
attributes[name] !==
(name === "value" || name === "checked"
? element[name]
: oldAttributes[name])
) {
updateAttribute(
element,
name,
attributes[name],
oldAttributes[name],
isSVG
)
}
}
// pickle mods
if (! isRecycling && attributes.onBeforeUpdate) {
attributes.onBeforeUpdate(element, attributes)
}
// pickle mods
if (! isRecycling && attributes.onUpdated)
callbacks.push (() => attributes.onUpdated! (element, oldAttributes))
else if (isRecycling && attributes.onAttached)
callbacks.push (() => attributes.onAttached! (element, oldAttributes))
}
function removeChildren(element: Element, node: VNode) {
if (isVElement(node)) { // pickle mod
var attributes = node.attributes
if (attributes) {
for (var i = 0; i < node.children.length; i++) {
removeChildren(<Element>element.childNodes[i], node.children[i])
}
if (attributes.onRemoved) {
attributes.onRemoved(element)
}
}
}
return element
}
// pickle mod
async function removeNode(parent: Element, element: Node, vnode: VNode)
{
if (isVElement (vnode)) {
element["removing"] = true
if (vnode.attributes.onBeforeRemove)
await vnode.attributes.onBeforeRemove (<Element>element)
removeChildren(<Element>element, vnode)
}
parent.removeChild(element)
}
function activeNodes (nodes: NodeList) {
var activeNodes = []
for (var x = 0; x < nodes.length; x++)
if (nodes[x]["removing"] !== true)
activeNodes.push (nodes[x])
return activeNodes
}
function patchElement(
parent: Element,
node: Node | undefined,
oldVNode: VNode | undefined,
vnode: VNode,
lifecycleCallbacks: Function[],
isRecycling: boolean,
isSVG = false
) {
if (vnode === oldVNode) {
} else if (oldVNode == null || oldVNode["nodeName"] !== vnode["nodeName"]) { // pickle mod
var newElement = createNode(vnode!, lifecycleCallbacks, isSVG)
if (parent) {
parent.insertBefore(newElement, node || null) // pickle mod
if (oldVNode != null) {
removeNode(parent, <Element>node, <VElement> oldVNode) // pickle mod
}
}
node = newElement
} else if (oldVNode["nodeName"] == null) { // pickle mod
node!.nodeValue = "" + vnode // pickle mod
} else {
updateElement(
<Element>node,
(<VElement>oldVNode).attributes,
(<VElement>vnode).attributes,
lifecycleCallbacks,
isRecycling,
(isSVG = (isSVG || (<VElement>vnode).nodeName === "svg"))
)
var oldKeyed = {}
var newKeyed = {}
var oldElements: Node[] = []
var oldChildren = (<VElement>oldVNode).children
var children = (<VElement>vnode).children
var active = activeNodes (node!.childNodes) // pickle mod (allow asynchronous removes)
for (var i = 0; i < oldChildren.length; i++) {
oldElements[i] = active[i] // pickle mod
var oldKey = getKey(oldChildren[i])
if (oldKey != null) {
oldKeyed[oldKey] = [oldElements[i], oldChildren[i]]
}
}
var i = 0
var k = 0
while (k < children.length) {
var oldKey = getKey(oldChildren[i])
var newKey = getKey(children[k])
if (oldKey && newKeyed[oldKey]) { // pickle mod
i++
continue
}
if (newKey == null || isRecycling) {
if (oldKey == null) {
patchElement(
<Element>node,
oldElements[i],
<VElement>oldChildren[i],
<VElement>children[k],
lifecycleCallbacks,
isRecycling,
isSVG
)
k++
}
i++
} else {
var keyedNode = oldKeyed[newKey] || []
if (oldKey === newKey) {
patchElement(
<Element>node,
keyedNode[0],
keyedNode[1],
<VElement>children[k],
lifecycleCallbacks,
isRecycling,
isSVG
)
i++
} else if (keyedNode[0]) {
patchElement(
<Element>node,
node!.insertBefore(keyedNode[0], oldElements[i]),
keyedNode[1],
<VElement>children[k],
lifecycleCallbacks,
isRecycling,
isSVG
)
} else {
patchElement(
<Element>node,
oldElements[i],
undefined, // pickle mod
<VElement>children[k],
lifecycleCallbacks,
isRecycling,
isSVG
)
}
newKeyed[newKey] = children[k]
k++
}
}
while (i < oldChildren.length) {
if (getKey(oldChildren[i]) == null) {
removeNode(<Element>node, <Element>oldElements[i], <VElement>oldChildren[i])
}
i++
}
for (var j in oldKeyed) {
if (!newKeyed[j]) {
removeNode(<Element>node, oldKeyed[j][0], oldKeyed[j][1])
}
}
}
return node
} | the_stack |
import React from 'react';
const icons = {
// back
back: (
<path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
),
// forward
forward: (
<path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z" />
),
// refresh
refresh: (
<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z" />
),
// zoom back
zoomBack: [
<path
key={'frame'}
d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"
/>,
<path key={'plus'} d="M12 10h-2v2H9v-2H7V9h2V7h1v2h2v1z" />,
],
fullScreen: [
<path key={'outsideSquares'} d="M0 0h24v24H0z" fill="none" />,
<path
key={'outsideCorners'}
d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"
/>,
],
exitFullScreen: [
<path key={'insideSquares'} d="M0 0h24v24H0z" fill="none" />,
<path
key={'outsideCorners'}
d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"
/>,
],
close: [
<path
key={'closeIcon'}
d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
/>,
<path key={'closeButton'} d="M0 0h24v24H0z" fill="none" />,
],
// save
save: (
<path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z" />
),
'close-regular': {
component: (
<g>
<g transform="translate(49.000000, 49.000000)">
<rect
transform="translate(151.000000, 151.434283) rotate(-45.000000) translate(-151.000000, -151.434283) "
x="133"
y="-44"
width="36"
height="390.868566"
/>
<rect
transform="translate(151.000000, 151.434283) rotate(45.000000) translate(-151.000000, -151.434283) "
x="133"
y="-44"
width="36"
height="390.868566"
/>
</g>
</g>
),
viewBox: '0 0 400 400',
},
leads: {
component: (
<g stroke="none" strokeWidth="1" fillRule="evenodd">
<g transform="translate(-80.000000, -183.000000)" fillRule="nonzero">
<g transform="translate(15.000000, 170.000000)">
<g transform="translate(65.000000, 17.000000)">
<g>
<path d="M19.1166667,15.6521739 L7.75,15.6521739 C6.89543333,15.6521739 6.2,14.949913 6.2,14.0869565 C6.2,14.0368696 6.21136667,12.8452174 7.1548,11.6713043 C7.6973,10.9972174 8.43716667,10.4629565 9.35373333,10.0831304 C10.4604333,9.624 11.8337333,9.39234783 13.4333333,9.39234783 C15.0329333,9.39234783 16.4052,9.62504348 17.5129333,10.0831304 C18.4295,10.4629565 19.1693667,10.9972174 19.7118667,11.6713043 C20.6563333,12.8452174 20.6666667,14.0368696 20.6666667,14.0869565 C20.6666667,14.949913 19.9712333,15.6521739 19.1166667,15.6521739 Z M7.23333333,14.090087 C7.23436667,14.3770435 7.46583333,14.6086957 7.75,14.6086957 L19.1166667,14.6086957 C19.4008333,14.6086957 19.6323,14.376 19.6333333,14.090087 C19.6323,14.0535652 19.6002667,13.1561739 18.8697,12.2806957 C17.8632333,11.0733913 15.9836,10.4358261 13.4333333,10.4358261 C10.8830667,10.4358261 9.00343333,11.0744348 7.99696667,12.2806957 C7.2664,13.1572174 7.23436667,14.0535652 7.23333333,14.090087 Z" />
<path d="M13.4333333,8.34782609 C11.1538,8.34782609 9.3,6.47582609 9.3,4.17391304 C9.3,1.872 11.1538,0 13.4333333,0 C15.7128667,0 17.5666667,1.872 17.5666667,4.17391304 C17.5666667,6.47582609 15.7128667,8.34782609 13.4333333,8.34782609 Z M13.4333333,1.04347826 C11.7242,1.04347826 10.3333333,2.448 10.3333333,4.17391304 C10.3333333,5.89982609 11.7242,7.30434783 13.4333333,7.30434783 C15.1424667,7.30434783 16.5333333,5.89982609 16.5333333,4.17391304 C16.5333333,2.448 15.1424667,1.04347826 13.4333333,1.04347826 Z" />
<path d="M4.65,15.6521739 L1.55,15.6521739 C0.695433333,15.6521739 0,14.949913 0,14.0869565 C0,14.0483478 0.00826666667,13.1196522 0.6851,12.2086957 C1.0757,11.6817391 1.6089,11.2653913 2.2692,10.9690435 C3.05866667,10.6142609 4.03413333,10.4347826 5.1677,10.4347826 C5.35266667,10.4347826 5.53556667,10.44 5.71226667,10.4493913 C5.99746667,10.4650435 6.2155,10.7102609 6.20103333,10.9982609 C6.18656667,11.2862609 5.9427,11.5074783 5.6575,11.4918261 C5.4994,11.4834783 5.3351,11.4793043 5.16873333,11.4793043 C1.14493333,11.4793043 1.0385,13.9617391 1.0354,14.0911304 C1.03643333,14.3770435 1.2679,14.6097391 1.55206667,14.6097391 L4.65206667,14.6097391 C4.93726667,14.6097391 5.16873333,14.8434783 5.16873333,15.1314783 C5.16873333,15.4194783 4.93726667,15.6532174 4.65206667,15.6532174 L4.65,15.6521739 Z" />
<path d="M5.16666667,9.39130435 C3.45753333,9.39130435 2.06666667,7.98678261 2.06666667,6.26086957 C2.06666667,4.53495652 3.45753333,3.13043478 5.16666667,3.13043478 C6.8758,3.13043478 8.26666667,4.53495652 8.26666667,6.26086957 C8.26666667,7.98678261 6.8758,9.39130435 5.16666667,9.39130435 Z M5.16666667,4.17391304 C4.0269,4.17391304 3.1,5.10991304 3.1,6.26086957 C3.1,7.41182609 4.0269,8.34782609 5.16666667,8.34782609 C6.30643333,8.34782609 7.23333333,7.41182609 7.23333333,6.26086957 C7.23333333,5.10991304 6.30643333,4.17391304 5.16666667,4.17391304 Z" />
</g>
</g>
</g>
</g>
</g>
),
},
'resize-regular': {
component: (
<g transform="translate(0.000000, -10.000000)">
<polygon
transform="translate(319.028800, 100.804257) rotate(45.000000) translate(-319.028800, -100.804257) "
points="319.0288 56.9400268 417.723317 144.668486 220.334283 144.668486"
/>
<polygon
transform="translate(100.804257, 319.028800) rotate(225.000000) translate(-100.804257, -319.028800) "
points="100.804257 275.16457 199.498774 362.893029 2.10973956 362.893029"
/>
<rect
transform="translate(216.424915, 203.265646) rotate(45.000000) translate(-216.424915, -203.265646) "
x="196.686011"
y="59.6102934"
width="39.4778068"
height="287.310705"
/>
</g>
),
viewBox: '0 0 400 400',
},
restore: {
component: (
<g transform="translate(2.000000, 2.000000)">
<polygon
transform="translate(6.000000, 5.978022) rotate(45.000000) translate(-6.000000, -5.978022) "
points="5.56043956 -2.02549434 6.43956044 -2.02549434 6.43956044 4.80212161 6 5.97802198 6.43956044 6.92599193 6.43956044 13.9815383 5.56043956 13.9815383 5.56043956 6.84405952 6 5.97802198 5.56043956 5.14443388"
/>
<polygon
transform="translate(7.249401, 4.743907) rotate(-135.000000) translate(-7.249401, -4.743907) "
points="7.24940139 2.98566512 11.2054453 6.50214864 3.29335743 6.50214864"
/>
<polygon
transform="translate(4.743907, 7.249401) rotate(45.000000) translate(-4.743907, -7.249401) "
points="4.74390688 5.49115963 8.69995084 9.00764315 0.787862925 9.00764315"
/>
</g>
),
viewBox: '0 0 16 16',
},
minimize: {
component: (
<rect
transform="translate(0, -20)"
x="60"
y="318"
width="280"
height="36"
/>
),
viewBox: '0 0 400 400',
},
expand: {
component: <rect x="60" y="46.359375" width="280" height="36" />,
viewBox: '0 0 400 400',
},
'pin-up': {
component: (
<g transform="translate(94.000000, 46.000000)">
<rect x="90" y="160" width="36" height="148" />
<rect
transform="translate(105.500000, 160.000000) rotate(90.000000) translate(-105.500000, -160.000000) "
x="87.5"
y="54.5"
width="36"
height="211"
/>
<path d="M43,0 L169,0 L169,148 L43,148 L43,0 Z M79,36 L79,145 L106,145 L106,36 L79,36 Z" />
</g>
),
viewBox: '0 0 400 400',
},
'pin-down': {
component: (
<g transform="translate(199.500000, 200.000000) rotate(90.000000) translate(-199.500000, -200.000000) translate(94.000000, 46.000000)">
<rect x="90" y="160" width="36" height="148" />
<rect
transform="translate(105.500000, 160.000000) rotate(90.000000) translate(-105.500000, -160.000000) "
x="87.5"
y="54.5"
width="36"
height="211"
/>
<path d="M43,0 L169,0 L169,148 L43,148 L43,0 Z M79,36 L79,145 L106,145 L106,36 L79,36 Z" />
</g>
),
viewBox: '0 0 400 400',
},
print: {
component: (
<g transform="translate(49.000000, 50.000000)">
<path d="M231,99 L251,99 L251,0 L69,0 L69,99 L89,99 L89,20.1114925 L231,20.1114925 L231,99 Z" />
<path d="M69,209.959999 L69,229.962121 L0,229.962121 L0,113.991104 C0,105.711746 6.71525269,99 14.9908423,99 L303.009158,99 C311.288371,99 318,105.71983 318,113.991104 L318,229.962121 L250.714286,229.962121 L250.714286,209.959999 L298,209.959999 L298,133.994706 C298,125.725445 291.28618,119 283.004264,119 L34.9957363,119 C26.7170743,119 20,125.713359 20,133.994706 L20,209.959999 L69,209.959999 Z" />
<path d="M69,172 L250.714286,172 L250.714286,294.083333 L69,294.083333 L69,172 Z M89,192 L89,274.080002 L230.710007,274.080002 L230.710007,192 L89,192 Z" />
<ellipse
cx="50.728223"
cy="143.757576"
rx="17.728223"
ry="17.7575758"
/>
</g>
),
viewBox: '0 0 400 400',
},
pin: {
component: (
<g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g transform="translate(-48.000000, -12.000000)" fill="#495E85">
<g transform="translate(48.000000, 12.000000)">
<rect x="6.583333335" y="4.375" width="7.83333333" height="8.125" />
<rect
x="4.916666665"
y="12.5"
width="11.16666667"
height="2.0825"
/>
<rect
x="9.666666665"
y="14.5825"
width="1.66666667"
height="5.79"
/>
</g>
</g>
</g>
),
},
collapse: {
component: (
<g stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g transform="translate(-19.000000, -16.000000)" fill="#495E85">
<rect x="21" y="19.5" width="19" height="2" />
</g>
</g>
),
},
};
const Icon = ({ type = 'back', size = 23, viewBox = '0 0 24 24', ...rest }) => {
// because different icons have different vieBoxes
const icon = icons[type];
const actialViewBox = icon.viewBox ? icon.viewBox : viewBox;
return (
<svg height={size} viewBox={actialViewBox} width={size} {...rest}>
{icon.component || icon}
</svg>
);
};
export default Icon; | the_stack |
import { Loki } from "../../src/loki";
import { Collection } from "../../src/collection";
import { LokiOperatorPackageMap } from "../../src/operator_packages";
describe("Testing operators", () => {
interface Tree {
text: string;
value: string;
id: number;
order: number;
parents_id: number[];
level: number;
open: boolean;
checked: boolean;
}
let db: Loki;
let tree: Collection<Tree>;
let res;
beforeEach(() => {
db = new Loki("testOps");
tree = db.addCollection<Tree>("tree");
/*
* The following data represents a tree that should look like this:
*
├A
├B
└───┐
├C
├D
└───┐
├E
├F
├G
└───┐
├H
├I
└───┐
├J
├K
├L
├M
├N
└───┐
├O
├P
└───┐
├Q
└───┐
├R
└───┐
├S
├T
├U
├V
├W
├X
└───┐
├Y
├Z
*
*/
tree.insert([
{text: "A", value: "a", id: 1, order: 1, parents_id: [], level: 0, open: true, checked: false},
{text: "B", value: "b", id: 2, order: 2, parents_id: [], level: 0, open: true, checked: false},
{text: "C", value: "c", id: 3, order: 3, parents_id: [2], level: 1, open: true, checked: false},
{text: "D", value: "d", id: 4, order: 4, parents_id: [], level: 0, open: true, checked: false},
{text: "E", value: "e", id: 5, order: 5, parents_id: [4], level: 1, open: true, checked: false},
{text: "F", value: "f", id: 6, order: 6, parents_id: [4], level: 1, open: true, checked: false},
{text: "G", value: "g", id: 7, order: 7, parents_id: [], level: 0, open: true, checked: false},
{text: "H", value: "h", id: 8, order: 8, parents_id: [7], level: 1, open: true, checked: false},
{text: "I", value: "i", id: 9, order: 9, parents_id: [7], level: 1, open: true, checked: false},
{text: "J", value: "j", id: 10, order: 10, parents_id: [7, 9], level: 2, open: true, checked: false},
{text: "K", value: "k", id: 11, order: 11, parents_id: [7, 9], level: 2, open: true, checked: false},
{text: "L", value: "l", id: 12, order: 12, parents_id: [7], level: 1, open: true, checked: false},
{text: "M", value: "m", id: 13, order: 13, parents_id: [7], level: 1, open: true, checked: false},
{text: "N", value: "n", id: 14, order: 14, parents_id: [], level: 0, open: true, checked: false},
{text: "O", value: "o", id: 15, order: 15, parents_id: [14], level: 1, open: true, checked: false},
{text: "P", value: "p", id: 16, order: 16, parents_id: [14], level: 1, open: true, checked: false},
{text: "Q", value: "q", id: 17, order: 17, parents_id: [14, 16], level: 2, open: true, checked: false},
{text: "R", value: "r", id: 18, order: 18, parents_id: [14, 16, 17], level: 3, open: true, checked: false},
{text: "S", value: "s", id: 19, order: 19, parents_id: [14, 16, 17, 18], level: 4, open: true, checked: false},
{text: "T", value: "t", id: 20, order: 20, parents_id: [14, 16, 17], level: 3, open: true, checked: false},
{text: "U", value: "u", id: 21, order: 21, parents_id: [14, 16], level: 2, open: true, checked: false},
{text: "V", value: "v", id: 22, order: 22, parents_id: [14], level: 1, open: true, checked: false},
{text: "W", value: "w", id: 23, order: 23, parents_id: [], level: 0, open: true, checked: false},
{text: "X", value: "x", id: 24, order: 24, parents_id: [], level: 0, open: true, checked: false},
{text: "Y", value: "y", id: 25, order: 25, parents_id: [24], level: 1, open: true, checked: false},
{text: "Z", value: "z", id: 26, order: 26, parents_id: [24], level: 1, open: true, checked: false}
]);
});
it("$size works", () => {
res = tree
.chain()
.find({
"parents_id": {"$size": 4}
});
expect(res.data().length).toEqual(1);
expect(res.data()[0].value).toEqual("s");
});
});
describe("Individual operator tests", () => {
it("$ne op works as expected with 'loki' comparator", () => {
expect(LokiOperatorPackageMap["loki"].$ne(15, 20)).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$ne(15, 15.0)).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$ne(0, "0")).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$ne(NaN, NaN)).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$ne("en", NaN)).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$ne(0, NaN)).toEqual(true);
});
it("misc eq ops works as expected", () => {
expect(LokiOperatorPackageMap["loki"].$eq(1, 11)).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$eq(1, "1")).toEqual(true);
const dt1 = new Date();
const dt2 = new Date();
dt2.setTime(dt1.getTime());
const dt3 = new Date();
dt3.setTime(dt1.getTime() - 10000);
expect(LokiOperatorPackageMap["loki"].$eq(dt1, dt2)).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$eq(dt1, dt3)).toEqual(false);
});
it("$type op works as expected", () => {
expect(LokiOperatorPackageMap["loki"].$type("test", "string")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$type(4, "number")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$type({a: 1}, "object")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$type(new Date(), "date")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$type([1, 2], "array")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$type("test", "number")).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$type(4, "string")).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$type({a: 1}, "date")).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$type(new Date(), "object")).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$type([1, 2], "number")).toEqual(false);
});
it("$in op works as expected", () => {
expect(LokiOperatorPackageMap["loki"].$in(4, [1, 2, 3, 4])).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$in(7, [1, 2, 3, 4])).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$in("el", "hello")).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$in("le", "hello")).toEqual(false);
});
it("$between op works as expected", () => {
expect(LokiOperatorPackageMap["loki"].$between(75, [5, 100])).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$between(75, [75, 100])).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$between(75, [5, 75])).toEqual(true);
expect(LokiOperatorPackageMap["loki"].$between(75, [5, 74])).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$between(75, [76, 100])).toEqual(false);
expect(LokiOperatorPackageMap["loki"].$between(null, [5, 100])).toEqual(false);
});
it("$between find works as expected", () => {
// test unindexed code path
let db = new Loki("db");
interface User {
name: string;
count: number;
}
let coll: Collection<User> = db.addCollection<User>("coll");
coll.insert({name: "mjolnir", count: 73});
coll.insert({name: "gungnir", count: 5});
coll.insert({name: "tyrfing", count: 15});
coll.insert({name: "draupnir", count: 132});
// simple inner between
let results = coll.chain().find({count: {$between: [10, 80]}}).simplesort("count").data();
expect(results.length).toEqual(2);
expect(results[0].count).toEqual(15);
expect(results[1].count).toEqual(73);
// range exceeds bounds
results = coll.find({count: {$between: [100, 200]}});
expect(results.length).toEqual(1);
expect(results[0].count).toEqual(132);
// no matches in range
expect(coll.find({count: {$between: [133, 200]}}).length).toEqual(0);
expect(coll.find({count: {$between: [1, 4]}}).length).toEqual(0);
// multiple low and high bounds
db = new Loki("db");
coll = db.addCollection<User>("coll");
coll.insert({name: "first", count: 5});
coll.insert({name: "mjolnir", count: 15});
coll.insert({name: "gungnir", count: 15});
coll.insert({name: "tyrfing", count: 75});
coll.insert({name: "draupnir", count: 75});
coll.insert({name: "last", count: 100});
results = coll.chain().find({count: {$between: [15, 75]}}).simplesort("count").data();
expect(results.length).toEqual(4);
expect(results[0].count).toEqual(15);
expect(results[1].count).toEqual(15);
expect(results[2].count).toEqual(75);
expect(results[3].count).toEqual(75);
expect(coll.find({count: {$between: [-1, 4]}}).length).toEqual(0);
expect(coll.find({count: {$between: [-1, 5]}}).length).toEqual(1);
expect(coll.find({count: {$between: [-1, 6]}}).length).toEqual(1);
expect(coll.find({count: {$between: [99, 140]}}).length).toEqual(1);
expect(coll.find({count: {$between: [100, 140]}}).length).toEqual(1);
expect(coll.find({count: {$between: [101, 140]}}).length).toEqual(0);
expect(coll.find({count: {$between: [12, 76]}}).length).toEqual(4);
expect(coll.find({count: {$between: [20, 60]}}).length).toEqual(0);
// now test -indexed- code path
coll.ensureRangedIndex("count");
results = coll.chain().find({count: {$between: [15, 75]}}).simplesort("count").data();
expect(results.length).toEqual(4);
expect(results[0].count).toEqual(15);
expect(results[1].count).toEqual(15);
expect(results[2].count).toEqual(75);
expect(results[3].count).toEqual(75);
expect(coll.find({count: {$between: [-1, 4]}}).length).toEqual(0);
expect(coll.find({count: {$between: [-1, 5]}}).length).toEqual(1);
expect(coll.find({count: {$between: [-1, 6]}}).length).toEqual(1);
expect(coll.find({count: {$between: [99, 140]}}).length).toEqual(1);
expect(coll.find({count: {$between: [100, 140]}}).length).toEqual(1);
expect(coll.find({count: {$between: [101, 140]}}).length).toEqual(0);
expect(coll.find({count: {$between: [12, 76]}}).length).toEqual(4);
expect(coll.find({count: {$between: [20, 60]}}).length).toEqual(0);
});
it("indexed $in find works as expected", () => {
interface User {
name: string;
count: number;
}
// test unindexed code path
const db = new Loki("db");
const coll = db.addCollection<User>("coll", { rangedIndexes: { "count": {} } });
coll.insert({name: "mjolnir", count: 73});
coll.insert({name: "gungnir", count: 5});
coll.insert({name: "tyrfing", count: 15});
coll.insert({name: "draupnir", count: 132});
const results = coll.chain().find({count: {$in: [15, 73]}}).simplesort("count").data();
expect(results.length).toEqual(2);
expect(results[0].count).toEqual(15);
expect(results[1].count).toEqual(73);
});
it("$keyin and $nkeyin", () => {
interface User {
name: string;
}
const db = new Loki("db");
const coll = db.addCollection<User>("coll");
coll.insert({name: "mjolnir"});
let results = coll.find({name: {$keyin: {mjolnir: "not relevant"}}});
expect(results.length).toEqual(1);
results = coll.find({name: {$keyin: {mjolnir: undefined}}});
expect(results.length).toEqual(1);
results = coll.find({name: {$nkeyin: {mjolnir: "not relevant"}}});
expect(results.length).toEqual(0);
results = coll.find({name: {$nkeyin: {mjolnir: undefined}}});
expect(results.length).toEqual(0);
});
it("$definedin and $ndefinedin", () => {
interface User {
name: string;
}
const db = new Loki("db");
const coll = db.addCollection<User>("coll");
coll.insert({name: "mjolnir"});
let results = coll.find({name: {$definedin: {mjolnir: "not relevant"}}});
expect(results.length).toEqual(1);
results = coll.find({name: {$definedin: {mjolnir: undefined}}});
expect(results.length).toEqual(0);
results = coll.find({name: {$undefinedin: {mjolnir: "not relevant"}}});
expect(results.length).toEqual(0);
results = coll.find({name: {$undefinedin: {mjolnir: undefined}}});
expect(results.length).toEqual(1);
});
describe("$contains, $containsNone, $containsAny", () => {
describe("string", () => {
interface User {
name: string;
}
const db = new Loki("db");
const coll = db.addCollection<User>("coll");
coll.insert({name: "odin"});
coll.insert({name: "thor"});
coll.insert({name: "svafrlami"});
coll.insert({name: "arngrim"});
it("$contains", () => {
let results = coll.find({name: {$contains: "d"}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({name: {$contains: ["o", "i"]}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({name: {$contains: "x"}});
expect(results.length).toEqual(0);
});
it("$containsNone", () => {
let results = coll.find({name: {$containsNone: "d"}});
expect(results.length).toEqual(3);
expect(results[0].name).toEqual("thor");
expect(results[1].name).toEqual("svafrlami");
expect(results[2].name).toEqual("arngrim");
results = coll.find({name: {$containsNone: ["i", "o"]}});
expect(results.length).toEqual(0);
results = coll.find({name: {$containsNone: "x"}});
expect(results.length).toEqual(4);
});
it("$containsAny", () => {
let results = coll.find({name: {$containsAny: "d"}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({name: {$containsAny: ["o", "i"]}});
expect(results.length).toEqual(4);
results = coll.find({name: {$containsAny: "x"}});
expect(results.length).toEqual(0);
});
});
describe("array", () => {
interface User {
name: string;
weapons: string[];
}
const db = new Loki("db");
const coll = db.addCollection<User>("coll");
coll.insert({name: "odin", weapons: ["gungnir", "draupnir"]});
coll.insert({name: "thor", weapons: ["mjolnir"]});
coll.insert({name: "svafrlami", weapons: ["tyrfing"]});
coll.insert({name: "arngrim", weapons: ["tyrfing"]});
it("$contains", () => {
let results = coll.find({weapons: {$contains: ["gungnir", "draupnir"]}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({weapons: {$contains: ["mjolnir"]}});
expect(results).toEqual(coll.find({weapons: {$contains: "mjolnir"}}));
expect(results.length).toEqual(1);
coll.find({weapons: {$contains: "mjolnir"}});
results = coll.find({weapons: {$contains: ["mjolnir", "tyrfing"]}});
expect(results.length).toEqual(0);
});
it("$containsNone", () => {
let results = coll.find({weapons: {$containsNone: ["mjolnir", "tyrfing"]}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({weapons: {$containsNone: ["draupnir"]}});
expect(results.length).toEqual(3);
});
it("$containsAny", () => {
let results = coll.find({weapons: {$containsAny: ["gungnir", "mjolnir"]}});
expect(results.length).toEqual(2);
expect(results[0].name).toEqual("odin");
expect(results[1].name).toEqual("thor");
results = coll.find({weapons: {$containsAny: ["svafrlami"]}});
expect(results.length).toEqual(0);
});
});
describe("object", () => {
interface User {
name: string;
options: {
a?: boolean;
b?: boolean;
c?: boolean;
};
}
const db = new Loki("db");
const coll = db.addCollection<User>("coll");
coll.insert({name: "odin", options: {a: true, b: true}});
coll.insert({name: "thor", options: {a: true}});
coll.insert({name: "svafrlami", options: {}});
coll.insert({name: "arngrim", options: {b: true}});
it("$contains", () => {
let results = coll.find({options: {$contains: ["a", "b"]}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("odin");
results = coll.find({options: {$contains: ["a"]}});
expect(results).toEqual(coll.find({options: {$contains: "a"}}));
expect(results.length).toEqual(2);
expect(results[0].name).toEqual("odin");
expect(results[1].name).toEqual("thor");
results = coll.find({options: {$contains: ["c"]}});
expect(results.length).toEqual(0);
});
it("$containsNone", () => {
let results = coll.find({options: {$containsNone: ["a"]}});
expect(results).toEqual(coll.find({options: {$containsNone: "a"}}));
expect(results.length).toEqual(2);
expect(results[0].name).toEqual("svafrlami");
expect(results[1].name).toEqual("arngrim");
results = coll.find({options: {$containsNone: ["a", "b"]}});
expect(results.length).toEqual(1);
expect(results[0].name).toEqual("svafrlami");
results = coll.find({options: {$containsNone: ["c"]}});
expect(results.length).toEqual(4);
});
it("$containsAny", () => {
let results = coll.find({options: {$containsAny: ["a", "b"]}});
expect(results.length).toEqual(3);
expect(results[0].name).toEqual("odin");
expect(results[1].name).toEqual("thor");
expect(results[2].name).toEqual("arngrim");
results = coll.find({options: {$containsAny: ["b"]}});
expect(results).toEqual(coll.find({options: {$containsAny: "b"}}));
expect(results.length).toEqual( 2);
expect(results[0].name).toEqual("odin");
expect(results[1].name).toEqual("arngrim");
results = coll.find({options: {$containsAny: ["c"]}});
expect(results.length).toEqual(0);
});
});
});
it("ops work with mixed datatypes", () => {
const db = new Loki("db");
interface AB {
a: any;
b: number;
}
const coll = db.addCollection<AB>("coll", { defaultLokiOperatorPackage: "loki" });
coll.insert({a: null, b: 5});
coll.insert({a: "asdf", b: 5});
coll.insert({a: "11", b: 5});
coll.insert({a: 2, b: 5});
coll.insert({a: "1", b: 5});
coll.insert({a: "4", b: 5});
coll.insert({a: 7.2, b: 5});
coll.insert({a: "5", b: 5});
coll.insert({a: 4, b: 5});
coll.insert({a: "18.1", b: 5});
expect(coll.findOne({a: "asdf"}).a).toEqual("asdf");
// loki equality is abstract
expect(coll.find({a: 4}).length).toEqual(2);
expect(coll.find({a: "4"}).length).toEqual(2);
// default range ops (lt, lte, gt, gte, between) are loose
expect(coll.find({a: {$between: [4, 12]}}).length).toEqual(5); // "4", 4, "5", 7.2, "11"
expect(coll.find({a: {$gte: "7.2"}}).length).toEqual(4); // 7.2, "11", "18.1", "asdf" (strings after numbers)
expect(coll.chain().find({a: {$gte: "7.2"}}).find({a: {$finite: true}}).data().length).toEqual(3); // 7.2, "11", "18.1"
expect(coll.find({a: {$gt: "7.2"}}).length).toEqual(3); // "11", "18.1", "asdf"
expect(coll.find({a: {$lte: "7.2"}}).length).toEqual(7); // 7.2, "5", "4", 4, 2, 1, null
// expect same behavior when avl index is applied to property being queried
coll.ensureIndex("a");
expect(coll.findOne({a: "asdf"}).a).toEqual("asdf");
// loki equality is abstract, whether indexed or not
expect(coll.find({a: 4}).length).toEqual(2);
expect(coll.find({a: "4"}).length).toEqual(2);
// default range ops (lt, lte, gt, gte, between) are loose
expect(coll.find({a: {$between: [4, 12]}}).length).toEqual(5); // "4", 4, "5", 7.2, "11"
expect(coll.find({a: {$gte: "7.2"}}).length).toEqual(4); // 7.2, "11", "18.1", "asdf" (strings after numbers)
expect(coll.chain().find({a: {$gte: "7.2"}}).find({a: {$finite: true}}).data().length).toEqual(3); // 7.2, "11", "18.1"
expect(coll.find({a: {$gt: "7.2"}}).length).toEqual(3); // "11", "18.1", "asdf"
expect(coll.find({a: {$lte: "7.2"}}).length).toEqual(7); // 7.2, "5", "4", 4, 2, 1, null
});
}); | the_stack |
import type { Defs, CssSyntaxTokenizer } from './types';
import { checkMultiTypes } from './check-multi-types';
import { getCandicate } from './get-candicate';
import { matched, matches, unmatched } from './match-result';
import { splitUnit, isFloat, isUint, isInt } from './primitive';
import { isBCP47 } from './rfc/is-bcp-47';
import { Token, TokenCollection } from './token';
import { checkSerializedPermissionsPolicy } from './w3c/check-serialized-permissions-policy';
import { checkAutoComplete } from './whatwg/check-autocomplete';
import { checkDateTime } from './whatwg/check-datetime';
import { checkMIMEType } from './whatwg/check-mime-type';
import { isAbsURL } from './whatwg/is-abs-url';
import { isBrowserContextName } from './whatwg/is-browser-context-name';
import { isCustomElementName } from './whatwg/is-custom-element-name';
import { isItempropName } from './whatwg/is-itemprop-name';
export const types: Defs = {
Any: {
ref: '',
is: () => matched(),
},
NoEmptyAny: {
ref: '',
is: value => (0 < value.length ? matched() : unmatched(value, 'empty-token')),
},
OneLineAny: {
ref: '',
is: value => {
const tokens = new TokenCollection(value);
/**
* @see https://infra.spec.whatwg.org/#ascii-tab-or-newline
*/
const newline = ['\u000A', '\u000D'];
const newlineToken = tokens.search(newline);
if (newlineToken) {
return newlineToken.unmatched({
reason: 'unexpected-newline',
});
}
return matched();
},
},
Zero: {
ref: '',
expects: [
{
type: 'common',
value: 'zero',
},
],
is: value => (value === '0' ? matched() : unmatched(value, 'syntax-error')),
},
Number: {
ref: '',
expects: [
{
type: 'common',
value: 'number',
},
],
is: value => (isFloat(value) ? matched() : unmatched(value, 'unexpected-token')),
},
Int: {
ref: '',
expects: [
{
type: 'common',
value: 'integer',
},
],
is: value => (isInt(value) ? matched() : unmatched(value, 'unexpected-token')),
},
Uint: {
ref: '',
expects: [
{
type: 'common',
value: 'non-negative integer',
},
],
is: value => (isUint(value) ? matched() : unmatched(value, 'unexpected-token')),
},
XMLName: {
ref: 'https://www.w3.org/TR/xml/#NT-Name',
expects: [
{
type: 'format',
value: 'XML name',
},
],
is: value => {
// NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
const nameStartChar =
/[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u{10000}-\u{EFFFF}]/u;
// NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
const nameCharTail = /-|[.0-9\u00B7]|[\u0300-\u036F\u203F-\u2040]/;
// Name ::= NameStartChar (NameChar)*
const name = RegExp(`(?:${nameStartChar.source})(?:${nameCharTail})*`, 'u');
return name.test(value) ? matched() : unmatched(value, 'unexpected-token');
},
},
DOMID: {
ref: 'https://html.spec.whatwg.org/multipage/dom.html#global-attributes:concept-id',
expects: [
{
type: 'format',
value: 'ID',
},
],
is: value => {
const tokens = new TokenCollection(value);
const ws = tokens.search(Token.WhiteSpace);
if (ws) {
return ws.unmatched({
reason: 'unexpected-space',
});
}
if (!tokens.length) {
return unmatched(value, 'empty-token');
}
return matched();
},
},
FunctionBody: {
ref: '',
expects: [
{
type: 'syntax',
value: 'JavaScript',
},
],
// **NO IMPLEMENT PLAN NOW**
is: () => matched(),
},
Pattern: {
ref: 'https://html.spec.whatwg.org/multipage/input.html#compiled-pattern-regular-expression',
expects: [
{
type: 'common',
value: 'regular expression',
},
],
is: value => {
try {
new RegExp(`^(?:${value})$`);
} catch {
return unmatched(value);
}
return matched();
},
},
DateTime: {
ref: 'https://html.spec.whatwg.org/multipage/text-level-semantics.html#datetime-value',
expects: [
{
type: 'format',
value: 'date time',
},
],
is: checkDateTime(),
},
/**
* It doesn't check the meaningless number less than -1
* that is the same as -1.
* It is another rule.
*/
TabIndex: {
expects: [
{
type: 'common',
value: '-1',
},
{
type: 'common',
value: '0',
},
{
type: 'common',
value: 'non-negative integer',
},
],
ref: 'https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex',
is: matches(value => isInt(value)),
},
BCP47: {
expects: [
{
type: 'format',
value: 'BCP47',
},
],
ref: 'https://tools.ietf.org/rfc/bcp/bcp47.html',
is: matches(isBCP47(), { reason: 'unexpected-token' }),
},
/**
* **NO IMPLEMENT NEVER**
*
* We can evaluate the absolute URL through WHATWG API,
* but it isn't easy to check the relative URL.
* And the relative URL expects almost all of the characters.
* In short, this checking is meaningless.
*
* So it always returns the matched object.
*
* If you want to expect the URL without multi-byte characters,
* it should use another rule.
*/
URL: {
ref: 'https://html.spec.whatwg.org/multipage/urls-and-fetching.html#valid-url-potentially-surrounded-by-spaces',
is: () => matched(),
},
AbsoluteURL: {
ref: 'https://url.spec.whatwg.org/#syntax-url-absolute',
is: matches(isAbsURL()),
},
HashName: {
ref: 'https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-hash-name-reference',
expects: [
{
type: 'format',
value: 'hash name',
},
],
is: value => (value[0] === '#' ? matched() : unmatched(value, 'unexpected-token')),
},
OneCodePointChar: {
ref: 'https://html.spec.whatwg.org/multipage/interaction.html#the-accesskey-attribute',
expects: [
{
type: 'common',
value: 'one code point character',
},
],
is: value => (value.length === 1 ? matched() : unmatched(value, 'unexpected-token')),
},
CustomElementName: {
ref: 'https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name',
expects: [
{
type: 'format',
value: 'custom element name',
},
],
is: matches(isCustomElementName()),
},
BrowsingContextName: {
ref: 'https://html.spec.whatwg.org/multipage/browsers.html#browsing-context-names',
expects: [
{
type: 'common',
value: 'browsing context name',
},
],
// <iframe name="[HERE]">
is: matches(isBrowserContextName()),
},
BrowsingContextNameOrKeyword: {
ref: 'https://html.spec.whatwg.org/multipage/browsers.html#valid-browsing-context-name-or-keyword',
expects: [
{ type: 'const', value: '_blank' },
{ type: 'const', value: '_self' },
{ type: 'const', value: '_parent' },
{ type: 'const', value: '_top' },
{
type: 'common',
value: 'browsing context name',
},
],
// <a target="[HERE]">
is(value) {
value = value.toLowerCase();
const keywords = ['_blank', '_self', '_parent', '_top'];
if (keywords.includes(value)) {
return matched();
}
if (value[0] === '_') {
const candicate = getCandicate(value, keywords);
return unmatched(value, 'unexpected-token', { candicate });
}
return matches(isBrowserContextName())(value);
},
},
HTTPSchemaURL: {
ref: 'https://html.spec.whatwg.org/multipage/links.html#ping',
expects: [
{
type: 'format',
value: 'URL who schema is an HTTP(S) schema',
},
],
is(value) {
if (isAbsURL()(value)) {
return unmatched(value, 'unexpected-token');
}
if (/^https?/i.test(value)) {
return matched();
}
return unmatched(value, 'unexpected-token', {
expects: [
{
type: 'format',
value: 'HTTP(S) schema',
},
],
});
},
},
MIMEType: {
ref: 'https://mimesniff.spec.whatwg.org/#valid-mime-type',
expects: [
{
type: 'format',
value: 'MIME Type',
},
],
is: checkMIMEType(),
},
ItemProp: {
ref: 'https://html.spec.whatwg.org/multipage/microdata.html#names:-the-itemprop-attribute',
expects: [
{
type: 'common',
value: 'absolute URL',
},
{
type: 'format',
value: 'property name',
},
],
is(value) {
const _matched = matched();
const _unmatched = unmatched(value, 'unexpected-token');
return checkMultiTypes(value, [
value => (isAbsURL()(value) ? _matched : _unmatched),
value => (isItempropName()(value) ? _matched : _unmatched),
]);
},
},
Srcset: {
ref: 'https://html.spec.whatwg.org/multipage/images.html#srcset-attributes',
syntax: {
apply: '<srcset>',
def: {
srcset: '<image-candidate-strings> [, <image-candidate-strings>]*',
'image-candidate-strings': '<valid-non-empty-url> [ <width-descriptor> | <pixel-density-descriptor> ]?',
'valid-non-empty-url'(token, getNextToken) {
if (!token) {
return 0;
}
let willAdoptTokenLength = 0;
do {
if (token.type === 13) {
break;
}
willAdoptTokenLength++;
} while ((token = getNextToken(willAdoptTokenLength)));
return willAdoptTokenLength;
},
'width-descriptor'(token) {
if (!token) {
return 0;
}
const { num, unit } = splitUnit(token.value);
if (unit !== 'w') {
return 0;
}
if (!isUint(num)) {
return 0;
}
return 1;
},
'pixel-density-descriptor'(token) {
if (!token) {
return 0;
}
const { num, unit } = splitUnit(token.value);
if (unit !== 'x') {
return 0;
}
if (!isFloat(num)) {
return 0;
}
return 1;
},
},
},
},
SourceSizeList: {
ref: 'https://html.spec.whatwg.org/multipage/images.html#sizes-attributes',
expects: [
{
type: 'syntax',
value: '<source-size-list>',
},
],
syntax: {
apply: '<source-size-list>',
def: {
'source-size-list': '[ <source-size># , ]? <source-size-value>',
'source-size': '<media-condition> <source-size-value>',
'source-size-value': '<length>',
},
},
},
IconSize: {
ref: 'https://html.spec.whatwg.org/multipage/semantics.html#attr-link-sizes',
expects: [
{
type: 'const',
value: 'any',
},
{
type: 'syntax',
value: '[WIDTH]x[HEIGHT]',
},
],
is(value) {
value = value.toLowerCase();
if (value === 'any') {
return matched();
}
const tokens = new TokenCollection(value, { speificSeparator: 'x' });
const [width, sep, height, ...tail] = tokens;
if (!width) {
return unmatched(value, 'unexpected-token');
}
if (!sep) {
return width.unmatched({ reason: 'unexpected-token' });
}
if (!height) {
return sep.unmatched({ reason: 'unexpected-token' });
}
if (tail && tail.length) {
return tail[0].unmatched({ reason: 'extra-token' });
}
if (!isUint(width.value)) {
return width.unmatched({ reason: 'unexpected-token' });
}
if (width.value === '0') {
return width.unmatched({ reason: 'out-of-range' });
}
if (sep.value !== 'x') {
return sep.unmatched({ reason: 'out-of-range' });
}
if (!isUint(height.value)) {
return height.unmatched({ reason: 'unexpected-token' });
}
if (height.value === '0') {
return height.unmatched({ reason: 'out-of-range' });
}
return matched();
},
},
AutoComplete: {
ref: 'https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-autocomplete',
is: checkAutoComplete(),
},
Accept: {
ref: 'https://html.spec.whatwg.org/multipage/input.html#attr-input-accept',
expects: [
{
type: 'const',
value: 'audio/*',
},
{
type: 'const',
value: 'video/*',
},
{
type: 'const',
value: 'image/*',
},
{
type: 'format',
value: 'MIME Type',
},
{
type: 'format',
value: 'Extension',
},
],
// input[type=file] accept: { type: { token: "Accept", "separator": "comma" } }
is(value) {
const extMap = ['audio/*', 'video/*', 'image/*'];
if (extMap.includes(value)) return matched();
// A valid MIME type string with no parameters
const mimeMatched = checkMIMEType({ withoutParameters: true })(value);
if (mimeMatched.matched) return matched();
// A string whose first character is a U+002E FULL STOP character (.)
return value[0] === '.' && value[1] ? matched() : mimeMatched;
},
},
SerializedPermissionsPolicy: {
ref: 'https://w3c.github.io/webappsec-permissions-policy/#serialized-permissions-policy',
is: checkSerializedPermissionsPolicy(),
},
'<css-declaration-list>': {
ref: 'https://drafts.csswg.org/css-style-attr/#syntax',
syntax: {
apply: '<css-declaration-list>',
def: {
'css-declaration-list': '<declaration-list>',
},
},
},
'<class-list>': {
ref: 'https://www.w3.org/TR/SVG/styling.html#ClassAttribute',
syntax: {
apply: '<class-list>',
def: {
'class-list': '<ident-token>*',
},
},
},
'<svg-font-size>': {
ref: 'https://drafts.csswg.org/css-fonts-5/#descdef-font-face-font-size',
// TODO:
is: () => matched(),
},
'<svg-font-size-adjust>': {
ref: 'https://drafts.csswg.org/css-fonts-5/#propdef-font-size-adjust',
// TODO:
is: () => matched(),
},
"<'color-profile'>": {
ref: 'https://www.w3.org/TR/SVG11/color.html#ColorProfileProperty',
// TODO:
is: () => matched(),
},
"<'color-rendering'>": {
ref: 'https://www.w3.org/TR/SVG11/painting.html#ColorRenderingProperty',
// TODO:
is: () => matched(),
},
"<'enable-background'>": {
ref: 'https://www.w3.org/TR/SVG11/filters.html#EnableBackgroundProperty',
// TODO:
is: () => matched(),
},
'<list-of-svg-feature-string>': {
ref: 'https://www.w3.org/TR/SVG11/feature.html',
// TODO:
is: () => matched(),
},
'<animatable-value>': {
ref: 'https://svgwg.org/specs/animations/#FromAttribute',
// TODO:
is: () => matched(),
},
'<begin-value-list>': {
ref: 'https://svgwg.org/specs/animations/#BeginValueListSyntax',
// TODO:
is: () => matched(),
},
'<end-value-list>': {
ref: 'https://svgwg.org/specs/animations/#EndValueListSyntax',
// TODO:
is: () => matched(),
},
'<list-of-value>': {
ref: 'https://svgwg.org/specs/animations/#ValuesAttribute',
// TODO:
is: () => matched(),
},
'<clock-value>': {
ref: 'https://www.w3.org/TR/2001/REC-smil-animation-20010904/#Timing-ClockValueSyntax',
syntax: {
// TODO:
apply: '<clock-value>',
def: {
'clock-value': '<any-value>',
},
},
},
'<color-matrix>': {
ref: 'https://drafts.fxtf.org/filter-effects/#element-attrdef-fecolormatrix-values',
syntax: {
apply: '<color-matrix>',
def: {
'color-matrix': '[ <number-zero-one> [,]? ]{19} <number-zero-one>',
},
},
},
'<dasharray>': {
ref: 'https://svgwg.org/svg2-draft/painting.html#StrokeDasharrayProperty',
syntax: {
apply: '<dasharray>',
def: {
dasharray: '[ [ <svg-length> | <percentage> | <number> ]+ ]#',
},
},
},
'<key-points>': {
ref: 'https://svgwg.org/specs/animations/#KeyPointsAttribute',
syntax: {
apply: '<key-points>',
def: {
'key-points': '<number> [; <number>]* [;]?',
},
},
},
'<key-splines>': {
ref: 'https://svgwg.org/specs/animations/#KeyTimesAttribute',
syntax: {
apply: '<key-splines>',
def: {
'key-splines': '<control-point> [; <control-point>]* [;]?',
'control-point': '<number> [,]? <number> [,]? <number> [,]? <number>',
},
},
},
'<key-times>': {
ref: 'https://svgwg.org/specs/animations/#KeyTimesAttribute',
syntax: {
apply: '<key-times>',
def: {
'key-times': '<number> [; <number>]* [;]?',
},
},
},
'<system-language>': {
ref: 'https://svgwg.org/svg2-draft/struct.html#SystemLanguageAttribute',
syntax: {
apply: '<system-language>',
def: {
'system-language': '<bcp-47>#',
},
},
},
'<origin>': {
ref: 'https://www.w3.org/TR/2001/REC-smil-animation-20010904/#MotionOriginAttribute',
syntax: {
apply: '<origin>',
def: {
origin: 'default',
},
},
},
'<svg-path>': {
ref: 'https://svgwg.org/svg2-draft/paths.html#PathDataBNF',
syntax: {
apply: '<svg-path>',
// TODO:
def: {
'svg-path': '<any-value>',
},
},
},
'<points>': {
ref: 'https://svgwg.org/svg2-draft/shapes.html#DataTypePoints',
syntax: {
apply: '<points>',
def: {
points: '[ <number>+ ]#',
},
},
},
'<preserve-aspect-ratio>': {
ref: 'https://svgwg.org/svg2-draft/coords.html#PreserveAspectRatioAttribute',
syntax: {
apply: '<preserve-aspect-ratio>',
def: {
'preserve-aspect-ratio': '<align> <meet-or-slice>?',
align: 'none | xMinYMin | xMidYMin | xMaxYMin | xMinYMid | xMidYMid | xMaxYMid| xMinYMax | xMidYMax | xMaxYMax',
'meet-or-slice': 'meet | slice',
},
// A new spec
// @see https://drafts.fxtf.org/filter-effects/#element-attrdef-feimage-preserveaspectratio
// > preserveAspectRatio = "[defer] <align> [<meetOrSlice>]"
},
},
'<view-box>': {
ref: 'https://svgwg.org/svg2-draft/coords.html#ViewBoxAttribute',
syntax: {
apply: '<view-box>',
def: {
'view-box': '<min-x> [,]? <min-y> [,]? <width> [,]? <height>', // As '[<min-x>,? <min-y>,? <width>,? <height>]',
'min-x': '<number>',
'min-y': '<number>',
width: '<number>',
height: '<number>',
},
},
},
'<rotate>': {
ref: 'https://svgwg.org/specs/animations/#RotateAttribute',
syntax: {
apply: '<rotate>',
def: {
rotate: '<number> | auto | auto-reverse',
},
},
},
'<text-coordinate>': {
ref: 'https://svgwg.org/svg2-draft/text.html#TSpanAttributes',
syntax: {
apply: '<text-coordinate>',
def: {
'text-coordinate': '[ [ <svg-length> | <percentage> | <number> ]+ ]#',
},
},
},
'<list-of-lengths>': {
ref: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts',
syntax: {
apply: '<list-of-lengths>',
def: {
'list-of-lengths': '[ <svg-length> [,]? ]* <svg-length>',
},
},
},
'<list-of-numbers>': {
ref: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts',
syntax: {
apply: '<list-of-numbers>',
def: {
'list-of-numbers': '[ <number> [,]? ]* <number>',
},
},
},
'<list-of-percentages>': {
ref: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage',
syntax: {
apply: '<list-of-percentages>',
def: {
'list-of-percentages': '[ <percentage> [,]? ]* <percentage>',
},
},
},
'<number-optional-number>': {
ref: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number-optional-number',
syntax: {
apply: '<number-optional-number>',
def: {
'number-optional-number': '<number> | <number> , <number>',
},
},
},
};
export const tokenizers: Record<string, CssSyntaxTokenizer> = {
// RFC
// https://tools.ietf.org/rfc/bcp/bcp47.html
'bcp-47'(token) {
if (!token) {
return 0;
}
return isBCP47()(token.value) ? 1 : 0;
},
}; | the_stack |
import { memo } from '../../../src/component';
import {
b,
mount,
machine,
VNode,
emit,
lazy,
SFC,
MachineComponent,
} from '../../../src';
import { machineRegistry } from '../../../src/machineRegistry';
import { shouldRender } from '../../../src/diff/index';
import { ElementVNode } from '../../../src/createElement';
describe('optimizations', () => {
// memo instance
let $root = document.body;
test('isLeaf', () => {
/** make 2 sibling machines; one marked as a leaf,
* one not. make them push to an array (leafArr, nonLeafArr)
* on each render. send events to both machines and count renders.
* this test must pass!
*/
expect(true).toBe(true);
});
test('granular global events', () => {
const idNodeDepth: [string, number][] = [];
idNodeDepth.push(['hi', 2], ['ur mom', 1], ['a child', 4], ['fun', 3]);
idNodeDepth.sort((a, b) => b[1] - a[1]);
const ids = idNodeDepth.map(node => node[1]);
expect(ids).toStrictEqual([4, 3, 2, 1]);
});
test('shouldRender', () => {
expect(shouldRender({ count: 10 }, { count: 11 })).toBe(true);
expect(shouldRender({ count: 10 }, { count: 10 })).toBe(false);
const anObjProp = { name: 'TJ' };
// same object reference
expect(
shouldRender(
{ count: 10, objProp: anObjProp },
{ count: 10, objProp: anObjProp }
)
).toBe(false);
expect(
shouldRender(
{ count: 10, objProp: anObjProp },
{ count: 11, objProp: anObjProp }
)
).toBe(true);
// new objects. this should be true bc only checking for shallow eq
expect(
shouldRender(
{ count: 10, objProp: { name: 'TJ' } },
{ count: 10, objProp: { name: 'TJ' } }
)
).toBe(true);
});
test('memo basic', () => {
const MemoComp = memo<{ count: number }>(({ count }) => {
renders++;
return <p>{count}</p>;
});
const Mach = machine<{}>({
id: 'mach',
initial: 'default',
context: () => ({
first: 10,
second: 22,
}),
when: {
default: {
on: {
INC_FIRST: {
do: ctx => (ctx.first = ctx.first + 1),
},
},
},
},
render: (_s, ctx) => (
<div>
<MemoComp count={ctx.first} />
<MemoComp count={ctx.second} />
</div>
),
});
/** TODO: count renders */
let renders = 0;
$root = mount(Mach, $root);
const inst = machineRegistry.get('mach');
const rootMachineVNode = inst?.v;
const divVChildrenBefore = rootMachineVNode?.c?.c as VNode[];
const firstVChildBefore = divVChildrenBefore[0].c as ElementVNode;
const secondVChildBefore = divVChildrenBefore[1].c as ElementVNode;
expect(renders).toBe(2);
expect(inst?.x['first']).toBe(10);
expect($root.firstChild?.firstChild?.nodeValue).toBe('10');
expect($root.childNodes[1]?.firstChild?.nodeValue).toBe('22');
const vkids = rootMachineVNode?.c?.c as VNode[];
expect(vkids.length).toBe(2);
emit({ type: 'INC_FIRST' });
// this should be three bc props of first memo changed, second didn't
expect(renders).toBe(3);
// check that first vnode is not equal (before + after), while second vnode is!
const divVChildrenAfter = rootMachineVNode?.c?.c as VNode[];
const firstVChildAfter = divVChildrenAfter[0].c as ElementVNode;
const secondVChildAfter = divVChildrenAfter[1].c as ElementVNode;
expect(firstVChildBefore === firstVChildAfter).toBe(false);
expect(secondVChildBefore === secondVChildAfter).toBe(true);
expect(inst?.x['first']).toBe(11);
expect($root.firstChild?.firstChild?.nodeValue).toBe('11');
expect($root.childNodes[1]?.firstChild?.nodeValue).toBe('22');
expect(true).toBe(true);
});
test('global events, render parents before children', () => {
/**
* ~ROOT~
* / \
* A B
* / \ / \
* C D E F
*
* Make an event that A, B, C, and F listen to.
* A shouldn't render C after this event.
*
* To ensure that the Baahu logic works, count machine
* renders (should be 3 machines), and make sure the DOM looks
* how it is expected to look!
*
* Will need to make four machines for this:
* -A machine
* -B machine
* - C & F machine
* - D & E machine
*
* 6 initial renders, 3 rerenders, so 9 total is target
*/
let renders = 0;
const AMach = machine<{}>({
id: 'a',
initial: 'even',
context: () => ({}),
when: {
even: {
on: {
TOGGLE: {
to: 'odd',
},
},
},
odd: {},
},
render: state => {
renders++;
return (
<div>
{state === 'even' && <CFMach id="c" />}
<DEMach id="d" />
</div>
);
},
});
const BMach = machine<{}>({
id: 'b',
initial: 'default',
context: () => ({}),
when: {
default: {
on: { TOGGLE: {} },
},
},
render: () => {
renders++;
return (
<div>
<CFMach id="f" />
<DEMach id="e" />
</div>
);
},
});
const CFMach = machine<{ id: 'c' | 'f' }>({
id: ({ id }) => id,
initial: 'default',
context: () => ({}),
when: {
default: {
on: { TOGGLE: {} },
},
},
render: () => {
renders++;
return <div>hi</div>;
},
});
const DEMach = machine<{ id: 'd' | 'e' }>({
id: ({ id }) => id,
initial: 'default',
context: () => ({}),
when: {
default: {},
},
render: () => {
renders++;
return <div>hi</div>;
},
});
const Root = () => (
<div>
<AMach />
<BMach />
</div>
);
mount(Root, $root);
expect(renders).toBe(6);
expect(machineRegistry.size).toBe(6);
emit({ type: 'TOGGLE' });
expect(renders).toBe(9);
expect(machineRegistry.size).toBe(5);
});
const Comp = () => (
<div>
<p>me lazy</p>
</div>
);
test('memo DOES render when needed', () => {
// this case really shouldn't happen in the real world
const MemoName = memo<{ name: string | null }>(props => {
const name = props ? props.name : 'second';
return <p>{name}</p>;
});
const ToggleName = machine<{}, 'even' | 'odd'>({
id: 'toggle',
initial: 'even',
context: () => ({}),
when: {
even: {
on: {
TOGGLE: { to: 'odd' },
},
},
odd: {
on: { TOGGLE: { to: 'even' } },
},
},
render: state => b(MemoName, state === 'even' ? { name: 'first' } : null),
});
const $root = mount(ToggleName, document.body);
expect($root.firstChild?.nodeValue).toBe('first');
emit({ type: 'TOGGLE' });
expect($root.firstChild?.nodeValue).toBe('second');
emit({ type: 'TOGGLE' });
expect($root.firstChild?.nodeValue).toBe('first');
});
test('lazy', () => {
async function mockDynamicImport<Props>(
comp: SFC<Props> | MachineComponent<Props>
) {
return {
default: comp,
};
}
const LazyComp = lazy(() => mockDynamicImport(Comp), null);
let myRoot = mount(LazyComp, $root);
// will be wrapped in div before and after!
// before replacement
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe(undefined);
// after replacement (loaded promise)
return new Promise(res => {
setTimeout(() => res(true), 0);
}).then(() => {
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe('DIV');
expect(myRoot.firstChild?.firstChild?.nodeName).toBe('P');
// render it again
myRoot = mount(LazyComp, myRoot);
});
});
async function mockDynamicImportError<Props>(
comp: SFC<Props> | MachineComponent<Props>
) {
throw Error;
return {
default: comp,
};
}
test('lazy handles error', () => {
const LazyComp = lazy(
() => mockDynamicImportError(Comp),
null,
300,
<p>error</p>
);
let myRoot = mount(LazyComp, $root);
// will be wrapped in div before and after!
// before replacement
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe(undefined);
// after replacement (error)
return new Promise(res => {
setTimeout(() => res(true), 0);
}).then(() => {
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe('P');
expect(myRoot.firstChild?.firstChild?.nodeValue).toBe('error');
});
});
test('lazy renders fallback', () => {
async function mockDynamicImportLag<Props>(
comp: SFC<Props> | MachineComponent<Props>
) {
await new Promise(resolve => setTimeout(resolve, 1000));
return {
default: comp,
};
}
const LazyComp = lazy(() => mockDynamicImportLag(Comp), <p>fallback</p>, 1);
let myRoot = mount(LazyComp, $root);
// will be wrapped in div before and after!
// before replacement
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe(undefined);
// after replacement (fallback)
return new Promise(res => {
setTimeout(() => res(true), 1);
}).then(() => {
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe('P');
expect(myRoot.firstChild?.firstChild?.nodeValue).toBe('fallback');
});
});
test('lazy renders fallback, then replaces it', () => {
async function mockDynamicImportLag<Props>(
comp: SFC<Props> | MachineComponent<Props>
) {
await new Promise(resolve => setTimeout(resolve, 20));
return {
default: comp,
};
}
const LazyComp = lazy(
() => mockDynamicImportLag(Comp),
<p>fallback</p>,
10
);
let myRoot = mount(LazyComp, $root);
// will be wrapped in div before and after!
// before replacement
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe(undefined);
// after replacement (should be component this time)
return new Promise(res => {
setTimeout(() => res(true), 30);
}).then(() => {
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe('DIV');
expect(myRoot.firstChild?.firstChild?.nodeName).toBe('P');
});
});
test('lazy renders fallback, then replaces w/ error', () => {
async function mockDynamicImportLagError<Props>(
comp: SFC<Props> | MachineComponent<Props>
) {
await new Promise(resolve => setTimeout(resolve, 10));
throw Error;
return {
default: comp,
};
}
const LazyComp = lazy(
() => mockDynamicImportLagError(Comp),
<p>fallback</p>,
1,
<p>error</p>
);
let myRoot = mount(LazyComp, $root);
// will be wrapped in div before and after!
// before replacement
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe(undefined);
// after replacement (should be error this time)
return new Promise(res => setTimeout(res, 30)).then(() => {
expect(myRoot.nodeName).toBe('DIV');
expect(myRoot.firstChild?.nodeName).toBe('P');
expect(myRoot.firstChild?.firstChild?.nodeValue).toBe('error');
});
});
}); | the_stack |
import {ElementRef, Injectable} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
import {take} from 'rxjs/operators';
import {
BaseType as D3BaseType,
ContainerElement as D3ContainerElement,
select as d3Select,
selectAll as d3SelectAll,
Selection as D3Selection
} from 'd3-selection';
import {ScaleLinear as D3ScaleLinear, ScaleTime as D3ScaleTime} from 'd3-scale';
import {axisBottom as d3AxisBottom} from 'd3-axis';
import {Transition as D3Transition} from 'd3-transition';
import {EventResultDataDTO} from 'src/app/modules/time-series/models/event-result-data.model';
import {EventResultSeriesDTO} from 'src/app/modules/time-series/models/event-result-series.model';
import {EventResultPointDTO} from 'src/app/modules/time-series/models/event-result-point.model';
import {TimeSeries} from 'src/app/modules/time-series/models/time-series.model';
import {TimeSeriesPoint} from 'src/app/modules/time-series/models/time-series-point.model';
import {parseDate} from 'src/app/utils/date.util';
import {UrlBuilderService} from './url-builder.service';
import {LineChartScaleService} from './chart-services/line-chart-scale.service';
import {LineChartDrawService} from './chart-services/line-chart-draw.service';
import {LineChartEventService} from './chart-services/line-chart-event.service';
import {LineChartLegendService} from './chart-services/line-chart-legend.service';
import {SummaryLabel} from '../models/summary-label.model';
/**
* Generate line charts with ease and fun 😎
*/
@Injectable({
providedIn: 'root'
})
export class LineChartService {
// D3 margin conventions
// > With this convention, all subsequent code can ignore margins.
// see: https://bl.ocks.org/mbostock/3019563
private MARGIN: { [key: string]: number } = {top: 60, right: 60, bottom: 40, left: 75};
private Y_AXIS_WIDTH = 65;
private _margin: { [key: string]: number } = {
top: this.MARGIN.top,
right: this.MARGIN.right,
bottom: this.MARGIN.bottom,
left: this.MARGIN.left
};
private _width: number = 600 - this._margin.left - this._margin.right;
private _height: number = 550 - this._margin.top - this._margin.bottom;
private _legendGroupTop: number = this._margin.top + this._height + 50;
private _xScale: D3ScaleTime<number, number>;
constructor(private translationService: TranslateService,
private urlBuilderService: UrlBuilderService,
private lineChartScaleService: LineChartScaleService,
private lineChartDrawService: LineChartDrawService,
private lineChartEventService: LineChartEventService,
private lineChartLegendService: LineChartLegendService) {
}
private _dataTrimLabels: { [key: string]: string } = {};
get dataTrimLabels(): { [p: string]: string } {
return this._dataTrimLabels;
}
private _dataMaxValues: { [key: string]: number } = {};
get dataMaxValues(): { [p: string]: number } {
return this._dataMaxValues;
}
initChart(svgElement: ElementRef, pointSelectionErrorHandler: Function): void {
this.lineChartEventService.pointSelectionErrorHandler = pointSelectionErrorHandler;
const data: { [key: string]: TimeSeries[] } = {};
const chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}> = this.createChart(svgElement);
this._xScale = this.lineChartScaleService.getXScale(data, this._width);
this.addXAxisToChart(chart);
this.lineChartEventService.prepareMouseEventCatcher(chart, this._width, this._height, this._margin.top, this._margin.left);
}
/**
* Prepares the incoming data for drawing with D3.js
*/
prepareData(incomingData: EventResultDataDTO,
dataTrimValues: { [key: string]: { [key: string]: number } }): { [key: string]: TimeSeries[] } {
const data: { [key: string]: TimeSeries[] } = {};
const measurandGroups = Object.keys(incomingData.series);
measurandGroups.forEach((measurandGroup: string) => {
let maxValue = 0;
data[measurandGroup] = incomingData.series[measurandGroup].map((seriesDTO: EventResultSeriesDTO) => {
const lineChartData: TimeSeries = new TimeSeries();
if (incomingData.summaryLabels.length === 0 ||
(incomingData.summaryLabels.length > 0 && incomingData.summaryLabels[0].key !== 'measurand')) {
seriesDTO.identifier = this.lineChartLegendService.translateMeasurand(seriesDTO);
}
lineChartData.key = this.lineChartLegendService.generateKey(seriesDTO);
lineChartData.values = seriesDTO.data.map((point: EventResultPointDTO) => {
const lineChartDataPoint: TimeSeriesPoint = new TimeSeriesPoint();
lineChartDataPoint.date = parseDate(point.date);
lineChartDataPoint.value = point.value;
lineChartDataPoint.agent = point.agent;
lineChartDataPoint.tooltipText = `${seriesDTO.identifier}: `;
lineChartDataPoint.wptInfo = point.wptInfo;
maxValue = Math.max(maxValue, point.value);
return lineChartDataPoint;
}).filter((point: TimeSeriesPoint) => {
const min: boolean = dataTrimValues.min[measurandGroup] ? point.value >= dataTrimValues.min[measurandGroup] : true;
const max: boolean = dataTrimValues.max[measurandGroup] ? point.value <= dataTrimValues.max[measurandGroup] : true;
return min && max;
});
return lineChartData;
});
this._dataMaxValues[measurandGroup] = maxValue;
});
return data;
}
prepareLegend(incomingData: EventResultDataDTO): void {
this.lineChartLegendService.setLegendData(incomingData);
}
drawLineChart(timeSeries: { [key: string]: TimeSeries[] },
measurandGroups: { [key: string]: string },
summaryLabels: SummaryLabel[],
timeSeriesAmount: number,
dataTrimValues: { [key: string]: { [key: string]: number } }): void {
this.lineChartEventService.prepareCleanState();
this.adjustChartDimensions(measurandGroups, summaryLabels);
const chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}> = d3Select('g#time-series-chart-drawing-area');
const width: number = this.lineChartDrawService.getDrawingAreaWidth(this._width, this.Y_AXIS_WIDTH,
Object.keys(measurandGroups).length);
this._xScale = this.lineChartScaleService.getXScale(timeSeries, width);
const yScales: { [key: string]: D3ScaleLinear<number, number> } = this.lineChartScaleService.getYScales(
timeSeries, this._height, dataTrimValues);
this.lineChartDrawService.setYAxesInChart(chart, yScales);
const legendGroupHeight = this.lineChartLegendService.calculateLegendDimensions(this._width);
d3Select('svg#time-series-chart')
.transition()
.duration(500)
.attr('height', this._height + legendGroupHeight + this._margin.top + this._margin.bottom);
d3Select('.x-axis').transition().call((transition: D3Transition<SVGGElement, any, HTMLElement, any>) => {
this.lineChartDrawService.updateXAxis(transition, this._xScale);
});
this.lineChartDrawService.updateYAxes(yScales, this._width, this.Y_AXIS_WIDTH);
this.addYAxisUnits(measurandGroups, width);
const chartContentContainer = chart.select('.chart-content');
this.lineChartEventService.createContextMenu();
this.lineChartEventService.addBrush(chartContentContainer, this._width, this._height, this.Y_AXIS_WIDTH, this._xScale,
timeSeries, dataTrimValues, this.lineChartLegendService.legendDataMap);
this.lineChartLegendService.addLegendsToChart(chartContentContainer, this._xScale, yScales, timeSeries, timeSeriesAmount);
this.lineChartLegendService.setSummaryLabel(chart, summaryLabels, this._width);
Object.keys(yScales).forEach((key: string, index: number) => {
this.lineChartDrawService.addDataLinesToChart(chartContentContainer, this.lineChartEventService.pointsSelection,
this._xScale, yScales[key], timeSeries[key], this.lineChartLegendService.legendDataMap, index);
});
this.lineChartEventService.addMouseMarkerToChart(chartContentContainer);
this.lineChartDrawService.drawAllSelectedPoints(this.lineChartEventService.pointsSelection);
this.setDataTrimLabels(measurandGroups);
chartContentContainer
.attr('width', this._width)
.attr('height', this._height);
}
restoreZoom(timeSeriesData: { [key: string]: TimeSeries[] },
dataTrimValues: { [key: string]: { [key: string]: number } }): void {
const chartContentContainer = d3Select('g#time-series-chart-drawing-area .chart-content');
this.lineChartEventService.restoreSelectedZoom(chartContentContainer, this._width, this._height,
this.Y_AXIS_WIDTH, this._xScale, timeSeriesData, dataTrimValues, this.lineChartLegendService.legendDataMap);
}
startResize(svgElement: ElementRef): void {
d3Select(svgElement.nativeElement).transition().duration(100).style('opacity', 0.0);
}
resizeChart(svgElement: ElementRef): void {
this._width = svgElement.nativeElement.parentElement.offsetWidth - this._margin.left - this._margin.right;
d3Select(svgElement.nativeElement).attr('width', this._width + this._margin.left + this._margin.right);
}
endResize(svgElement: ElementRef): void {
d3Select(svgElement.nativeElement).transition().duration(50).style('opacity', 1.0);
}
/**
* Setup the basic chart with an x- and y-axis
*/
private createChart(svgElement: ElementRef): D3Selection<D3BaseType, {}, D3ContainerElement, {}> {
this._width = svgElement.nativeElement.parentElement.offsetWidth - this._margin.left - this._margin.right;
const svg = d3Select(svgElement.nativeElement)
.attr('id', 'time-series-chart')
.attr('width', this._width + this._margin.left + this._margin.right)
.attr('height', 0);
svg.append('g')
.attr('id', 'header-group')
.attr('transform', `translate(${this._margin.left}, ${this._margin.top - 16})`);
const chart = svg.append('g') // g = grouping element; group all other stuff into the chart
.attr('id', 'time-series-chart-drawing-area')
// translates the origin to the top left corner (default behavior of D3)
.attr('transform', `translate(${this._margin.left}, ${this._margin.top})`);
svg.append('g')
.attr('id', 'time-series-chart-legend')
.attr('class', 'legend-group')
.attr('transform', `translate(${this._margin.left}, ${this._legendGroupTop})`);
return chart;
}
/**
* Print the x-axis on the graph
*/
private addXAxisToChart(chart: D3Selection<D3BaseType, {}, D3ContainerElement, {}>): void {
const xAxis = d3AxisBottom(this._xScale);
// Add the X-Axis to the chart
chart.append('g') // new group for the X-Axis (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g)
.attr('class', 'axis x-axis') // a css class to style it later
// even if the D3 method called `axisBottom` we have to move it to the bottom by ourselves
.attr('transform', `translate(0, ${this._height})`)
.call(xAxis);
}
private adjustChartDimensions(measurandGroups: { [key: string]: string },
summaryLabels: SummaryLabel[]): void {
this._width = this._width + this._margin.right;
if (Object.keys(measurandGroups).length > 1) {
this._margin.right = this.MARGIN.right - 30;
} else {
this._margin.right = this.MARGIN.right;
}
this._width = this._width - this._margin.right;
if (Object.keys(measurandGroups).length === 1) {
this._margin.top = this.MARGIN.top;
} else if (summaryLabels.length === 0 || Object.keys(measurandGroups).length === 2) {
this._margin.top = this.MARGIN.top + 10;
} else {
this._margin.top = this.MARGIN.top + 20;
}
this._legendGroupTop = this._margin.top + this._height + 50;
d3Select('#time-series-chart')
.attr('width', this._width + this._margin.left + this._margin.right);
d3Select('#header-group')
.attr('transform', `translate(${this._margin.left}, ${this._margin.top - 16})`);
d3Select('#time-series-chart-drawing-area')
.attr('transform', `translate(${this._margin.left}, ${this._margin.top})`);
d3Select('#time-series-chart-legend')
.attr('transform', `translate(${this._margin.left}, ${this._legendGroupTop})`);
}
private addYAxisUnits(measurandGroups: { [key: string]: string }, width: number): void {
d3SelectAll('.axis-unit').selectAll('*').remove();
const axisLabelKeys = Object.keys(measurandGroups);
axisLabelKeys.forEach((axisLabelKey: string, index: number) => {
let xPosition: number;
if (index === 0) {
xPosition = -42;
} else {
xPosition = width - 12 + this.Y_AXIS_WIDTH * index;
}
this.translationService.get(`frontend.de.iteratec.isr.measurand.group.axisLabel.${axisLabelKey}`).pipe(take(1)).subscribe(title => {
d3Select(`.axis-unit${index}`).append('text')
.attr('class', 'description unit')
.attr('transform', `translate(${xPosition}, ${this._height / 2}) rotate(-90)`)
.text(`${title} [${measurandGroups[axisLabelKey]}]`);
});
});
}
private setDataTrimLabels(measurandGroups: { [key: string]: string }): void {
this._dataTrimLabels = measurandGroups;
}
} | the_stack |
import { ServiceState } from './types'
import { assert } from 'chai'
import feathersVuex from '../../src/index'
import { feathersRestClient as feathersClient } from '../fixtures/feathers-client'
import Vuex from 'vuex'
import { clearModels } from '../../src/service-module/global-models'
import memory from 'feathers-memory'
import { makeStore } from '../test-utils'
import { isDate } from 'date-fns'
require('events').EventEmitter.prototype._maxListeners = 100
interface TodoState extends ServiceState {
test: any
test2: {
test: boolean
}
isTrue: boolean
}
interface RootState {
['model-methods-persons']: ServiceState
['model-methods-todos']: TodoState
['model-methods-tasks']: ServiceState
tests: ServiceState
blah: ServiceState
things: ServiceState
}
function makeContext() {
const { makeServicePlugin, BaseModel } = feathersVuex(feathersClient, {
serverAlias: 'model-methods'
})
const serialize = context => {
context.data = JSON.parse(JSON.stringify(context.data))
}
const deserialize = context => {
context.result = JSON.parse(JSON.stringify(context.result))
}
feathersClient.use('model-methods-letters', memory())
const lettersService = feathersClient.service('model-methods-letters')
// Setup hooks on letters service to simulate toJSON serialization that occurs
// with a remote API request.
lettersService.hooks({
before: {
create: [serialize],
update: [serialize],
patch: [serialize]
},
after: {
create: [deserialize],
patch: [deserialize],
update: [deserialize]
}
})
class Task extends BaseModel {
public static modelName = 'Task'
public static servicePath: 'model-methods-tasks'
public constructor(data?, options?) {
super(data, options)
}
}
class Todo extends BaseModel {
public static modelName = 'Todo'
public static servicePath: 'model-methods-todos'
public constructor(data?, options?) {
super(data, options)
}
}
class Letter extends BaseModel {
public constructor(data?, options?) {
super(data, options)
}
public static modelName = 'Letter'
public static servicePath = 'model-methods-letters'
public static instanceDefaults(data, { models, store }) {
return {
to: '',
from: ''
}
}
public static setupInstance(data, { models }) {
if (typeof data.createdAt === 'string') {
data.createdAt = new Date(data.createdAt) // just assuming the date is formatted correctly ;)
}
return data
}
public get status() {
return 'pending'
}
}
class Person extends BaseModel {
public static modelName = 'Person'
public static servicePath = 'model-methods-persons'
public constructor(data?, options?) {
super(data, options)
}
}
const store = new Vuex.Store<RootState>({
strict: true,
plugins: [
makeServicePlugin({
Model: Task,
servicePath: 'model-methods-tasks',
service: feathersClient.service('model-methods-tasks'),
preferUpdate: true,
namespace: 'model-methods-tasks'
}),
makeServicePlugin({
Model: Todo,
servicePath: 'model-methods-todos',
service: feathersClient.service('model-methods-todos'),
namespace: 'model-methods-todos'
}),
makeServicePlugin({
Model: Letter,
servicePath: 'model-methods-letters',
service: feathersClient.service('model-methods-letters'),
namespace: 'model-methods-letters'
}),
makeServicePlugin({
Model: Person,
servicePath: 'model-methods-persons',
service: feathersClient.service('model-methods-persons'),
keepCopiesInStore: true,
namespace: 'model-methods-persons'
})
]
})
// Fake server call
feathersClient.service('model-methods-tasks').hooks({
before: {
create: [
context => {
delete context.data.__id
delete context.data.__isTemp
},
context => {
context.result = { _id: 24, ...context.data }
return context
}
],
update: [
context => {
context.result = { ...context.data }
return context
}
],
patch: [
context => {
context.result = { ...context.data }
return context
}
],
remove: [
context => {
context.result = {}
return context
}
]
}
})
// Fake server call
feathersClient.service('model-methods-persons').hooks({
before: {
create: [
context => {
delete context.data.__id
delete context.data.__isTemp
},
context => {
context.result = { _id: 24, ...context.data }
return context
}
],
update: [
context => {
context.result = { ...context.data }
return context
}
],
patch: [
context => {
context.result = { ...context.data }
return context
}
],
remove: [
context => {
context.result = {}
return context
}
]
}
})
return {
BaseModel,
Task,
Todo,
Letter,
Person,
lettersService,
store
}
}
export { makeContext }
describe('Models - Methods', function () {
beforeEach(() => {
clearModels()
})
it('Model.find is a function', function () {
const { Task } = makeContext()
assert(typeof Task.find === 'function')
})
it('Model.find returns a Promise', function () {
const { Task } = makeContext()
const result = Task.find()
assert(typeof result.then !== 'undefined')
result.catch(err => {
/* noop -- prevents UnhandledPromiseRejectionWarning */
})
})
it('Model.findInStore', function () {
const { Task } = makeContext()
assert(typeof Task.findInStore === 'function')
})
it('Model.count is a function', function () {
const { Task } = makeContext()
assert(typeof Task.count === 'function')
})
it('Model.count returns a Promise', function () {
const { Task } = makeContext()
const result = Task.count({ query: {} })
assert(typeof result.then !== 'undefined')
result.catch(err => {
/* noop -- prevents UnhandledPromiseRejectionWarning */
})
})
it('Model.countInStore', function () {
const { Task } = makeContext()
assert(typeof Task.countInStore === 'function')
})
it('Model.get', function () {
const { Task } = makeContext()
assert(typeof Task.get === 'function')
})
it('Model.getFromStore', function () {
const { Task } = makeContext()
assert(typeof Task.getFromStore === 'function')
})
it('allows listening to Feathers events on Model', function (done) {
const { Letter } = makeContext()
Letter.on('created', data => {
assert(data.to === 'Santa', 'received event with data')
done()
})
// This should trigger an event from the bottom of make-service-plugin.ts
const letter = new Letter({
from: 'Me',
to: 'Santa'
}).save()
})
it('instance.save calls create with correct arguments', function () {
const { Task } = makeContext()
const task = new Task({ test: true })
Object.defineProperty(task, 'create', {
value(params) {
assert(arguments.length === 1, 'should have only called with params')
assert(
params === undefined,
'no params should have been passed this time'
)
}
})
task.save()
})
it('instance.save passes params to create', function () {
const { Task } = makeContext()
const task = new Task({ test: true })
let called = false
Object.defineProperty(task, 'create', {
value(params) {
assert(arguments.length === 1, 'should have only called with params')
assert(params.test, 'should have received params')
called = true
}
})
task.save({ test: true })
assert(called, 'create should have been called')
})
it('instance.save passes params to patch', function () {
const { Todo } = makeContext()
const todo = new Todo({ id: 1, test: true })
let called = false
Object.defineProperty(todo, 'patch', {
value(params) {
assert(arguments.length === 1, 'should have only called with params')
assert(params.test, 'should have received params')
called = true
}
})
todo.save({ test: true })
assert(called, 'patch should have been called')
})
it('instance.save passes params to update', function () {
const { Task } = makeContext()
Task.preferUpdate = true
const task = new Task({ id: 1, test: true })
let called = false
Object.defineProperty(task, 'update', {
value(params) {
assert(arguments.length === 1, 'should have only called with params')
assert(params.test, 'should have received params')
called = true
}
})
task.save({ test: true })
assert(called, 'update should have been called')
})
it('instance.remove works with temp records', function () {
const { Task, store } = makeContext()
const task = new Task({ test: true })
const tempId = task.__id
task.remove()
assert(
!store.state['model-methods-tasks'].tempsById[tempId],
'temp was removed'
)
})
it('instance.remove removes cloned record from the store', async function () {
const { Person, store } = makeContext()
const person = new Person({ _id: 1, test: true })
const id = person._id
// @ts-ignore
const { copiesById } = store.state['model-methods-persons']
person.clone()
assert(copiesById[id], 'clone exists')
await person.remove()
assert(!copiesById[id], 'clone was removed')
})
it('instance.remove removes cloned record from Model.copiesById', async function () {
const { Task } = makeContext()
const task = new Task({ _id: 2, test: true })
const id = task._id
task.clone()
assert(Task.copiesById[id], 'clone exists')
await task.remove()
assert(!Task.copiesById[id], 'clone was removed')
})
it('instance.remove for temp record removes cloned record from the store', function () {
const { Person, store } = makeContext()
const person = new Person({ test: true })
const tempId = person.__id
// @ts-ignore
const { copiesById } = store.state['model-methods-persons']
person.clone()
assert(copiesById[tempId], 'clone exists')
person.remove()
assert(!copiesById[tempId], 'clone was removed')
})
it('instance.remove for temp record removes cloned record from the Model.copiesById', function () {
const { Task } = makeContext()
const task = new Task({ test: true })
const tempId = task.__id
task.clone()
assert(Task.copiesById[tempId], 'clone exists')
task.remove()
assert(!Task.copiesById[tempId], 'clone was removed')
})
it('removes clone and original upon calling clone.remove()', async function () {
const { Person, store } = makeContext()
const person = new Person({ _id: 1, test: true })
const id = person._id
// @ts-ignore
const { copiesById, keyedById } = store.state['model-methods-persons']
person.clone()
assert(copiesById[id], 'clone exists')
assert(keyedById[id], 'original exists')
const clone = copiesById[id]
await clone.remove()
assert(!copiesById[id], 'clone was removed')
assert(!keyedById[id], 'original was removed')
})
it('instance methods still available in store data after updateItem mutation (or socket event)', async function () {
const { Letter, store, lettersService } = makeContext()
let letter = new Letter({ name: 'Garmadon', age: 1025 })
letter = await letter.save()
assert.equal(
typeof letter.save,
'function',
'saved instance has a save method'
)
store.commit('model-methods-letters/updateItem', {
id: letter.id,
name: 'Garmadon / Dad',
age: 1026
})
const letter2 = new Letter({
id: letter.id,
name: 'Just Garmadon',
age: 1027
})
assert.equal(
typeof letter2.save,
'function',
'new instance has a save method'
)
})
it('Dates remain as dates after changes', async function () {
const { Letter, store, lettersService } = makeContext()
let letter = new Letter({
name: 'Garmadon',
age: 1025,
createdAt: new Date().toString()
})
assert(isDate(letter.createdAt), 'createdAt should be a date')
letter = await letter.save()
assert(isDate(letter.createdAt), 'createdAt should be a date')
letter = await letter.save()
assert(isDate(letter.createdAt), 'createdAt should be a date')
})
it('instance.toJSON', function () {
const { Task } = makeContext()
const task = new Task({ id: 1, test: true })
Object.defineProperty(task, 'getter', {
get() {
return `got'er`
}
})
assert.equal(task.getter, `got'er`)
const json = task.toJSON()
assert(json, 'got json')
})
it('Model pending status sets/clears for create/update/patch/remove', async function() {
const { makeServicePlugin, BaseModel } = feathersVuex(feathersClient, {
idField: '_id',
serverAlias: 'model-methods'
})
class PendingThing extends BaseModel {
public static modelName = 'PendingThing'
public constructor(data?, options?) {
super(data, options)
}
}
const store = new Vuex.Store<RootState>({
plugins: [
makeServicePlugin({
Model: PendingThing,
service: feathersClient.service('methods-pending-things')
})
]
})
// Create instance
const thing = new PendingThing({ description: 'pending test' })
const clone = thing.clone()
assert(!!thing.__id, "thing has a tempId")
assert(clone.__id === thing.__id, "clone has thing's tempId")
// Manually set the result in a hook to simulate the server request.
feathersClient.service('methods-pending-things').hooks({
before: {
create: [
context => {
context.result = { _id: 42, ...context.data }
// Check pending status
assert(thing.isCreatePending === true, 'isCreatePending set')
assert(thing.isSavePending === true, 'isSavePending set')
assert(thing.isPending === true, 'isPending set')
// Check clone's pending status
assert(clone.isCreatePending === true, 'isCreatePending set on clone')
assert(clone.isSavePending === true, 'isSavePending set on clone')
assert(clone.isPending === true, 'isPending set on clone')
return context
}
],
update: [
context => {
context.result = { ...context.data }
// Check pending status
assert(thing.isUpdatePending === true, 'isUpdatePending set')
assert(thing.isSavePending === true, 'isSavePending set')
assert(thing.isPending === true, 'isPending set')
// Check clone's pending status
assert(clone.isUpdatePending === true, 'isUpdatePending set on clone')
assert(clone.isSavePending === true, 'isSavePending set on clone')
assert(clone.isPending === true, 'isPending set on clone')
return context
}
],
patch: [
context => {
context.result = { ...context.data }
// Check pending status
assert(thing.isPatchPending === true, 'isPatchPending set')
assert(thing.isSavePending === true, 'isSavePending set')
assert(thing.isPending === true, 'isPending set')
// Check clone's pending status
assert(clone.isPatchPending === true, 'isPatchPending set on clone')
assert(clone.isSavePending === true, 'isSavePending set on clone')
assert(clone.isPending === true, 'isPending set on clone')
return context
}
],
remove: [
context => {
context.result = { ...context.data }
// Check pending status
assert(thing.isRemovePending === true, 'isRemovePending set')
assert(thing.isSavePending === false, 'isSavePending clear on remove')
assert(thing.isPending === true, 'isPending set')
// Check clone's pending status
assert(clone.isRemovePending === true, 'isRemovePending set on clone')
assert(clone.isSavePending === false, 'isSavePending clear on remove on clone')
assert(clone.isPending === true, 'isPending set on clone')
return context
}
]
}
})
// Create and verify status
await thing.create()
assert(thing.isCreatePending === false, 'isCreatePending cleared')
assert(thing.isSavePending === false, 'isSavePending cleared')
assert(thing.isPending === false, 'isPending cleared')
assert(clone.isCreatePending === false, 'isCreatePending cleared on clone')
assert(clone.isSavePending === false, 'isSavePending cleared on clone')
assert(clone.isPending === false, 'isPending cleared on clone')
// Update and verify status
await thing.update()
assert(thing.isUpdatePending === false, 'isUpdatePending cleared')
assert(thing.isSavePending === false, 'isSavePending cleared')
assert(thing.isPending === false, 'isPending cleared')
assert(clone.isUpdatePending === false, 'isUpdatePending cleared on clone')
assert(clone.isSavePending === false, 'isSavePending cleared on clone')
assert(clone.isPending === false, 'isPending cleared on clone')
// Patch and verify status
await thing.patch()
assert(thing.isPatchPending === false, 'isPatchPending cleared')
assert(thing.isSavePending === false, 'isSavePending cleared')
assert(thing.isPending === false, 'isPending cleared')
assert(clone.isPatchPending === false, 'isPatchPending cleared on clone')
assert(clone.isSavePending === false, 'isSavePending cleared on clone')
assert(clone.isPending === false, 'isPending cleared on clone')
// Remove and verify status
await thing.remove()
assert(thing.isRemovePending === false, 'isRemovePending cleared')
assert(thing.isSavePending === false, 'isSavePending cleared')
assert(thing.isPending === false, 'isPending cleared')
assert(clone.isRemovePending === false, 'isRemovePending cleared on clone')
assert(clone.isSavePending === false, 'isSavePending cleared on clone')
assert(clone.isPending === false, 'isPending cleared on clone')
})
}) | the_stack |
import { $PropertyType } from "utility-types";
// @flow
import { PressEvent } from "../Types/CoreEventTypes";
declare type GestureState =
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
/**
* ID of the gestureState - persisted as long as there at least one touch on screen
*/
stateID: number;
/**
* The latest screen coordinates of the recently-moved touch
*/
moveX: number;
/**
* The latest screen coordinates of the recently-moved touch
*/
moveY: number;
/**
* The screen coordinates of the responder grant
*/
x0: number;
/**
* The screen coordinates of the responder grant
*/
y0: number;
/**
* Accumulated distance of the gesture since the touch started
*/
dx: number;
/**
* Accumulated distance of the gesture since the touch started
*/
dy: number;
/**
* Current velocity of the gesture
*/
vx: number;
/**
* Current velocity of the gesture
*/
vy: number;
/**
* Number of touches currently on screen
*/
numberActiveTouches: number;
/**
* All `gestureState` accounts for timeStamps up until this value
*
* @private
*/
_accountsForMovesUpTo: number;
};
declare type ActiveCallback = (event: PressEvent, gestureState: GestureState) => boolean;
declare type PassiveCallback = (event: PressEvent, gestureState: GestureState) => unknown;
declare type PanResponderConfig = Readonly<
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
onMoveShouldSetPanResponder?: null | undefined | ActiveCallback;
onMoveShouldSetPanResponderCapture?: null | undefined | ActiveCallback;
onStartShouldSetPanResponder?: null | undefined | ActiveCallback;
onStartShouldSetPanResponderCapture?: null | undefined | ActiveCallback;
/**
* The body of `onResponderGrant` returns a bool, but the vast majority of
* callsites return void and this TODO notice is found in it:
* TODO: t7467124 investigate if this can be removed
*/
onPanResponderGrant?: null | undefined | (PassiveCallback | ActiveCallback);
onPanResponderReject?: null | undefined | PassiveCallback;
onPanResponderStart?: null | undefined | PassiveCallback;
onPanResponderEnd?: null | undefined | PassiveCallback;
onPanResponderRelease?: null | undefined | PassiveCallback;
onPanResponderMove?: null | undefined | PassiveCallback;
onPanResponderTerminate?: null | undefined | PassiveCallback;
onPanResponderTerminationRequest?: null | undefined | ActiveCallback;
onShouldBlockNativeResponder?: null | undefined | ActiveCallback;
}>;
declare var PanResponder:
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
/**
*
* A graphical explanation of the touch data flow:
*
* +----------------------------+ +--------------------------------+
* | ResponderTouchHistoryStore | |TouchHistoryMath |
* +----------------------------+ +----------+---------------------+
* |Global store of touchHistory| |Allocation-less math util |
* |including activeness, start | |on touch history (centroids |
* |position, prev/cur position.| |and multitouch movement etc) |
* | | | |
* +----^-----------------------+ +----^---------------------------+
* | |
* | (records relevant history |
* | of touches relevant for |
* | implementing higher level |
* | gestures) |
* | |
* +----+-----------------------+ +----|---------------------------+
* | ResponderEventPlugin | | | Your App/Component |
* +----------------------------+ +----|---------------------------+
* |Negotiates which view gets | Low level | | High level |
* |onResponderMove events. | events w/ | +-+-------+ events w/ |
* |Also records history into | touchHistory| | Pan | multitouch + |
* |ResponderTouchHistoryStore. +---------------->Responder+-----> accumulative|
* +----------------------------+ attached to | | | distance and |
* each event | +---------+ velocity. |
* | |
* | |
* +--------------------------------+
*
*
*
* Gesture that calculates cumulative movement over time in a way that just
* "does the right thing" for multiple touches. The "right thing" is very
* nuanced. When moving two touches in opposite directions, the cumulative
* distance is zero in each dimension. When two touches move in parallel five
* pixels in the same direction, the cumulative distance is five, not ten. If
* two touches start, one moves five in a direction, then stops and the other
* touch moves fives in the same direction, the cumulative distance is ten.
*
* This logic requires a kind of processing of time "clusters" of touch events
* so that two touch moves that essentially occur in parallel but move every
* other frame respectively, are considered part of the same movement.
*
* Explanation of some of the non-obvious fields:
*
* - moveX/moveY: If no move event has been observed, then `(moveX, moveY)` is
* invalid. If a move event has been observed, `(moveX, moveY)` is the
* centroid of the most recently moved "cluster" of active touches.
* (Currently all move have the same timeStamp, but later we should add some
* threshold for what is considered to be "moving"). If a palm is
* accidentally counted as a touch, but a finger is moving greatly, the palm
* will move slightly, but we only want to count the single moving touch.
* - x0/y0: Centroid location (non-cumulative) at the time of becoming
* responder.
* - dx/dy: Cumulative touch distance - not the same thing as sum of each touch
* distance. Accounts for touch moves that are clustered together in time,
* moving the same direction. Only valid when currently responder (otherwise,
* it only represents the drag distance below the threshold).
* - vx/vy: Velocity.
*/
_initializeGestureState: (gestureState: GestureState) => void;
/**
* This is nuanced and is necessary. It is incorrect to continuously take all
* active *and* recently moved touches, find the centroid, and track how that
* result changes over time. Instead, we must take all recently moved
* touches, and calculate how the centroid has changed just for those
* recently moved touches, and append that change to an accumulator. This is
* to (at least) handle the case where the user is moving three fingers, and
* then one of the fingers stops but the other two continue.
*
* This is very different than taking all of the recently moved touches and
* storing their centroid as `dx/dy`. For correctness, we must *accumulate
* changes* in the centroid of recently moved touches.
*
* There is also some nuance with how we handle multiple moved touches in a
* single event. With the way `ReactNativeEventEmitter` dispatches touches as
* individual events, multiple touches generate two 'move' events, each of
* them triggering `onResponderMove`. But with the way `PanResponder` works,
* all of the gesture inference is performed on the first dispatch, since it
* looks at all of the touches (even the ones for which there hasn't been a
* native dispatch yet). Therefore, `PanResponder` does not call
* `onResponderMove` passed the first dispatch. This diverges from the
* typical responder callback pattern (without using `PanResponder`), but
* avoids more dispatches than necessary.
*/
_updateGestureStateOnMove: (gestureState: GestureState, touchHistory: $PropertyType<PressEvent, "touchHistory">) => void;
/**
* @param {object} config Enhanced versions of all of the responder callbacks
* that provide not only the typical `ResponderSyntheticEvent`, but also the
* `PanResponder` gesture state. Simply replace the word `Responder` with
* `PanResponder` in each of the typical `onResponder*` callbacks. For
* example, the `config` object would look like:
*
* - `onMoveShouldSetPanResponder: (e, gestureState) => {...}`
* - `onMoveShouldSetPanResponderCapture: (e, gestureState) => {...}`
* - `onStartShouldSetPanResponder: (e, gestureState) => {...}`
* - `onStartShouldSetPanResponderCapture: (e, gestureState) => {...}`
* - `onPanResponderReject: (e, gestureState) => {...}`
* - `onPanResponderGrant: (e, gestureState) => {...}`
* - `onPanResponderStart: (e, gestureState) => {...}`
* - `onPanResponderEnd: (e, gestureState) => {...}`
* - `onPanResponderRelease: (e, gestureState) => {...}`
* - `onPanResponderMove: (e, gestureState) => {...}`
* - `onPanResponderTerminate: (e, gestureState) => {...}`
* - `onPanResponderTerminationRequest: (e, gestureState) => {...}`
* - `onShouldBlockNativeResponder: (e, gestureState) => {...}`
*
* In general, for events that have capture equivalents, we update the
* gestureState once in the capture phase and can use it in the bubble phase
* as well.
*
* Be careful with onStartShould* callbacks. They only reflect updated
* `gestureState` for start/end events that bubble/capture to the Node.
* Once the node is the responder, you can rely on every start/end event
* being processed by the gesture and `gestureState` being updated
* accordingly. (numberActiveTouches) may not be totally accurate unless you
* are the responder.
*/
create: (config: PanResponderConfig) =>
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
getInteractionHandle: () => null | undefined | number;
panHandlers:
/*[FLOW2DTS - Warning] This type was an exact object type in the original Flow source.*/
{
onMoveShouldSetResponder: (event: PressEvent) => boolean;
onMoveShouldSetResponderCapture: (event: PressEvent) => boolean;
onResponderEnd: (event: PressEvent) => void;
onResponderGrant: (event: PressEvent) => boolean;
onResponderMove: (event: PressEvent) => void;
onResponderReject: (event: PressEvent) => void;
onResponderRelease: (event: PressEvent) => void;
onResponderStart: (event: PressEvent) => void;
onResponderTerminate: (event: PressEvent) => void;
onResponderTerminationRequest: (event: PressEvent) => boolean;
onStartShouldSetResponder: (event: PressEvent) => boolean;
onStartShouldSetResponderCapture: (event: PressEvent) => boolean;
};
};
};
declare type PanResponderInstance = ReturnType<typeof PanResponder["create"]>;
export type { GestureState };
export type { PanResponderInstance };
declare const $f2tExportDefault: typeof PanResponder;
export default $f2tExportDefault; | the_stack |
import '@material/mwc-button';
import '@material/mwc-dialog';
import '@material/mwc-textarea';
import { MobxLitElement } from '@adobe/lit-mobx';
import { TextArea } from '@material/mwc-textarea';
import { Router } from '@vaadin/router';
import { css, customElement, html, TemplateResult } from 'lit-element';
import { observable } from 'mobx';
import '../../components/build_tag_row';
import '../../components/build_step_list';
import '../../components/link';
import '../../components/log';
import '../../components/property_viewer';
import '../../components/test_variants_table/test_variant_entry';
import '../../components/timestamp';
import { AppState, consumeAppState } from '../../context/app_state';
import { BuildState, consumeBuildState } from '../../context/build_state';
import { consumeInvocationState, InvocationState } from '../../context/invocation_state';
import { consumeConfigsStore, UserConfigsStore } from '../../context/user_configs';
import { GA_ACTIONS, GA_CATEGORIES, trackEvent } from '../../libs/analytics_utils';
import {
getBotLink,
getBuildbucketLink,
getURLForGerritChange,
getURLForGitilesCommit,
getURLForSwarmingTask,
getURLPathForBuild,
} from '../../libs/build_utils';
import { BUILD_STATUS_CLASS_MAP, BUILD_STATUS_DISPLAY_MAP } from '../../libs/constants';
import { consumer } from '../../libs/context';
import { renderMarkdown } from '../../libs/markdown_utils';
import { sanitizeHTML } from '../../libs/sanitize_html';
import { displayDuration } from '../../libs/time_utils';
import { router } from '../../routes';
import { BuildStatus, GitilesCommit } from '../../services/buildbucket';
import { getPropKeyLabel } from '../../services/resultdb';
import colorClasses from '../../styles/color_classes.css';
import commonStyle from '../../styles/common_style.css';
const MAX_DISPLAYED_UNEXPECTED_TESTS = 10;
@customElement('milo-overview-tab')
@consumer
export class OverviewTabElement extends MobxLitElement {
@observable.ref
@consumeAppState()
appState!: AppState;
@observable.ref
@consumeConfigsStore()
configsStore!: UserConfigsStore;
@observable.ref
@consumeBuildState()
buildState!: BuildState;
@observable.ref
@consumeInvocationState()
invocationState!: InvocationState;
@observable.ref private showRetryDialog = false;
@observable.ref private showCancelDialog = false;
connectedCallback() {
super.connectedCallback();
this.appState.selectedTabId = 'overview';
trackEvent(GA_CATEGORIES.OVERVIEW_TAB, GA_ACTIONS.TAB_VISITED, window.location.href);
}
private renderActionButtons() {
const build = this.buildState.build!;
const canRetry = this.buildState.permittedActions.has('ADD_BUILD');
const canCancel = this.buildState.permittedActions.has('CANCEL_BUILD');
if (build.endTime) {
return html`
<h3>Actions</h3>
<div title=${canRetry ? '' : 'You have no permission to retry this build.'}>
<mwc-button dense unelevated @click=${() => (this.showRetryDialog = true)} ?disabled=${!canRetry}>
Retry Build
</mwc-button>
</div>
`;
}
return html`
<h3>Actions</h3>
<div title=${canCancel ? '' : 'You have no permission to cancel this build.'}>
<mwc-button dense unelevated @click=${() => (this.showCancelDialog = true)} ?disabled=${!canCancel}>
Cancel Build
</mwc-button>
</div>
`;
}
private renderCanaryWarning() {
if (!this.buildState.build?.isCanary) {
return html``;
}
if ([BuildStatus.Failure, BuildStatus.InfraFailure].indexOf(this.buildState.build!.status) === -1) {
return html``;
}
return html`
<div id="canary-warning" class="warning">
WARNING: This build ran on a canary version of LUCI. If you suspect it failed due to infra, retry the build.
Next time it may use the non-canary version.
</div>
`;
}
private async cancelBuild(reason: string) {
await this.appState.buildsService!.cancelBuild({
id: this.buildState.build!.id,
summaryMarkdown: reason,
});
this.appState.refresh();
}
private async retryBuild() {
const build = await this.appState.buildsService!.scheduleBuild({
templateBuildId: this.buildState.build!.id,
});
Router.go(getURLPathForBuild(build));
}
private renderSummary() {
const build = this.buildState.build!;
if (!build.summaryMarkdown) {
return html`
<div id="summary-html" class="${BUILD_STATUS_CLASS_MAP[build.status]}-bg">
<div id="status">Build ${BUILD_STATUS_DISPLAY_MAP[build.status] || 'status unknown'}</div>
</div>
`;
}
return html`
<div id="summary-html" class="${BUILD_STATUS_CLASS_MAP[build.status]}-bg">
${renderMarkdown(build.summaryMarkdown)}
</div>
`;
}
private renderBuilderDescription() {
const descriptionHtml = this.buildState.builder?.config.descriptionHtml;
if (!descriptionHtml) {
return html``;
}
return html`
<h3>Builder Info</h3>
<div id="builder-description">${sanitizeHTML(descriptionHtml)}</div>
`;
}
private renderRevision(gitilesCommit: GitilesCommit) {
return html`
<tr>
<td>Revision:</td>
<td>
<a href=${getURLForGitilesCommit(gitilesCommit)} target="_blank">${gitilesCommit.id}</a>
${gitilesCommit.position ? `CP #${gitilesCommit.position}` : ''}
</td>
</tr>
`;
}
private renderInput() {
const input = this.buildState.build?.input;
if (!input?.gitilesCommit && !input?.gerritChanges) {
return html``;
}
return html`
<h3>Input</h3>
<table>
${input.gitilesCommit ? this.renderRevision(input.gitilesCommit) : ''}
${(input.gerritChanges || []).map(
(gc) => html`
<tr>
<td>Patch:</td>
<td>
<a href=${getURLForGerritChange(gc)}> ${gc.change} (ps #${gc.patchset}) </a>
</td>
</tr>
`
)}
</table>
`;
}
private renderOutput() {
const output = this.buildState.build?.output;
if (!output?.gitilesCommit) {
return html``;
}
return html`
<h3>Output</h3>
<table>
${this.renderRevision(output.gitilesCommit)}
</table>
`;
}
private renderInfra() {
const build = this.buildState.build!;
const botLink = build.infra?.swarming ? getBotLink(build.infra.swarming) : null;
return html`
<h3>Infra</h3>
<table>
<tr>
<td>Buildbucket ID:</td>
<td><milo-link .link=${getBuildbucketLink(CONFIGS.BUILDBUCKET.HOST, build.id)} target="_blank"></td>
</tr>
${
build.infra?.swarming
? html`
<tr>
<td>Swarming Task:</td>
<td>
${!build.infra.swarming.taskId
? 'N/A'
: html`
<a href=${getURLForSwarmingTask(build.infra.swarming.hostname, build.infra.swarming.taskId)}>
${build.infra.swarming.taskId}
</a>
`}
</td>
</tr>
<tr>
<td>Bot:</td>
<td>${botLink ? html`<milo-link .link=${botLink} target="_blank"></milo-link>` : 'N/A'}</td>
</tr>
<tr>
<td>Service Account:</td>
<td>${build.infra.swarming.taskServiceAccount}</td>
</tr>
`
: ''
}
<tr>
<td>Recipe:</td>
<td><milo-link .link=${build.recipeLink} target="_blank"></milo-link></td>
</tr>
</table>
`;
}
private renderFailedTests() {
if (!this.invocationState.hasInvocation) {
return;
}
const testLoader = this.invocationState.testLoader;
const testsTabUrl = router.urlForName('build-test-results', {
...this.buildState.builderIdParam!,
build_num_or_id: this.buildState.buildNumOrIdParam!,
});
// Overview tab is more crowded than the test results tab.
// Hide all additional columns.
const columnWidths = this.invocationState.columnWidths.map(() => '0').join(' ');
return html`
<h3>Failed Tests (<a href=${testsTabUrl}>View All Test</a>)</h3>
<div id="failed-tests-section-body">
${testLoader?.firstPageLoaded
? html`
<div style="--columns: ${columnWidths}">${this.renderFailedTestList()}</div>
<div id="failed-test-count">
${testLoader.unfilteredUnexpectedVariantsCount === 0
? 'No failed tests.'
: html`Showing
${Math.min(testLoader.unfilteredUnexpectedVariantsCount, MAX_DISPLAYED_UNEXPECTED_TESTS)} /
${testLoader.unfilteredUnexpectedVariantsCount} failed tests.
<a href=${testsTabUrl}>[view all]</a>`}
</div>
`
: html`<div id="loading-spinner">Loading <milo-dot-spinner></milo-dot-spinner></div>`}
</div>
`;
}
private renderFailedTestList() {
const testLoader = this.invocationState.testLoader!;
const groupDefs = this.invocationState.groupers
.filter(([key]) => key !== 'status')
.map(([key, getter]) => [getPropKeyLabel(key), getter] as [string, typeof getter]);
let remaining = MAX_DISPLAYED_UNEXPECTED_TESTS;
const htmlTemplates: TemplateResult[] = [];
for (const group of testLoader.groupedUnfilteredUnexpectedVariants) {
if (remaining === 0) {
break;
}
if (groupDefs.length !== 0) {
htmlTemplates.push(html`<h4>${groupDefs.map(([label, getter]) => html`${label}: ${getter(group[0])}`)}</h4>`);
}
for (const testVariant of group) {
if (remaining === 0) {
break;
}
remaining--;
htmlTemplates.push(html`
<milo-test-variant-entry
.variant=${testVariant}
.columnGetters=${this.invocationState.displayedColumnGetters}
></milo-test-variant-entry>
`);
}
}
return htmlTemplates;
}
private renderSteps() {
const stepsUrl = router.urlForName('build-steps', {
...this.buildState.builderIdParam,
build_num_or_id: this.buildState.buildNumOrIdParam!,
});
return html`
<div>
<h3>Steps & Logs (<a href=${stepsUrl}>View in Steps Tab</a>)</h3>
<div id="step-config">
Show:
<input
id="succeeded"
type="checkbox"
?checked=${this.configsStore.userConfigs.steps.showSucceededSteps}
@change=${(e: MouseEvent) => {
this.configsStore.userConfigs.steps.showSucceededSteps = (e.target as HTMLInputElement).checked;
}}
/>
<label for="succeeded" style="color: var(--success-color);">Succeeded Steps</label>
<span> </span>
<input
id="debug-logs"
type="checkbox"
?checked=${this.configsStore.userConfigs.steps.showDebugLogs}
@change=${(e: MouseEvent) => {
this.configsStore.userConfigs.steps.showDebugLogs = (e.target as HTMLInputElement).checked;
}}
/>
<label id="debug-logs-label" for="debug-logs">Debug Logs</label>
<input
id="expand-by-default"
type="checkbox"
?checked=${this.configsStore.userConfigs.steps.expandByDefault}
@change=${(e: MouseEvent) => {
this.configsStore.userConfigs.steps.expandByDefault = (e.target as HTMLInputElement).checked;
}}
/>
<label for="expand-by-default">Expand by default</label>
</div>
<milo-build-step-list></milo-build-step-list>
</div>
`;
}
private renderTiming() {
const build = this.buildState.build!;
return html`
<h3>Timing</h3>
<table>
<tr>
<td>Created:</td>
<td>
<milo-timestamp .datetime=${build.createTime}></milo-timestamp>
</td>
</tr>
<tr>
<td>Started:</td>
<td>${build.startTime ? html`<milo-timestamp .datetime=${build.startTime}></milo-timestamp>` : 'N/A'}</td>
</tr>
<tr>
<td>Ended:</td>
<td>${build.endTime ? html`<milo-timestamp .datetime=${build.endTime}></milo-timestamp>` : 'N/A'}</td>
</tr>
<tr>
<td>Pending:</td>
<td>
${displayDuration(build.pendingDuration)} ${build.isPending ? '(and counting)' : ''}
${build.exceededSchedulingTimeout ? html`<span class="warning">(exceeded timeout)</span>` : ''}
<mwc-icon
class="inline-icon"
title="Maximum pending duration: ${build.schedulingTimeout
? displayDuration(build.schedulingTimeout)
: 'N/A'}"
>info</mwc-icon
>
</td>
</tr>
<tr>
<td>Execution:</td>
<td>
${build.executionDuration ? displayDuration(build.executionDuration) : 'N/A'}
${build.isExecuting ? '(and counting)' : ''}
${build.exceededExecutionTimeout ? html`<span class="warning">(exceeded timeout)</span>` : ''}
<mwc-icon
class="inline-icon"
title="Maximum execution duration: ${build.executionTimeout
? displayDuration(build.executionTimeout)
: 'N/A'}"
>info</mwc-icon
>
</td>
</tr>
</table>
`;
}
private renderTags() {
const tags = this.buildState.build?.tags;
if (!tags) {
return html``;
}
return html`
<h3>Tags</h3>
<table>
${tags.map((tag) => html` <milo-build-tag-row .key=${tag.key} .value=${tag.value}> </milo-build-tag-row> `)}
</table>
`;
}
private renderExperiments() {
const experiments = this.buildState.build?.input?.experiments;
if (!experiments) {
return html``;
}
return html`
<h3>Enabled Experiments</h3>
<ul>
${experiments.map((exp) => html`<li>${exp}</li>`)}
</ul>
`;
}
private renderBuildLogs() {
const logs = this.buildState.build?.output?.logs;
if (!logs) {
return html``;
}
return html`
<h3>Build Logs</h3>
<ul>
${logs.map((log) => html`<li><milo-log .log=${log}></li>`)}
</ul>
`;
}
protected render() {
const build = this.buildState.build;
if (!build) {
return html``;
}
return html`
<mwc-dialog
heading="Retry Build"
?open=${this.showRetryDialog}
@closed=${async (event: CustomEvent<{ action: string }>) => {
if (event.detail.action === 'retry') {
await this.retryBuild();
}
this.showRetryDialog = false;
}}
>
<p>Note: this doesn't trigger anything else (e.g. CQ).</p>
<mwc-button slot="primaryAction" dialogAction="retry" dense unelevated>Retry</mwc-button>
<mwc-button slot="secondaryAction" dialogAction="dismiss">Dismiss</mwc-button>
</mwc-dialog>
<mwc-dialog
heading="Cancel Build"
?open=${this.showCancelDialog}
@closed=${async (event: CustomEvent<{ action: string }>) => {
if (event.detail.action === 'cancel') {
const reason = (this.shadowRoot!.getElementById('cancel-reason') as TextArea).value;
await this.cancelBuild(reason);
}
this.showCancelDialog = false;
}}
>
<mwc-textarea id="cancel-reason" label="Reason" required></mwc-textarea>
<mwc-button slot="primaryAction" dialogAction="cancel" dense unelevated>Cancel</mwc-button>
<mwc-button slot="secondaryAction" dialogAction="dismiss">Dismiss</mwc-button>
</mwc-dialog>
<div id="main">
<div class="first-column">
${this.renderCanaryWarning()}${this.renderSummary()}${this.renderFailedTests()}${this.renderSteps()}
</div>
<div class="second-column">
${this.renderBuilderDescription()} ${this.renderInput()} ${this.renderOutput()} ${this.renderInfra()}
${this.renderTiming()} ${this.renderBuildLogs()} ${this.renderActionButtons()} ${this.renderTags()}
${this.renderExperiments()}
<h3>Input Properties</h3>
<milo-property-viewer
.properties=${build.input?.properties || {}}
.propLineFoldTime=${this.configsStore.userConfigs.inputPropLineFoldTime}
></milo-property-viewer>
<h3>Output Properties</h3>
<milo-property-viewer
.properties=${build.output?.properties || {}}
.propLineFoldTime=${this.configsStore.userConfigs.outputPropLineFoldTime}
></milo-property-viewer>
</div>
</div>
`;
}
static styles = [
commonStyle,
colorClasses,
css`
#main {
margin: 10px 16px;
}
@media screen and (min-width: 1300px) {
#main {
display: grid;
grid-template-columns: 1fr 20px 40vw;
}
.second-column > h3:first-child {
margin-block: 5px 10px;
}
}
.first-column {
overflow: hidden;
grid-column: 1;
}
.second-column {
overflow: hidden;
grid-column: 3;
}
h3 {
margin-block: 15px 10px;
}
h4 {
margin-block: 10px 10px;
}
#summary-html {
padding: 0 10px;
clear: both;
overflow-wrap: break-word;
}
#summary-html pre {
white-space: pre-wrap;
overflow-wrap: break-word;
font-size: 12px;
}
#summary-html * {
margin-block: 10px;
}
#status {
font-weight: 500;
}
:host > mwc-dialog {
margin: 0 0;
}
#cancel-reason {
width: 500px;
height: 200px;
}
#canary-warning {
padding: 5px;
}
.warning {
background-color: var(--warning-color);
font-weight: 500;
}
td:nth-child(2) {
clear: both;
overflow-wrap: anywhere;
}
/*
* Use normal text color and add extra margin so it's easier to tell where
* does the failed tests section ends and the steps section starts.
*/
#failed-tests-section-body {
margin-bottom: 25px;
}
#failed-test-count > a {
color: var(--default-text-color);
}
#failed-test-count {
margin-top: 10px;
}
#loading-spinner {
color: var(--active-text-color);
}
#step-buttons {
float: right;
}
#step-config {
margin-bottom: 10px;
}
#debug-logs-label {
margin-right: 50px;
}
milo-property-viewer {
min-width: 600px;
max-width: 1000px;
}
mwc-button {
width: 155px;
}
.inline-icon {
--mdc-icon-size: 1.2em;
vertical-align: bottom;
width: 16px;
height: 16px;
}
`,
];
} | the_stack |
import { assertNever } from "@opticss/util";
export type AnySelector<isDefinition extends DefinitionAST | BlockAST> =
ComplexSelector<isDefinition>
| ContextCompoundSelector<isDefinition>
| KeyCompoundSelector<isDefinition>
| ScopeSelector
| ClassSelector
| AttributeSelector
| ForeignAttributeSelector
| PseudoClassSelector
| PseudoElementSelector;
export type TopLevelNode<isDefinition extends DefinitionAST | BlockAST> = BlockSyntaxVersion | BlockReference | LocalBlockExport | BlockExport | Rule<isDefinition> | GlobalDeclaration;
export type Node<isDefinition extends DefinitionAST | BlockAST> =
Root<isDefinition>
| TopLevelNode<isDefinition>
| AnySelector<isDefinition>
| Declaration;
const NODE_TYPES = new Set<Node<BlockAST>["type"]>();
export interface Name {
name: string;
asName?: undefined;
}
export interface Rename {
name: string;
asName: string;
}
export interface Root<isDefinition extends DefinitionAST | BlockAST = BlockAST> {
type: "Root";
children: Array<TopLevelNode<isDefinition>>;
}
NODE_TYPES.add("Root");
export type DefinitionAST = "definition";
export type BlockAST = "block";
export type DefinitionRoot = Root<DefinitionAST>;
export interface BlockSyntaxVersion {
type: "BlockSyntaxVersion";
version: number;
}
NODE_TYPES.add("BlockSyntaxVersion");
export interface BlockReference {
type: "BlockReference";
references?: Array<Name | Rename>;
defaultName?: string;
fromPath: string;
}
NODE_TYPES.add("BlockReference");
/* The statement that exports a block that was previously imported via `@block` */
export interface LocalBlockExport {
type: "LocalBlockExport";
exports: Array<Name | Rename>;
}
NODE_TYPES.add("LocalBlockExport");
/* The statement that exports a block that was previously imported via `@block` */
export interface BlockExport {
type: "BlockExport";
exports: Array<Name | Rename>;
fromPath: string;
}
NODE_TYPES.add("BlockExport");
export type KeyCompoundSelector<isDefinition extends DefinitionAST | BlockAST> = CompoundSelector<isDefinition, AttributeSelector, PseudoClassSelector, PseudoElementSelector>;
export type ContextCompoundSelector<isDefinition extends DefinitionAST | BlockAST> = CompoundSelector<isDefinition, ForeignAttributeSelector | AttributeSelector, PseudoClassSelector, never>;
export type ElementSelector = ScopeSelector | ClassSelector;
export type Selector<isDefinition extends DefinitionAST | BlockAST> = ElementSelector | KeyCompoundSelector<isDefinition> | ComplexSelector<isDefinition>;
export interface PseudoElementSelector {
type: "PseudoElementSelector";
/** The name of the psuedoelement without the `::` at the beginning. */
name: string;
}
NODE_TYPES.add("PseudoElementSelector");
export interface PseudoClassSelector {
type: "PseudoClassSelector";
/** The name of the psuedoclass without the `:` at the beginning. */
name: string;
}
NODE_TYPES.add("PseudoClassSelector");
export interface SelectorAndCombinator<isDefinition extends DefinitionAST | BlockAST> {
selector: ContextCompoundSelector<isDefinition>;
combinator: " " | ">" | "+" | "~";
}
export interface ComplexSelector<isDefinition extends DefinitionAST | BlockAST> {
type: "ComplexSelector";
/** There should be at least one context selector. */
contextSelectors: Array<SelectorAndCombinator<isDefinition>>;
keySelector: KeyCompoundSelector<isDefinition>;
}
NODE_TYPES.add("ComplexSelector");
export interface CompoundSelector<
isDefinition extends DefinitionAST | BlockAST,
AttributeSelectorType extends ForeignAttributeSelector | AttributeSelector,
PseudoClassType extends PseudoClassSelector | never,
PseudoElementType extends PseudoElementSelector | never,
> {
type: "CompoundSelector";
element: ElementSelector;
attributes?: Array<AttributeSelectorType>;
elementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : (PseudoClassType extends never ? undefined : Array<PseudoClassType>);
pseudoElement?: PseudoElementType;
pseudoElementPseudoClasses?: isDefinition extends DefinitionAST
? undefined
: (PseudoElementSelector extends never
? undefined
: (PseudoClassType extends never ? undefined : Array<PseudoClassType>));
}
NODE_TYPES.add("CompoundSelector");
export interface ForeignAttributeSelector {
type: "ForeignAttributeSelector";
ns: string;
attribute: string;
matches?: {
matcher: "=";
value: string;
};
}
NODE_TYPES.add("ForeignAttributeSelector");
export interface AttributeSelector {
type: "AttributeSelector";
ns?: undefined;
attribute: string;
matches?: {
matcher: "=";
value: string;
};
}
NODE_TYPES.add("AttributeSelector");
export interface ScopeSelector {
type: "ScopeSelector";
value: ":scope";
}
NODE_TYPES.add("ScopeSelector");
export interface ClassSelector {
type: "ClassSelector";
/** The name of the class without the `.` at the beginning. */
name: string;
}
NODE_TYPES.add("ClassSelector");
export interface Declaration {
type: "Declaration";
property: string;
value: string;
}
NODE_TYPES.add("Declaration");
export interface Rule<isDefinition extends DefinitionAST | BlockAST> {
type: "Rule";
selectors: Array<Selector<isDefinition>>;
declarations: Array<Declaration>;
}
NODE_TYPES.add("Rule");
export interface GlobalDeclaration {
type: "GlobalDeclaration";
selector: AttributeSelector;
}
NODE_TYPES.add("GlobalDeclaration");
export namespace typeguards {
export function isNode<isDefinition extends DefinitionAST | BlockAST>(node: unknown): node is Node<isDefinition> {
return typeof node === "object"
&& node !== null
&& typeof (<Node<isDefinition>>node).type === "string"
&& NODE_TYPES.has((<Node<isDefinition>>node).type);
}
export function isRoot<isDefinition extends DefinitionAST | BlockAST>(node: unknown): node is Root<isDefinition> {
return typeguards.isNode(node) && node.type === "Root";
}
export function isBlockSyntaxVersion(node: unknown): node is BlockSyntaxVersion {
return typeguards.isNode(node) && node.type === "BlockSyntaxVersion";
}
export function isBlockReference(node: unknown): node is BlockReference {
return typeguards.isNode(node) && node.type === "BlockReference";
}
export function isBlockExport(node: unknown): node is BlockExport {
return typeguards.isNode(node) && node.type === "BlockExport";
}
export function isLocalBlockExport(node: unknown): node is LocalBlockExport {
return typeguards.isNode(node) && node.type === "LocalBlockExport";
}
export function isPseudoElementSelector(node: unknown): node is PseudoElementSelector {
return typeguards.isNode(node) && node.type === "PseudoElementSelector";
}
export function isPseudoClassSelector(node: unknown): node is PseudoClassSelector {
return typeguards.isNode(node) && node.type === "PseudoClassSelector";
}
export function isComplexSelector<isDefinition extends DefinitionAST | BlockAST>(node: unknown): node is ComplexSelector<isDefinition> {
return typeguards.isNode(node) && node.type === "ComplexSelector";
}
export function isCompoundSelector<isDefinition extends DefinitionAST | BlockAST>(node: unknown): node is KeyCompoundSelector<isDefinition> | ContextCompoundSelector<isDefinition> {
return typeguards.isNode(node) && node.type === "CompoundSelector";
}
export function isAttributeSelector(node: unknown): node is AttributeSelector {
return typeguards.isNode(node) && node.type === "AttributeSelector";
}
export function isForeignAttributeSelector(node: unknown): node is ForeignAttributeSelector {
return typeguards.isNode(node) && node.type === "ForeignAttributeSelector";
}
export function isScopeSelector(node: unknown): node is ScopeSelector {
return typeguards.isNode(node) && node.type === "ScopeSelector";
}
export function isClassSelector(node: unknown): node is ClassSelector {
return typeguards.isNode(node) && node.type === "ClassSelector";
}
export function isDeclaration(node: unknown): node is Declaration {
return typeguards.isNode(node) && node.type === "Declaration";
}
export function isRule<isDefinition extends DefinitionAST | BlockAST>(node: unknown): node is Rule<isDefinition> {
return typeguards.isNode(node) && node.type === "Rule";
}
export function isGlobalDeclaration(node: unknown): node is GlobalDeclaration {
return typeguards.isNode(node) && node.type === "GlobalDeclaration";
}
}
export namespace builders {
export function root<isDefinition extends DefinitionAST | BlockAST>(children: Array<TopLevelNode<isDefinition>> = []): Root<isDefinition> {
return {
type: "Root",
children,
};
}
export function blockSyntaxVersion(version: number): BlockSyntaxVersion {
return {
type: "BlockSyntaxVersion",
version,
};
}
export function blockReference(fromPath: string, defaultName: string | undefined, references: Array<Name | Rename> | undefined): BlockReference {
return {
type: "BlockReference",
fromPath,
defaultName,
references,
};
}
export function localBlockExport(exports: Array<Name | Rename>): LocalBlockExport {
return {
type: "LocalBlockExport",
exports,
};
}
export function blockExport(fromPath: string, exports: Array<Name | Rename>): BlockExport {
return {
type: "BlockExport",
fromPath,
exports,
};
}
export function pseudoElementSelector(name: string): PseudoElementSelector {
return {
type: "PseudoElementSelector",
name,
};
}
export function pseudoClassSelector(name: string): PseudoClassSelector {
return {
type: "PseudoClassSelector",
name,
};
}
export function complexSelector<isDefinition extends DefinitionAST | BlockAST>(contextSelectors: Array<SelectorAndCombinator<isDefinition>>, keySelector: KeyCompoundSelector<isDefinition>): ComplexSelector<isDefinition> {
if (contextSelectors.length === 0) {
throw new Error("At least one context selector is required to build a complex selector.");
}
return {
type: "ComplexSelector",
keySelector,
contextSelectors,
};
}
export function compoundSelector<isDefinition extends DefinitionAST | BlockAST>(
element: ElementSelector,
attributes?: Array<ForeignAttributeSelector | AttributeSelector>,
elementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
pseudoElement?: PseudoElementSelector,
pseudoElementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
): CompoundSelector<isDefinition, AttributeSelector | ForeignAttributeSelector, PseudoClassSelector, PseudoElementSelector> {
return {
type: "CompoundSelector",
element,
attributes,
elementPseudoClasses,
pseudoElement,
pseudoElementPseudoClasses,
};
}
export function keyCompoundSelector<isDefinition extends DefinitionAST | BlockAST>(
element: ElementSelector,
attributes?: Array<AttributeSelector>,
elementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
pseudoElement?: PseudoElementSelector,
pseudoElementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
): KeyCompoundSelector<isDefinition> {
return {
type: "CompoundSelector",
element,
attributes,
elementPseudoClasses,
pseudoElement,
pseudoElementPseudoClasses,
};
}
export function contextCompoundSelector<isDefinition extends DefinitionAST | BlockAST>(
element: ElementSelector,
attributes?: Array<ForeignAttributeSelector | AttributeSelector>,
elementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
pseudoElementPseudoClasses?: isDefinition extends DefinitionAST ? undefined : Array<PseudoClassSelector>,
): ContextCompoundSelector<isDefinition> {
return {
type: "CompoundSelector",
element,
attributes,
elementPseudoClasses,
pseudoElementPseudoClasses,
};
}
export function attributeSelector(attribute: string, value?: string): AttributeSelector {
let attrSelector: AttributeSelector = {
type: "AttributeSelector",
attribute,
};
if (value) {
attrSelector.matches = { matcher: "=", value };
}
return attrSelector;
}
export function foreignAttributeSelector(ns: string, attribute: string, value?: string): ForeignAttributeSelector {
let attrSelector: ForeignAttributeSelector = {
type: "ForeignAttributeSelector",
ns,
attribute,
};
if (value) {
attrSelector.matches = { matcher: "=", value };
}
return attrSelector;
}
export function scopeSelector(): ScopeSelector {
return {
type: "ScopeSelector",
value: ":scope",
};
}
export function classSelector(name: string): ClassSelector {
return {
type: "ClassSelector",
name,
};
}
export function declaration(property: string, value: string): Declaration {
return {
type: "Declaration",
property,
value,
};
}
export function rule<isDefinition extends DefinitionAST | BlockAST>(selectors: Array<Selector<isDefinition>>, declarations: Array<Declaration>): Rule<isDefinition> {
return {
type: "Rule",
selectors,
declarations,
};
}
export function globalDeclaration(selector: AttributeSelector): GlobalDeclaration {
return {
type: "GlobalDeclaration",
selector,
};
}
}
export interface Visitor<isDefinition extends DefinitionAST | BlockAST> {
Root?(root: Root<isDefinition>): void | boolean | undefined;
BlockSyntaxVersion?(blockSyntaxVersion: BlockSyntaxVersion): void | boolean | undefined;
BlockReference?(blockReference: BlockReference): void | boolean | undefined;
LocalBlockExport?(localBlockExport: LocalBlockExport): void | boolean | undefined;
BlockExport?(blockExport: BlockExport): void | boolean | undefined;
PseudoElementSelector?(pseudoElementSelector: PseudoElementSelector): void | boolean | undefined;
PseudoClassSelector?(pseudoClassSelector: PseudoClassSelector): void | boolean | undefined;
ComplexSelector?(complexSelector: ComplexSelector<isDefinition>): void | boolean | undefined;
CompoundSelector?(compoundSelector: KeyCompoundSelector<isDefinition> | ContextCompoundSelector<isDefinition>): void | boolean | undefined;
AttributeSelector?(attributeSelector: AttributeSelector): void | boolean | undefined;
ForeignAttributeSelector?(foreignAttributeSelector: ForeignAttributeSelector): void | boolean | undefined;
ScopeSelector?(scopeSelector: ScopeSelector): void | boolean | undefined;
ClassSelector?(classSelector: ClassSelector): void | boolean | undefined;
Declaration?(declaration: Declaration): void | boolean | undefined;
Rule?(rule: Rule<isDefinition>): void | boolean | undefined;
GlobalDeclaration?(globalDeclaration: GlobalDeclaration): void | boolean | undefined;
}
export interface Mapper<
isToDefinition extends DefinitionAST | BlockAST
> {
Root?(children: Array<TopLevelNode<isToDefinition>>): Root<isToDefinition>;
BlockSyntaxVersion?(version: number): BlockSyntaxVersion;
BlockReference?(fromPath: string, defaultName: string | undefined, references: Array<Name | Rename> | undefined): BlockReference;
LocalBlockExport?(exports: Array<Name | Rename>): LocalBlockExport;
BlockExport?(fromPath: string, exports: Array<Name | Rename>): BlockExport;
PseudoElementSelector?(name: string): PseudoElementSelector;
PseudoClassSelector?(name: string): PseudoClassSelector;
ComplexSelector?(contextSelectors: Array<SelectorAndCombinator<isToDefinition>>, keySelector: KeyCompoundSelector<isToDefinition>): ComplexSelector<isToDefinition>;
CompoundSelector?(
element: ElementSelector,
attributes?: Array<AttributeSelector | ForeignAttributeSelector>,
elementPseudoClasses?: Array<PseudoClassSelector>,
pseudoElement?: PseudoElementSelector,
pseudoElementPseudoClasses?: Array<PseudoClassSelector>,
): KeyCompoundSelector<isToDefinition> | ContextCompoundSelector<isToDefinition>;
AttributeSelector?(attribute: string, value?: string): AttributeSelector;
ForeignAttributeSelector?(ns: string, attribute: string, value?: string): ForeignAttributeSelector;
ScopeSelector?(): ScopeSelector;
ClassSelector?(name: string): ClassSelector;
Declaration?(property: string, value: string): Declaration;
Rule?(selectors: Array<Selector<isToDefinition>>, declarations: Array<Declaration>): Rule<isToDefinition>;
GlobalDeclaration?(selector: AttributeSelector): GlobalDeclaration;
}
export function map<
isFromDefinition extends DefinitionAST | BlockAST,
isToDefinition extends DefinitionAST | BlockAST,
N extends Node<isFromDefinition>,
>(mapper: Mapper<isToDefinition>, node: N, fromType: isFromDefinition, toType: isToDefinition,
): N extends Root<isFromDefinition> ? Root<isToDefinition> :
(N extends Rule<isFromDefinition> ? Rule<isToDefinition> :
(N extends ComplexSelector<isFromDefinition> ? ComplexSelector<isToDefinition> :
(N extends ContextCompoundSelector<isFromDefinition> ? ContextCompoundSelector<isToDefinition> :
(N extends KeyCompoundSelector<isFromDefinition> ? KeyCompoundSelector<isToDefinition> : N)))) {
if (typeguards.isRoot<isFromDefinition>(node)) {
let children: Array<TopLevelNode<isToDefinition>> = [];
for (let child of node.children) {
let c: TopLevelNode<isToDefinition> = map(mapper, child, fromType, toType);
children.push(c);
}
let ret: Root<isToDefinition>;
if (mapper.Root) {
ret = mapper.Root(children);
} else {
ret = builders.root(children);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isBlockSyntaxVersion(node)) {
let ret: BlockSyntaxVersion;
if (mapper.BlockSyntaxVersion) {
ret = mapper.BlockSyntaxVersion(node.version);
} else {
ret = builders.blockSyntaxVersion(node.version);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isBlockReference(node)) {
let references: BlockReference["references"] | undefined;
if (node.references) {
references = [];
for (let ref of node.references) {
references.push(Object.assign({}, ref));
}
}
let ret: BlockReference;
if (mapper.BlockReference) {
ret = mapper.BlockReference(node.fromPath, node.defaultName, references);
} else {
ret = builders.blockReference(node.fromPath, node.defaultName, references);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isBlockExport(node)) {
let exports: BlockExport["exports"] = [];
for (let e of node.exports) {
exports.push(Object.assign({}, e));
}
let ret: BlockExport;
if (mapper.BlockExport) {
ret = mapper.BlockExport(node.fromPath, exports);
} else {
ret = builders.blockExport(node.fromPath, exports);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isLocalBlockExport(node)) {
let exports: LocalBlockExport["exports"] = [];
for (let e of node.exports) {
exports.push(Object.assign({}, e));
}
let ret: LocalBlockExport;
if (mapper.LocalBlockExport) {
ret = mapper.LocalBlockExport(exports);
} else {
ret = builders.localBlockExport(exports);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isComplexSelector<isFromDefinition>(node)) {
let contextSelectors: ComplexSelector<isToDefinition>["contextSelectors"] = [];
for (let ctx of node.contextSelectors) {
contextSelectors.push({selector: map(mapper, ctx.selector, fromType, toType), combinator: ctx.combinator});
}
let keySelector = map(mapper, node.keySelector, fromType, toType);
let ret: ComplexSelector<isToDefinition>;
if (mapper.ComplexSelector) {
ret = mapper.ComplexSelector(contextSelectors, keySelector);
} else {
ret = builders.complexSelector(contextSelectors, keySelector);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isForeignAttributeSelector(node)) {
let {ns, attribute, matches} = node;
let value = matches ? matches.value : undefined;
let ret: ForeignAttributeSelector;
if (mapper.ForeignAttributeSelector) {
ret = mapper.ForeignAttributeSelector(ns, attribute, value);
} else {
ret = builders.foreignAttributeSelector(ns, attribute, value);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isAttributeSelector(node)) {
let {attribute, matches} = node;
let value = matches ? matches.value : undefined;
let ret: AttributeSelector;
if (mapper.AttributeSelector) {
ret = mapper.AttributeSelector(attribute, value);
} else {
ret = builders.attributeSelector(attribute, value);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isCompoundSelector<isFromDefinition>(node)) {
let element = map(mapper, node.element, fromType, toType);
let attributes: Array<ForeignAttributeSelector | AttributeSelector> | undefined;
// []
if (node.attributes) {
attributes = [];
for (let attr of node.attributes) { attributes.push(map(mapper, attr, fromType, toType)); }
}
let elementPseudoClasses: Array<PseudoClassSelector> | undefined;
if (node.elementPseudoClasses && toType === "block") {
elementPseudoClasses = [];
for (let pseudoclass of <Array<PseudoClassSelector>>node.elementPseudoClasses) { elementPseudoClasses.push(map(mapper, pseudoclass, fromType, toType)); }
}
let psuedoElement: PseudoElementSelector | undefined;
if (node.pseudoElement) {
psuedoElement = map(mapper, node.pseudoElement, fromType, toType);
}
let pseudoElementPseudoClasses: Array<PseudoClassSelector> | undefined;
if (node.pseudoElementPseudoClasses) {
pseudoElementPseudoClasses = [];
for (let pseudoclass of <Array<PseudoClassSelector>>node.pseudoElementPseudoClasses) { pseudoElementPseudoClasses.push(map(mapper, pseudoclass, fromType, toType)); }
}
let ret: CompoundSelector<isToDefinition, ForeignAttributeSelector | AttributeSelector, PseudoClassSelector, PseudoElementSelector>;
if (mapper.CompoundSelector) {
ret = mapper.CompoundSelector(element, attributes, elementPseudoClasses, psuedoElement, pseudoElementPseudoClasses);
} else {
// tslint:disable-next-line:prefer-unknown-to-any
ret = builders.compoundSelector(element, attributes, <any>elementPseudoClasses, psuedoElement, <any>pseudoElementPseudoClasses);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isScopeSelector(node)) {
let ret: ScopeSelector;
if (mapper.ScopeSelector) {
ret = mapper.ScopeSelector();
} else {
ret = builders.scopeSelector();
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isClassSelector(node)) {
let ret: ClassSelector;
if (mapper.ClassSelector) {
ret = mapper.ClassSelector(node.name);
} else {
ret = builders.classSelector(node.name);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isPseudoClassSelector(node)) {
let ret: PseudoClassSelector;
if (mapper.PseudoClassSelector) {
ret = mapper.PseudoClassSelector(node.name);
} else {
ret = builders.pseudoClassSelector(node.name);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isPseudoElementSelector(node)) {
let ret: PseudoElementSelector;
if (mapper.PseudoElementSelector) {
ret = mapper.PseudoElementSelector(node.name);
} else {
ret = builders.pseudoElementSelector(node.name);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isRule(node)) {
let selectors: Rule<isToDefinition>["selectors"] = [];
for (let sel of node.selectors) {
selectors.push(map(mapper, sel, fromType, toType));
}
let declarations: Rule<isToDefinition>["declarations"] = [];
for (let decl of node.declarations) {
declarations.push(map(mapper, decl, fromType, toType));
}
let ret: Rule<isToDefinition>;
if (mapper.Rule) {
ret = mapper.Rule(selectors, declarations);
} else {
ret = builders.rule(selectors, declarations);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isDeclaration(node)) {
let ret: Declaration;
if (mapper.Declaration) {
ret = mapper.Declaration(node.property, node.value);
} else {
ret = builders.declaration(node.property, node.value);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else if (typeguards.isGlobalDeclaration(node)) {
let selector = map(mapper, node.selector, fromType, toType);
let ret: GlobalDeclaration;
if (mapper.GlobalDeclaration) {
ret = mapper.GlobalDeclaration(selector);
} else {
ret = builders.globalDeclaration(selector);
}
// tslint:disable-next-line:prefer-unknown-to-any
return <any>ret;
} else {
throw new Error("internal error");
}
}
export function visit<isDefinition extends DefinitionAST | BlockAST>(visitor: Visitor<isDefinition>, node: Node<isDefinition>): void {
if (typeguards.isRoot(node)) {
if (visitor.Root) {
let result = visitor.Root(node);
if (result === false) return;
}
for (let child of node.children) {
visit(visitor, child);
}
} else if (typeguards.isBlockSyntaxVersion(node)) {
if (visitor.BlockSyntaxVersion) {
let result = visitor.BlockSyntaxVersion(node);
if (result === false) {
return;
}
}
} else if (typeguards.isBlockReference(node)) {
if (visitor.BlockReference) {
let result = visitor.BlockReference(node);
if (result === false) {
return;
}
}
} else if (typeguards.isBlockExport(node)) {
if (visitor.BlockExport) {
let result = visitor.BlockExport(node);
if (result === false) {
return;
}
}
} else if (typeguards.isLocalBlockExport(node)) {
if (visitor.LocalBlockExport) {
let result = visitor.LocalBlockExport(node);
if (result === false) {
return;
}
}
} else if (typeguards.isComplexSelector(node)) {
if (visitor.ComplexSelector) {
let result = visitor.ComplexSelector(node);
if (result === false) {
return;
}
}
for (let ctx of node.contextSelectors) {
visit(visitor, ctx.selector);
}
visit(visitor, node.keySelector);
} else if (typeguards.isForeignAttributeSelector(node)) {
if (visitor.ForeignAttributeSelector) {
let result = visitor.ForeignAttributeSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isAttributeSelector(node)) {
if (visitor.AttributeSelector) {
let result = visitor.AttributeSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isCompoundSelector(node)) {
if (visitor.CompoundSelector) {
let result = visitor.CompoundSelector(node);
if (result === false) {
return;
}
}
visit(visitor, node.element);
if (node.attributes) {
for (let attr of node.attributes) { visit(visitor, attr); }
}
if (node.elementPseudoClasses) {
for (let pseudoclass of <Array<PseudoClassSelector>>node.elementPseudoClasses) { visit(visitor, pseudoclass); }
}
if (node.pseudoElement) {
visit(visitor, node.pseudoElement);
}
if (node.pseudoElementPseudoClasses) {
for (let pseudoclass of <Array<PseudoClassSelector>>node.pseudoElementPseudoClasses) { visit(visitor, pseudoclass); }
}
} else if (typeguards.isScopeSelector(node)) {
if (visitor.ScopeSelector) {
let result = visitor.ScopeSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isClassSelector(node)) {
if (visitor.ClassSelector) {
let result = visitor.ClassSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isPseudoClassSelector(node)) {
if (visitor.PseudoClassSelector) {
let result = visitor.PseudoClassSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isPseudoElementSelector(node)) {
if (visitor.PseudoElementSelector) {
let result = visitor.PseudoElementSelector(node);
if (result === false) {
return;
}
}
} else if (typeguards.isRule(node)) {
if (visitor.Rule) {
let result = visitor.Rule(node);
if (result === false) {
return;
}
}
for (let sel of node.selectors) {
visit(visitor, sel);
}
for (let decl of node.declarations) {
visit(visitor, decl);
}
} else if (typeguards.isDeclaration(node)) {
if (visitor.Declaration) {
let result = visitor.Declaration(node);
if (result === false) {
return;
}
}
} else if (typeguards.isGlobalDeclaration(node)) {
if (visitor.GlobalDeclaration) {
let result = visitor.GlobalDeclaration(node);
if (result === false) {
return;
}
}
visit(visitor, node.selector);
} else {
assertNever(node);
}
} | the_stack |
import { ColumnSeries, IColumnSeriesPrivate, IColumnSeriesSettings, IColumnSeriesDataItem, IColumnSeriesAxisRange } from "./ColumnSeries";
import type { DataItem } from "../../../core/render/Component";
import { Candlestick } from "./Candlestick";
import { Template } from "../../../core/util/Template";
import { ListTemplate } from "../../../core/util/List";
import * as $utils from "../../../core/util/Utils";
import * as $array from "../../../core/util/Array";
export interface ICandlestickSeriesDataItem extends IColumnSeriesDataItem {
lowValueX?: number;
lowValueXWorking?: number;
lowValueXChange?: number;
lowValueXChangePercent?: number;
lowValueXChangeSelection?: number;
lowValueXChangeSelectionPercent?: number;
lowValueXChangePrevious?: number;
lowValueXChangePreviousPercent?: number;
lowValueXWorkingOpen?: number;
lowValueXWorkingClose?: number;
highValueY?: number;
highValueYWorking?: number;
highValueYChange?: number;
highValueYChangePercent?: number;
highValueYChangeSelection?: number;
highValueYChangeSelectionPercent?: number;
highValueYChangePrevious?: number;
highValueYChangePreviousPercent?: number;
highValueYWorkingOpen?: number;
highValueYWorkingClose?: number;
}
export interface ICandlestickSeriesSettings extends IColumnSeriesSettings {
/**
* Input data field for X low value.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/candlestick-series/} for more info
*/
lowValueXField?: string;
/**
* Input data field for Y low value.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/candlestick-series/} for more info
*/
lowValueYField?: string;
/**
* Input data field for X high value.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/candlestick-series/} for more info
*/
highValueXField?: string;
/**
* Input data field for Y high value.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/candlestick-series/} for more info
*/
highValueYField?: string;
/**
* Display data field for X low value.
*/
lowValueXShow?: "lowValueXWorking" | "lowValueXChange" | "lowValueXChangePercent" | "lowValueXChangeSelection" | "lowValueXChangeSelectionPercent" | "lowValueXChangePrevious" | "lowValueXChangePreviousPercent";
/**
* Display data field for Y low value.
*/
lowValueYShow?: "lowValueYWorking" | "lowValueYChange" | "lowValueYChangePercent" | "lowValueYChangeSelection" | "lowValueYChangeSelectionPercent" | "lowValueYChangePrevious" | "lowValueYChangePreviousPercent";
/**
* Indicates what aggregate value to use for collective data item, when
* aggregating X low values from several data items.
*/
lowValueXGrouped?: "open" | "close" | "low" | "high" | "average" | "sum" | "extreme";
/**
* Indicates what aggregate value to use for collective data item, when
* aggregating Y low values from several data items.
*/
lowValueYGrouped?: "open" | "close" | "low" | "high" | "average" | "sum" | "extreme";
/**
* Display data field for X high value.
*/
highValueXShow?: "highValueXWorking" | "highValueXChange" | "highValueXChangePercent" | "highValueXChangeSelection" | "highValueXChangeSelectionPercent" | "highValueXChangePrevious" | "highValueXChangePreviousPercent";
/**
* Display data field for Y low value.
*/
highValueYShow?: "highValueYWorking" | "highValueYChange" | "highValueYChangePercent" | "highValueYChangeSelection" | "highValueYChangeSelectionPercent" | "highValueYChangePrevious" | "highValueYChangePreviousPercent";
/**
* Indicates what aggregate value to use for collective data item, when
* aggregating X high values from several data items.
*/
highValueXGrouped?: "open" | "close" | "high" | "high" | "average" | "sum" | "extreme";
/**
* Indicates what aggregate value to use for collective data item, when
* aggregating X high values from several data items.
*/
highValueYGrouped?: "open" | "close" | "high" | "high" | "average" | "sum" | "extreme";
/**
* Horizontal location of the low data point relative to its cell.
*
* `0` - beginning, `0.5` - middle, `1` - end.
*
* @default 0.5
*/
lowLocationX?: number;
/**
* Vertical location of the low data point relative to its cell.
*
* `0` - beginning, `0.5` - middle, `1` - end.
*
* @default 0.5
*/
lowLocationY?: number;
/**
* Horizontal location of the high data point relative to its cell.
*
* `0` - beginning, `0.5` - middle, `1` - end.
*
* @default 0.5
*/
highLocationX?: number;
/**
* Vertical location of the high data point relative to its cell.
*
* `0` - beginning, `0.5` - middle, `1` - end.
*
* @default 0.5
*/
highLocationY?: number;
}
export interface ICandlestickSeriesPrivate extends IColumnSeriesPrivate {
lowValueXAverage?: number;
lowValueXCount?: number;
lowValueXSum?: number;
lowValueXAbsoluteSum?: number;
lowValueXLow?: number;
lowValueXHigh?: number;
lowValueXlow?: number;
lowValueXClose?: number;
lowValueYAverage?: number;
lowValueYCount?: number;
lowValueYSum?: number;
lowValueYAbsoluteSum?: number;
lowValueYLow?: number;
lowValueYHigh?: number;
lowValueYlow?: number;
lowValueYClose?: number;
lowValueXAverageSelection?: number;
lowValueXCountSelection?: number;
lowValueXSumSelection?: number;
lowValueXAbsoluteSumSelection?: number;
lowValueXLowSelection?: number;
lowValueXHighSelection?: number;
lowValueXlowSelection?: number;
lowValueXCloseSelection?: number;
lowValueYAverageSelection?: number;
lowValueYCountSelection?: number;
lowValueYSumSelection?: number;
lowValueYAbsoluteSumSelection?: number;
lowValueYLowSelection?: number;
lowValueYHighSelection?: number;
lowValueYlowSelection?: number;
lowValueYCloseSelection?: number;
highValueXAverage?: number;
highValueXCount?: number;
highValueXSum?: number;
highValueXAbsoluteSum?: number;
highValueXLow?: number;
highValueXHigh?: number;
highValueXhigh?: number;
highValueXClose?: number;
highValueYAverage?: number;
highValueYCount?: number;
highValueYSum?: number;
highValueYAbsoluteSum?: number;
highValueYLow?: number;
highValueYHigh?: number;
highValueYhigh?: number;
highValueYClose?: number;
highValueXAverageSelection?: number;
highValueXCountSelection?: number;
highValueXSumSelection?: number;
highValueXAbsoluteSumSelection?: number;
highValueXLowSelection?: number;
highValueXHighSelection?: number;
highValueXhighSelection?: number;
highValueXCloseSelection?: number;
highValueYAverageSelection?: number;
highValueYCountSelection?: number;
highValueYSumSelection?: number;
highValueYAbsoluteSumSelection?: number;
highValueYLowSelection?: number;
highValueYHighSelection?: number;
highValueYhighSelection?: number;
highValueYCloseSelection?: number;
}
export interface ICandlestickSeriesAxisRange extends IColumnSeriesAxisRange {
columns: ListTemplate<Candlestick>
}
/**
* Candlestick series.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/series/candlestick-series/} for more info
* @important
*/
export class CandlestickSeries extends ColumnSeries {
declare public _settings: ICandlestickSeriesSettings;
declare public _privateSettings: ICandlestickSeriesPrivate;
declare public _dataItemSettings: ICandlestickSeriesDataItem;
declare public _axisRangeType: ICandlestickSeriesAxisRange;
public static className: string = "CandlestickSeries";
public static classNames: Array<string> = ColumnSeries.classNames.concat([CandlestickSeries.className]);
protected _afterNew() {
this.valueFields.push("lowValueX", "lowValueY", "highValueX", "highValueY");
this.valueXFields.push("lowValueX", "highValueX");
this.valueYFields.push("lowValueY", "highValueY");
this._setRawDefault("lowValueXShow", "lowValueXWorking");
this._setRawDefault("lowValueYShow", "lowValueYWorking");
this._setRawDefault("highValueXShow", "highValueXWorking");
this._setRawDefault("highValueYShow", "highValueYWorking");
this._setRawDefault("lowValueXGrouped", "low");
this._setRawDefault("lowValueYGrouped", "low");
this._setRawDefault("highValueXGrouped", "high");
this._setRawDefault("highValueYGrouped", "high");
super._afterNew();
}
/**
* @ignore
*/
public makeColumn(dataItem: DataItem<this["_dataItemSettings"]>, listTemplate: ListTemplate<Candlestick>): Candlestick {
const column = this.mainContainer.children.push(listTemplate.make());
column._setDataItem(dataItem);
listTemplate.push(column);
return column;
}
/**
* A list of candles in the series.
*
* `columns.template` can be used to configure candles.
*
* @default new ListTemplate<Candlestick>
*/
public readonly columns: ListTemplate<Candlestick> = new ListTemplate(
Template.new({
themeTags: ["autocolor"]
}),
() => Candlestick._new(this._root, {
themeTags: $utils.mergeTags(this.columns.template.get("themeTags", []), ["candlestick", "series", "column"])
}, [this.columns.template])
);
protected _updateGraphics(dataItem: DataItem<this["_dataItemSettings"]>, previousDataItem: DataItem<this["_dataItemSettings"]>) {
super._updateGraphics(dataItem, previousDataItem);
const xAxis = this.getRaw("xAxis");
const yAxis = this.getRaw("yAxis");
const baseAxis = this.getRaw("baseAxis");
let vcy = this.get("vcy", 1);
let vcx = this.get("vcx", 1);
let lx0: number;
let lx1: number;
let ly0: number;
let ly1: number;
let hx0: number;
let hx1: number;
let hy0: number;
let hy1: number;
let locationX = this.get("locationX", dataItem.get("locationX", 0.5));
let locationY = this.get("locationY", dataItem.get("locationY", 0.5));
let openLocationX = this.get("openLocationX", dataItem.get("openLocationX", locationX));
let openLocationY = this.get("openLocationY", dataItem.get("openLocationY", locationY));
let orientation: "horizontal" | "vertical";
if (yAxis === baseAxis) {
let open = xAxis.getDataItemPositionX(dataItem, this._xOpenField, 1, vcx);
let close = xAxis.getDataItemPositionX(dataItem, this._xField, 1, vcx);
lx1 = xAxis.getDataItemPositionX(dataItem, this._xLowField, 1, vcx);
hx1 = xAxis.getDataItemPositionX(dataItem, this._xHighField, 1, vcx);
hx0 = Math.max(open, close);
lx0 = Math.min(open, close);
let startLocation = this._aLocationY0 + openLocationY - 0.5;
let endLocation = this._aLocationY1 + locationY - 0.5;
ly0 = yAxis.getDataItemPositionY(dataItem, this._yField, startLocation + (endLocation - startLocation) / 2, vcy);
ly1 = ly0;
hy0 = ly0;
hy1 = ly0;
orientation = "horizontal";
}
else {
let open = yAxis.getDataItemPositionY(dataItem, this._yOpenField, 1, vcy);
let close = yAxis.getDataItemPositionY(dataItem, this._yField, 1, vcy);
ly1 = yAxis.getDataItemPositionY(dataItem, this._yLowField, 1, vcy);
hy1 = yAxis.getDataItemPositionY(dataItem, this._yHighField, 1, vcy);
hy0 = Math.max(open, close);
ly0 = Math.min(open, close);
let startLocation = this._aLocationX0 + openLocationX - 0.5;
let endLocation = this._aLocationX1 + locationX - 0.5;
lx0 = xAxis.getDataItemPositionX(dataItem, this._xField, startLocation + (endLocation - startLocation) / 2, vcx);
lx1 = lx0;
hx0 = lx0;
hx1 = lx0;
orientation = "vertical";
}
this._updateCandleGraphics(dataItem, lx0, lx1, ly0, ly1, hx0, hx1, hy0, hy1, orientation)
}
protected _updateCandleGraphics(dataItem: DataItem<this["_dataItemSettings"]>, lx0: number, lx1: number, ly0: number, ly1: number, hx0: number, hx1: number, hy0: number, hy1: number, orientation: "horizontal" | "vertical") {
let column = dataItem.get("graphics") as Candlestick;
if (column) {
let pl0 = this.getPoint(lx0, ly0);
let pl1 = this.getPoint(lx1, ly1);
let ph0 = this.getPoint(hx0, hy0);
let ph1 = this.getPoint(hx1, hy1);
let x = column.x();
let y = column.y();
column.set("lowX0", pl0.x - x);
column.set("lowY0", pl0.y - y);
column.set("lowX1", pl1.x - x);
column.set("lowY1", pl1.y - y);
column.set("highX0", ph0.x - x);
column.set("highY0", ph0.y - y);
column.set("highX1", ph1.x - x);
column.set("highY1", ph1.y - y);
column.set("orientation", orientation);
let rangeGraphics = dataItem.get("rangeGraphics")!;
if (rangeGraphics) {
$array.each(rangeGraphics, (column: any) => {
column.set("lowX0", pl0.x - x);
column.set("lowY0", pl0.y - y);
column.set("lowX1", pl1.x - x);
column.set("lowY1", pl1.y - y);
column.set("highX0", ph0.x - x);
column.set("highY0", ph0.y - y);
column.set("highX1", ph1.x - x);
column.set("highY1", ph1.y - y);
column.set("orientation", orientation);
})
}
}
}
protected _processAxisRange(axisRange: this["_axisRangeType"]) {
super._processAxisRange(axisRange);
axisRange.columns = new ListTemplate(
Template.new({}),
() => Candlestick._new(this._root, {
themeTags: $utils.mergeTags(axisRange.columns.template.get("themeTags", []), ["candlestick", "series", "column"]),
}, [this.columns.template, axisRange.columns.template])
);
}
} | the_stack |
import { debugMode } from "../settings";
import { ASS } from "../types/ass";
import { Attachment, AttachmentType } from "../types/attachment";
import { Dialogue } from "../types/dialogue";
import { Style } from "../types/style";
import { Map } from "../utility/map";
import { DeferredPromise } from "../utility/promise";
import { parseLineIntoProperty } from "./misc";
import { Stream } from "./streams";
enum Section {
ScriptInfo,
Styles,
Events,
Fonts,
Graphics,
Other,
EOF,
}
/**
* A parser that parses an {@link libjass.ASS} object from a {@link libjass.parser.Stream}.
*
* @param {!libjass.parser.Stream} stream The {@link libjass.parser.Stream} to parse
*/
export class StreamParser {
private _ass: ASS = new ASS();
private _minimalDeferred: DeferredPromise<ASS> = new DeferredPromise<ASS>();
private _deferred: DeferredPromise<ASS> = new DeferredPromise<ASS>();
private _shouldSwallowBom: boolean = true;
private _currentSection: Section = Section.ScriptInfo;
private _currentAttachment: Attachment | null = null;
constructor(private _stream: Stream) {
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._minimalDeferred.reject(reason);
this._deferred.reject(reason);
});
}
/**
* @type {!Promise.<!libjass.ASS>} A promise that will be resolved when the script properties of the ASS script have been parsed from the stream. Styles and events have not necessarily been
* parsed at the point this promise becomes resolved.
*/
get minimalASS(): Promise<ASS> {
return this._minimalDeferred.promise;
}
/**
* @type {!Promise.<!libjass.ASS>} A promise that will be resolved when the entire stream has been parsed.
*/
get ass(): Promise<ASS> {
return this._deferred.promise;
}
/**
* @type {number}
*/
private get currentSection(): Section {
return this._currentSection;
}
/**
* @type {number}
*/
private set currentSection(value: Section) {
if (this._currentAttachment !== null) {
this._ass.addAttachment(this._currentAttachment);
this._currentAttachment = null;
}
if (this._currentSection === Section.ScriptInfo && value !== Section.ScriptInfo) {
// Exiting script info section
this._minimalDeferred.resolve(this._ass);
}
if (value === Section.EOF) {
const scriptProperties = this._ass.properties;
/* tslint:disable-next-line:strict-type-predicates */
if (scriptProperties.resolutionX === undefined || scriptProperties.resolutionY === undefined) {
// Malformed script.
this._minimalDeferred.reject("Malformed ASS script.");
this._deferred.reject("Malformed ASS script.");
}
else {
this._minimalDeferred.resolve(this._ass);
this._deferred.resolve(this._ass);
}
}
this._currentSection = value;
}
/**
* @param {string} line
*/
private _onNextLine(line: string | null): void {
if (line === null) {
this.currentSection = Section.EOF;
return;
}
if (line[line.length - 1] === "\r") {
line = line.substr(0, line.length - 1);
}
if (line.charCodeAt(0) === 0xfeff && this._shouldSwallowBom) {
line = line.substr(1);
}
this._shouldSwallowBom = false;
if (line === "") {
// Ignore empty lines.
}
else if (line[0] === ";" && this._currentAttachment === null) {
// Lines starting with ; are comments, unless reading an attachment.
}
else if (line === "[Script Info]") {
this.currentSection = Section.ScriptInfo;
}
else if (line === "[V4+ Styles]" || line === "[V4 Styles]") {
this.currentSection = Section.Styles;
}
else if (line === "[Events]") {
this.currentSection = Section.Events;
}
else if (line === "[Fonts]") {
this.currentSection = Section.Fonts;
}
else if (line === "[Graphics]") {
this.currentSection = Section.Graphics;
}
else {
if (this._currentAttachment === null && line[0] === "[" && line[line.length - 1] === "]") {
/* This looks like the start of a new section. The section name is unrecognized if it is.
* Since there's no current attachment being parsed it's definitely the start of a new section.
* If an attachment is being parsed, this might be part of the attachment.
*/
this.currentSection = Section.Other;
}
switch (this.currentSection) {
case Section.ScriptInfo:
const property = parseLineIntoProperty(line);
if (property !== null) {
switch (property.name) {
case "PlayResX":
this._ass.properties.resolutionX = parseInt(property.value);
break;
case "PlayResY":
this._ass.properties.resolutionY = parseInt(property.value);
break;
case "WrapStyle":
this._ass.properties.wrappingStyle = parseInt(property.value);
break;
case "ScaledBorderAndShadow":
this._ass.properties.scaleBorderAndShadow = (property.value === "yes");
break;
}
}
break;
case Section.Styles:
if (this._ass.stylesFormatSpecifier === null) {
const property = parseLineIntoProperty(line);
if (property !== null && property.name === "Format") {
this._ass.stylesFormatSpecifier = property.value.split(",").map(str => str.trim());
}
else {
// Ignore any non-format lines
}
}
else {
try {
this._ass.addStyle(line);
}
catch (ex) {
if (debugMode) {
console.error(`Could not parse style from line ${ line } - ${ ex.stack || ex }`);
}
}
}
break;
case Section.Events:
if (this._ass.dialoguesFormatSpecifier === null) {
const property = parseLineIntoProperty(line);
if (property !== null && property.name === "Format") {
this._ass.dialoguesFormatSpecifier = property.value.split(",").map(str => str.trim());
}
else {
// Ignore any non-format lines
}
}
else {
try {
this._ass.addEvent(line);
}
catch (ex) {
if (debugMode) {
console.error(`Could not parse event from line ${ line } - ${ ex.stack || ex }`);
}
}
}
break;
case Section.Fonts:
case Section.Graphics:
const startOfNewAttachmentRegex = (this.currentSection === Section.Fonts) ? /^fontname:(.+)/ : /^filename:(.+)/;
const startOfNewAttachment = startOfNewAttachmentRegex.exec(line);
if (startOfNewAttachment !== null) {
// Start of new attachment
if (this._currentAttachment !== null) {
this._ass.addAttachment(this._currentAttachment);
this._currentAttachment = null;
}
this._currentAttachment = new Attachment(startOfNewAttachment[1].trim(), (this.currentSection === Section.Fonts) ? AttachmentType.Font : AttachmentType.Graphic);
}
else if (this._currentAttachment !== null) {
try {
this._currentAttachment.contents += uuencodedToBase64(line);
}
catch (ex) {
if (debugMode) {
console.error(`Encountered error while reading font ${ this._currentAttachment.filename }: %o`, ex);
}
this._currentAttachment = null;
}
}
else {
// Ignore.
}
break;
case Section.Other:
// Ignore other sections.
break;
default:
throw new Error(`Unhandled state ${ this.currentSection }`);
}
}
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._minimalDeferred.reject(reason);
this._deferred.reject(reason);
});
}
}
/**
* A parser that parses an {@link libjass.ASS} object from a {@link libjass.parser.Stream} of an SRT script.
*
* @param {!libjass.parser.Stream} stream The {@link libjass.parser.Stream} to parse
*/
export class SrtStreamParser {
private _ass: ASS = new ASS();
private _deferred: DeferredPromise<ASS> = new DeferredPromise<ASS>();
private _shouldSwallowBom: boolean = true;
private _currentDialogueNumber: string | null = null;
private _currentDialogueStart: string | null = null;
private _currentDialogueEnd: string | null = null;
private _currentDialogueText: string | null = null;
constructor(private _stream: Stream) {
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._deferred.reject(reason);
});
this._ass.properties.resolutionX = 1280;
this._ass.properties.resolutionY = 720;
this._ass.properties.wrappingStyle = 1;
this._ass.properties.scaleBorderAndShadow = true;
const newStyle = new Style(new Map([["Name", "Default"], ["FontSize", "36"]]));
this._ass.styles.set(newStyle.name, newStyle);
}
/**
* @type {!Promise.<!libjass.ASS>} A promise that will be resolved when the entire stream has been parsed.
*/
get ass(): Promise<ASS> {
return this._deferred.promise;
}
/**
* @param {string} line
*/
private _onNextLine(line: string | null): void {
if (line === null) {
if (this._currentDialogueNumber !== null && this._currentDialogueStart !== null && this._currentDialogueEnd !== null && this._currentDialogueText !== null) {
this._ass.dialogues.push(new Dialogue(new Map([
["Style", "Default"],
["Start", this._currentDialogueStart],
["End", this._currentDialogueEnd],
["Text", this._currentDialogueText],
]), this._ass));
}
this._deferred.resolve(this._ass);
return;
}
if (line[line.length - 1] === "\r") {
line = line.substr(0, line.length - 1);
}
if (line.charCodeAt(0) === 0xfeff && this._shouldSwallowBom) {
line = line.substr(1);
}
this._shouldSwallowBom = false;
if (line === "") {
if (this._currentDialogueNumber !== null && this._currentDialogueStart !== null && this._currentDialogueEnd !== null && this._currentDialogueText !== null) {
this._ass.dialogues.push(new Dialogue(new Map([
["Style", "Default"],
["Start", this._currentDialogueStart],
["End", this._currentDialogueEnd],
["Text", this._currentDialogueText],
]), this._ass));
}
this._currentDialogueNumber = this._currentDialogueStart = this._currentDialogueEnd = this._currentDialogueText = null;
}
else {
if (this._currentDialogueNumber === null) {
if (/^\d+$/.test(line)) {
this._currentDialogueNumber = line;
}
}
else if (this._currentDialogueStart === null && this._currentDialogueEnd === null) {
const match = /^(\d\d:\d\d:\d\d,\d\d\d) --> (\d\d:\d\d:\d\d,\d\d\d)/.exec(line);
if (match !== null) {
this._currentDialogueStart = match[1].replace(",", ".");
this._currentDialogueEnd = match[2].replace(",", ".");
}
}
else {
line = line
.replace(/<b>/g, "{\\b1}").replace(/\{b\}/g, "{\\b1}")
.replace(/<\/b>/g, "{\\b0}").replace(/\{\/b\}/g, "{\\b0}")
.replace(/<i>/g, "{\\i1}").replace(/\{i\}/g, "{\\i1}")
.replace(/<\/i>/g, "{\\i0}").replace(/\{\/i\}/g, "{\\i0}")
.replace(/<u>/g, "{\\u1}").replace(/\{u\}/g, "{\\u1}")
.replace(/<\/u>/g, "{\\u0}").replace(/\{\/u\}/g, "{\\u0}")
.replace(
/<font color="#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})">/g,
(/* ujs:unreferenced */ _substring: string, red: string, green: string, blue: string) => `{\c&H${ blue }${ green }${ red }&}`,
).replace(/<\/font>/g, "{\\c}");
if (this._currentDialogueText !== null) {
this._currentDialogueText += "\\N" + line;
}
else {
this._currentDialogueText = line;
}
}
}
/* tslint:disable-next-line:no-floating-promises */
this._stream.nextLine().then(line => this._onNextLine(line), reason => {
this._deferred.reject(reason);
});
}
}
/**
* Converts a uuencoded string to a base64 string.
*
* @param {string} str
* @return {string}
*/
function uuencodedToBase64(str: string): string {
let result = "";
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i) - 33;
if (charCode < 0 || charCode > 63) {
throw new Error(`Out-of-range character code ${ charCode } at index ${ i } in string ${ str }`);
}
if (charCode < 26) {
result += String.fromCharCode("A".charCodeAt(0) + charCode);
}
else if (charCode < 52) {
result += String.fromCharCode("a".charCodeAt(0) + charCode - 26);
}
else if (charCode < 62) {
result += String.fromCharCode("0".charCodeAt(0) + charCode - 52);
}
else if (charCode === 62) {
result += "+";
}
else {
result += "/";
}
}
return result;
} | the_stack |
import {DataCategory,DataType} from "../column-delegate";
import * as _ from "underscore";
export class ColumnUtil {
/**
* Converts from the specified data type to a category.
*
* @param dataType - the data type
* @returns the data category
*/
public static fromDataType(dataType: string): DataCategory {
switch (dataType) {
case DataType.TINYINT:
case DataType.SMALLINT:
case DataType.INT:
case DataType.BIGINT:
case DataType.FLOAT:
case DataType.DOUBLE:
case DataType.DECIMAL:
return DataCategory.NUMERIC;
case DataType.TIMESTAMP:
case DataType.DATE:
return DataCategory.DATETIME;
case DataType.STRING:
case DataType.VARCHAR:
case DataType.CHAR:
return DataCategory.STRING;
case DataType.BOOLEAN:
return DataCategory.BOOLEAN;
case DataType.BINARY:
return DataCategory.BINARY;
case DataType.ARRAY_DOUBLE:
return DataCategory.ARRAY_DOUBLE;
}
// Deal with complex types
if (dataType.startsWith(DataType.ARRAY.toString())) {
return DataCategory.ARRAY;
} else if (dataType.startsWith(DataType.MAP.toString())) {
return DataCategory.MAP;
} else if (dataType.startsWith(DataType.STRUCT.toString())) {
return DataCategory.STRUCT;
} else if (dataType.startsWith(DataType.UNION.toString())) {
return DataCategory.UNION;
}
return DataCategory.OTHER;
}
/**
* Creates a formula that replaces the specified column with the specified script.
*
* @param {string} script the expression for the column
* @param {ui.grid.GridColumn} column the column to be replaced
* @param {ui.grid.Grid} grid the grid with the column
* @returns {string} a formula that replaces the column
*/
static toFormula(script: string, column: any, grid: any): string {
const columnFieldName = this.getColumnFieldName(column);
let formula = "";
const self = this;
_.each(grid.columns, (item:any) =>{
if (item.visible) {
const itemFieldName = ColumnUtil.getColumnFieldName(item);
formula += (formula.length == 0) ? "select(" : ", ";
formula += (itemFieldName === columnFieldName) ? script : itemFieldName;
}
});
formula += ")";
return formula;
}
/**
* Creates a formula for cleaning values as future fieldnames
* @returns {string} a formula for cleaning row values as fieldnames
*/
static createCleanFieldFormula(fieldName: string, tempField: string): string {
return `when(startsWith(regexp_replace(substring(${fieldName},0,1),"[0-9]","***"),"***"),concat("c_",lower(regexp_replace(${fieldName},"[^a-zA-Z0-9_]+","_")))).otherwise(lower(regexp_replace(${fieldName},"[^a-zA-Z0-9_]+","_"))).as("${tempField}")`;
}
/**
* Gets the SQL identifier for the specified column.
*/
static getColumnFieldName(column: any): string {
return column.field || column.name;
}
/**
* Gets the human-readable name of the specified column.
*/
static getColumnDisplayName(column: any): string {
return column.displayName;
}
static approxQuantileFormula(fieldName:string, bins:number) {
let binSize = 1 / bins;
let arr = []
for (let i = 1; i < bins; i++) {
arr.push(i * binSize)
}
return `select(approxQuantile("${fieldName}", [${arr}], 0.0).as("data"))`
}
/**
* Creates a formula that adds a new column with the specified script. It generates a unique column name.
*
* @param {string} script the expression for the column
* @param {ui.grid.GridColumn} column the column to be replaced
* @param {ui.grid.Grid} grid the grid with the column
* @returns {string} a formula that replaces the column
*/
static toAppendColumnFormula(script: string, column: any, grid: any, newField ?: string): string {
const self = this;
const columnFieldName = ColumnUtil.getColumnFieldName(column);
const uniqueName = (newField == null ? ColumnUtil.toUniqueColumnName(grid.columns, columnFieldName) : newField);
return ColumnUtil.createAppendColumnFormula(script, column, grid, uniqueName);
}
/**
* Creates a formula that adds a new column with the specified script.
*
* @param {string} script the expression for the column
* @param {ui.grid.GridColumn} column the column to be replaced
* @param {ui.grid.Grid} grid the grid with the column
* @returns {string} a formula that replaces the column
*/
static createAppendColumnFormula(script: string, column: any, grid: any, newField: string): string {
const self = this;
const columnFieldName = ColumnUtil.getColumnFieldName(column);
let formula = "";
_.each(grid.columns, (item:any, idx:number) => {
if (item.visible) {
const itemFieldName = ColumnUtil.getColumnFieldName(item);
formula += (formula.length == 0) ? "select(" : ", ";
formula += itemFieldName;
if (itemFieldName == columnFieldName) {
formula += "," + script + ColumnUtil.toAliasClause(newField);
}
}
});
formula += ")";
return formula;
}
/**
* Generates a script to move the column B directly to the right of column A
* @returns {string}
*/
static generateMoveScript(fieldNameA: string, fieldNameB: string | string[], columnSource: any, keepFieldNameA: boolean = true): string {
var self = this;
let cols: string[] = [];
let sourceColumns = (columnSource.columns ? columnSource.columns : columnSource);
_.each(sourceColumns, col => {
let colName: string = ColumnUtil.getColumnFieldName(col);
if (colName == fieldNameA) {
if (keepFieldNameA) cols.push(colName);
if (_.isArray(fieldNameB)) {
cols = cols.concat(fieldNameB);
}
else {
cols.push(fieldNameB);
}
} else if ((_.isArray(fieldNameB) && !_.contains(fieldNameB, colName)) || (_.isString(fieldNameB) && colName != fieldNameB)) {
cols.push(colName);
}
});
let selectCols = cols.join();
return `select(${selectCols})`;
}
/**
* Returns the as alias clause
* @param columns column list
* @returns {string} a unique fieldname
*/
static toAliasClause(name: string): string {
return ".as(\"" + name + "\")"
}
/**
* Creates a guaranteed unique field name
* @param columns column list
* @returns {string} a unique fieldname
*/
static toUniqueColumnName(columns: Array<any>, columnFieldName: any): string {
let prefix = "new_";
let idx = 0;
let columnSet = new Set();
let uniqueName = null;
const self = this;
columnSet.add(columnFieldName);
_.each(columns, (item:any)=> {
columnSet.add(ColumnUtil.getColumnFieldName(item));
});
while (uniqueName == null) {
let name = prefix + idx;
uniqueName = (columnSet.has(name) ? null : name);
idx++;
}
return uniqueName;
}
/**
* Guaranteed to return a unique column name that conforms to the field naming requirements
* @param {Array<string>} columns
* @param {string} columnFieldName
* @param {number} idx
* @returns {string}
*/
static uniqueName(columns: Array<string>, columnFieldName: string, idx: number = -1): string {
if (columns == null || columns.length == 0) {
return columnFieldName;
}
let alias = columnFieldName.replace(/^(_)|[^a-zA-Z0-9_]+/g, "");
if (idx >= 0) {
alias += "_"+idx;
}
if (columns.indexOf(alias.toLowerCase()) > -1) {
return ColumnUtil.uniqueName(columns, columnFieldName, idx+1);
}
return alias;
}
/**
* Parse a struct field into its top-level fields
* @param column
* @returns {string[]} list of fields
*/
static structToFields(column: any): string[] {
let fields: string = column.dataType;
fields = fields.substr(7, fields.length - 2);
let level = 0;
let cleaned = [];
for (let i = 0; i < fields.length; i++) {
switch (fields.charAt(i)) {
case '<':
level++;
break;
case '>':
level--;
break;
default:
if (level == 0) {
cleaned.push(fields.charAt(i));
}
}
}
let cleanedString = cleaned.join("");
let fieldArray: string[] = cleanedString.split(",");
return fieldArray.map((v: string) => {
return v.split(":")[0].toLowerCase();
});
}
/**
* Generates a script to use a temp column with the desired result and replace the existing column and ordering for
* which the temp column was derived. This is used by some of the machine
* learning functions that don't return column types
* @returns {string}
*/
static generateRenameScript(fieldName: string, tempField: string, grid: any): string {
// Build select script to drop temp column we generated
var self = this;
let cols: string[] = [];
_.each(grid.columns, col => {
let colName: string = self.getColumnFieldName(col);
if (colName != tempField) {
colName = (colName == fieldName ? `${tempField}.as("${fieldName}")` : colName);
cols.push(colName);
}
});
let selectCols = cols.join();
let renameScript = `select(${selectCols})`;
return renameScript;
}
/**
* Generates a temporary fieldname
* @returns {string} the fieldName
*/
static createTempField(): string {
return "c_" + (new Date()).getTime();
}
static toColumnArray(columns: any[], ommitColumn ?: string): string[] {
let cols: string[] = [];
_.each(columns, column => {
if (!ommitColumn || (ommitColumn && ommitColumn != column.name)) {
cols.push(ColumnUtil.getColumnFieldName(column));
}
});
return cols;
}
static escapeRegExp(text: string): string {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\\\$&');
}
/**
* If the character is reserved regex then the character is escaped
*/
static escapeRegexCharIfNeeded(chr:string):string {
if (chr == ' ') return "\\\\s";
return (chr.match(/[\[\^\$\.\|\?\*\+\(\)]/g) ? `\\\\${chr}` : chr);
}
/**
* Attempt to determine number of elements in array
* @param {string} text
* @returns {string}
*/
static arrayItems(text: string): number {
return (text && text.length > 0 ? text.split(",").length : 1);
}
} | the_stack |
import * as ts from 'typescript';
import {
isBlockLike,
isBreakOrContinueStatement,
isBreakStatement,
isCallExpression,
isClassLikeDeclaration,
isDecorator,
isExpressionStatement,
isParameterDeclaration,
isPropertyDeclaration,
isPropertySignature,
isTypePredicateNode,
isVariableDeclaration,
} from '../typeguard/node';
import {
isTypeFlagSet,
isNodeFlagSet,
isFunctionScopeBoundary,
ScopeBoundary,
isFunctionWithBody,
isThisParameter,
isSymbolFlagSet,
hasExhaustiveCaseClauses,
} from './util';
export function endsControlFlow(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): boolean {
return getControlFlowEnd(statement, checker).end;
}
export type ControlFlowStatement =
| ts.BreakStatement
| ts.ContinueStatement
| ts.ReturnStatement
| ts.ThrowStatement
| ts.ExpressionStatement & {expression: ts.CallExpression};
export interface ControlFlowEnd {
/**
* Statements that may end control flow at this statement.
* Does not contain control flow statements that jump only inside the statement, for example a `continue` inside a nested for loop.
*/
readonly statements: ReadonlyArray<ControlFlowStatement>;
/** `true` if control flow definitely ends. */
readonly end: boolean;
}
interface MutableControlFlowEnd {
statements: ControlFlowStatement[];
end: boolean;
}
const defaultControlFlowEnd: ControlFlowEnd = {statements: [], end: false};
export function getControlFlowEnd(statement: ts.Statement | ts.BlockLike, checker?: ts.TypeChecker): ControlFlowEnd {
return isBlockLike(statement) ? handleBlock(statement, checker) : getControlFlowEndWorker(statement, checker);
}
function getControlFlowEndWorker(statement: ts.Statement, checker?: ts.TypeChecker): ControlFlowEnd {
switch (statement.kind) {
case ts.SyntaxKind.ReturnStatement:
case ts.SyntaxKind.ThrowStatement:
case ts.SyntaxKind.ContinueStatement:
case ts.SyntaxKind.BreakStatement:
return {statements: [<ControlFlowStatement>statement], end: true};
case ts.SyntaxKind.Block:
return handleBlock(<ts.Block>statement, checker);
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.WhileStatement:
return handleForAndWhileStatement(<ts.ForStatement | ts.WhileStatement>statement, checker);
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.ForInStatement:
return handleForInOrOfStatement(<ts.ForInOrOfStatement>statement, checker);
case ts.SyntaxKind.DoStatement:
return matchBreakOrContinue(
getControlFlowEndWorker((<ts.DoStatement>statement).statement, checker),
isBreakOrContinueStatement,
);
case ts.SyntaxKind.IfStatement:
return handleIfStatement(<ts.IfStatement>statement, checker);
case ts.SyntaxKind.SwitchStatement:
return matchBreakOrContinue(handleSwitchStatement(<ts.SwitchStatement>statement, checker), isBreakStatement);
case ts.SyntaxKind.TryStatement:
return handleTryStatement(<ts.TryStatement>statement, checker);
case ts.SyntaxKind.LabeledStatement:
return matchLabel(
getControlFlowEndWorker((<ts.LabeledStatement>statement).statement, checker),
(<ts.LabeledStatement>statement).label,
);
case ts.SyntaxKind.WithStatement:
return getControlFlowEndWorker((<ts.WithStatement>statement).statement, checker);
case ts.SyntaxKind.ExpressionStatement:
if (checker === undefined)
return defaultControlFlowEnd;
return handleExpressionStatement(<ts.ExpressionStatement>statement, checker);
default:
return defaultControlFlowEnd;
}
}
function handleBlock(statement: ts.BlockLike, checker?: ts.TypeChecker): ControlFlowEnd {
const result: MutableControlFlowEnd = {statements: [], end: false};
for (const s of statement.statements) {
const current = getControlFlowEndWorker(s, checker);
result.statements.push(...current.statements);
if (current.end) {
result.end = true;
break;
}
}
return result;
}
function handleForInOrOfStatement(statement: ts.ForInOrOfStatement, checker?: ts.TypeChecker) {
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), isBreakOrContinueStatement);
end.end = false; // loop body is guaranteed to be executed
return end;
}
function handleForAndWhileStatement(statement: ts.ForStatement | ts.WhileStatement, checker?: ts.TypeChecker) {
const constantCondition = statement.kind === ts.SyntaxKind.WhileStatement
? getConstantCondition(statement.expression)
: statement.condition === undefined || getConstantCondition(statement.condition);
if (constantCondition === false)
return defaultControlFlowEnd; // loop body is never executed
const end = matchBreakOrContinue(getControlFlowEndWorker(statement.statement, checker), isBreakOrContinueStatement);
if (constantCondition === undefined)
end.end = false; // can't be sure that loop body is executed at all
return end;
}
/** Simply detects `true` and `false` in conditions. That matches TypeScript's behavior. */
function getConstantCondition(node: ts.Expression): boolean | undefined {
switch (node.kind) {
case ts.SyntaxKind.TrueKeyword:
return true;
case ts.SyntaxKind.FalseKeyword:
return false;
default:
return;
}
}
function handleIfStatement(node: ts.IfStatement, checker?: ts.TypeChecker): ControlFlowEnd {
switch (getConstantCondition(node.expression)) {
case true:
// else branch is never executed
return getControlFlowEndWorker(node.thenStatement, checker);
case false:
// then branch is never executed
return node.elseStatement === undefined
? defaultControlFlowEnd
: getControlFlowEndWorker(node.elseStatement, checker);
}
const then = getControlFlowEndWorker(node.thenStatement, checker);
if (node.elseStatement === undefined)
return {
statements: then.statements,
end: false,
};
const elze = getControlFlowEndWorker(node.elseStatement, checker);
return {
statements: [...then.statements, ...elze.statements],
end: then.end && elze.end,
};
}
function handleSwitchStatement(node: ts.SwitchStatement, checker?: ts.TypeChecker) {
let hasDefault = false;
const result: MutableControlFlowEnd = {
statements: [],
end: false,
};
for (const clause of node.caseBlock.clauses) {
if (clause.kind === ts.SyntaxKind.DefaultClause)
hasDefault = true;
const current = handleBlock(clause, checker);
result.end = current.end;
result.statements.push(...current.statements);
}
result.end &&= hasDefault || checker !== undefined && hasExhaustiveCaseClauses(node, checker);
return result;
}
function handleTryStatement(node: ts.TryStatement, checker?: ts.TypeChecker): ControlFlowEnd {
let finallyResult: ControlFlowEnd | undefined;
if (node.finallyBlock !== undefined) {
finallyResult = handleBlock(node.finallyBlock, checker);
// if 'finally' always ends control flow, we are not interested in any jump statements from 'try' or 'catch'
if (finallyResult.end)
return finallyResult;
}
const tryResult = handleBlock(node.tryBlock, checker);
if (node.catchClause === undefined)
return {statements: finallyResult!.statements.concat(tryResult.statements), end: tryResult.end};
const catchResult = handleBlock(node.catchClause.block, checker);
return {
statements: tryResult.statements
// remove all throw statements and throwing function calls from the list of control flow statements inside tryBlock
.filter((s) => s.kind !== ts.SyntaxKind.ThrowStatement && s.kind !== ts.SyntaxKind.ExpressionStatement)
.concat(catchResult.statements, finallyResult === undefined ? [] : finallyResult.statements),
end: tryResult.end && catchResult.end, // only ends control flow if try AND catch definitely end control flow
};
}
/** Dotted name as TypeScript requires it for assertion signatures to affect control flow. */
function isDottedNameWithExplicitTypeAnnotation(node: ts.Expression, checker: ts.TypeChecker) {
while (true) {
switch (node.kind) {
case ts.SyntaxKind.Identifier: {
const symbol = checker.getExportSymbolOfSymbol(checker.getSymbolAtLocation(node)!);
return isExplicitlyTypedSymbol(
isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : symbol,
checker,
);
}
case ts.SyntaxKind.ThisKeyword:
return isExplicitlyTypedThis(node);
case ts.SyntaxKind.SuperKeyword:
return true;
case ts.SyntaxKind.PropertyAccessExpression:
if (!isExplicitlyTypedSymbol(checker.getSymbolAtLocation(node), checker))
return false;
// falls through
case ts.SyntaxKind.ParenthesizedExpression:
node = (<ts.PropertyAccessExpression | ts.ParenthesizedExpression>node).expression;
continue;
default:
return false;
}
}
}
function isExplicitlyTypedSymbol(symbol: ts.Symbol | undefined, checker: ts.TypeChecker): boolean {
if (symbol === undefined)
return false;
if (isSymbolFlagSet(symbol, ts.SymbolFlags.Function | ts.SymbolFlags.Method | ts.SymbolFlags.Class | ts.SymbolFlags.ValueModule))
return true;
if (!isSymbolFlagSet(symbol, ts.SymbolFlags.Variable | ts.SymbolFlags.Property))
return false;
if (symbol.valueDeclaration === undefined)
return false;
if (declarationHasExplicitTypeAnnotation(symbol.valueDeclaration))
return true;
return isVariableDeclaration(symbol.valueDeclaration) &&
symbol.valueDeclaration.parent.parent.kind === ts.SyntaxKind.ForOfStatement &&
isDottedNameWithExplicitTypeAnnotation(symbol.valueDeclaration.parent.parent.expression, checker);
}
function declarationHasExplicitTypeAnnotation(node: ts.Declaration) {
if (ts.isJSDocPropertyLikeTag(node))
return node.typeExpression !== undefined;
return (
isVariableDeclaration(node) ||
isParameterDeclaration(node) ||
isPropertyDeclaration(node) ||
isPropertySignature(node)
) && (
isNodeFlagSet(node, ts.NodeFlags.JavaScriptFile)
? ts.getJSDocType(node)
: node.type
) !== undefined;
}
function isExplicitlyTypedThis(node: ts.Node): boolean {
do {
node = node.parent!;
if (isDecorator(node)) {
// `this` in decorators always resolves outside of the containing class
if (node.parent.kind === ts.SyntaxKind.Parameter && isClassLikeDeclaration(node.parent.parent.parent)) {
node = node.parent.parent.parent.parent;
} else if (isClassLikeDeclaration(node.parent.parent)) {
node = node.parent.parent.parent;
} else if (isClassLikeDeclaration(node.parent)) {
node = node.parent.parent;
}
}
} while (isFunctionScopeBoundary(node) !== ScopeBoundary.Function || node.kind === ts.SyntaxKind.ArrowFunction);
return isFunctionWithBody(node) &&
(
isNodeFlagSet(node, ts.NodeFlags.JavaScriptFile)
? ts.getJSDocThisTag(node)?.typeExpression !== undefined
: node.parameters.length !== 0 && isThisParameter(node.parameters[0]) && node.parameters[0].type !== undefined
) ||
isClassLikeDeclaration(node.parent!);
}
export const enum SignatureEffect {
Never = 1,
Asserts,
}
/**
* Dermines whether a top level CallExpression has a control flow effect according to TypeScript's rules.
* This handles functions returning `never` and `asserts`.
*/
export function callExpressionAffectsControlFlow(node: ts.CallExpression, checker: ts.TypeChecker): SignatureEffect | undefined {
if (
!isExpressionStatement(node.parent!) ||
ts.isOptionalChain(node) ||
!isDottedNameWithExplicitTypeAnnotation(node.expression, checker)
)
return;
const signature = checker.getResolvedSignature(node);
if (signature?.declaration === undefined)
return;
const typeNode = ts.isJSDocSignature(signature.declaration)
? signature.declaration.type?.typeExpression?.type
: signature.declaration.type ?? (
isNodeFlagSet(signature.declaration, ts.NodeFlags.JavaScriptFile)
? ts.getJSDocReturnType(signature.declaration)
: undefined
);
if (typeNode === undefined)
return;
if (isTypePredicateNode(typeNode) && typeNode.assertsModifier !== undefined)
return SignatureEffect.Asserts;
return isTypeFlagSet(checker.getTypeFromTypeNode(typeNode), ts.TypeFlags.Never) ? SignatureEffect.Never : undefined;
}
function handleExpressionStatement(node: ts.ExpressionStatement, checker: ts.TypeChecker): ControlFlowEnd {
if (!isCallExpression(node.expression))
return defaultControlFlowEnd;
switch (callExpressionAffectsControlFlow(node.expression, checker)) {
case SignatureEffect.Asserts:
return {statements: [<any>node], end: false};
case SignatureEffect.Never:
return {statements: [<any>node], end: true};
case undefined:
return defaultControlFlowEnd;
}
}
function matchBreakOrContinue(current: ControlFlowEnd, pred: typeof isBreakOrContinueStatement) {
const result: MutableControlFlowEnd = {
statements: [],
end: current.end,
};
for (const statement of current.statements) {
if (pred(statement) && statement.label === undefined) {
result.end = false;
continue;
}
result.statements.push(statement);
}
return result;
}
function matchLabel(current: ControlFlowEnd, label: ts.Identifier) {
const result: MutableControlFlowEnd = {
statements: [],
end: current.end,
};
const labelText = label.text;
for (const statement of current.statements) {
switch (statement.kind) {
case ts.SyntaxKind.BreakStatement:
case ts.SyntaxKind.ContinueStatement:
if (statement.label !== undefined && statement.label.text === labelText) {
result.end = false;
continue;
}
}
result.statements.push(statement);
}
return result;
} | the_stack |
import { ATN } from "antlr4ts/atn/ATN";
import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer";
import { FailedPredicateException } from "antlr4ts/FailedPredicateException";
import { NotNull } from "antlr4ts/Decorators";
import { NoViableAltException } from "antlr4ts/NoViableAltException";
import { Override } from "antlr4ts/Decorators";
import { Parser } from "antlr4ts/Parser";
import { ParserRuleContext } from "antlr4ts/ParserRuleContext";
import { ParserATNSimulator } from "antlr4ts/atn/ParserATNSimulator";
import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener";
import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor";
import { RecognitionException } from "antlr4ts/RecognitionException";
import { RuleContext } from "antlr4ts/RuleContext";
//import { RuleVersion } from "antlr4ts/RuleVersion";
import { TerminalNode } from "antlr4ts/tree/TerminalNode";
import { Token } from "antlr4ts/Token";
import { TokenStream } from "antlr4ts/TokenStream";
import { Vocabulary } from "antlr4ts/Vocabulary";
import { VocabularyImpl } from "antlr4ts/VocabularyImpl";
import * as Utils from "antlr4ts/misc/Utils";
import { CashScriptListener } from "./CashScriptListener";
import { CashScriptVisitor } from "./CashScriptVisitor";
export class CashScriptParser extends Parser {
public static readonly T__0 = 1;
public static readonly T__1 = 2;
public static readonly T__2 = 3;
public static readonly T__3 = 4;
public static readonly T__4 = 5;
public static readonly T__5 = 6;
public static readonly T__6 = 7;
public static readonly T__7 = 8;
public static readonly T__8 = 9;
public static readonly T__9 = 10;
public static readonly T__10 = 11;
public static readonly T__11 = 12;
public static readonly T__12 = 13;
public static readonly T__13 = 14;
public static readonly T__14 = 15;
public static readonly T__15 = 16;
public static readonly T__16 = 17;
public static readonly T__17 = 18;
public static readonly T__18 = 19;
public static readonly T__19 = 20;
public static readonly T__20 = 21;
public static readonly T__21 = 22;
public static readonly T__22 = 23;
public static readonly T__23 = 24;
public static readonly T__24 = 25;
public static readonly T__25 = 26;
public static readonly T__26 = 27;
public static readonly T__27 = 28;
public static readonly T__28 = 29;
public static readonly T__29 = 30;
public static readonly T__30 = 31;
public static readonly T__31 = 32;
public static readonly T__32 = 33;
public static readonly T__33 = 34;
public static readonly T__34 = 35;
public static readonly T__35 = 36;
public static readonly T__36 = 37;
public static readonly T__37 = 38;
public static readonly T__38 = 39;
public static readonly T__39 = 40;
public static readonly T__40 = 41;
public static readonly T__41 = 42;
public static readonly T__42 = 43;
public static readonly VersionLiteral = 44;
public static readonly BooleanLiteral = 45;
public static readonly NumberUnit = 46;
public static readonly NumberLiteral = 47;
public static readonly Bytes = 48;
public static readonly Bound = 49;
public static readonly StringLiteral = 50;
public static readonly DateLiteral = 51;
public static readonly HexLiteral = 52;
public static readonly TxVar = 53;
public static readonly PreimageField = 54;
public static readonly Identifier = 55;
public static readonly WHITESPACE = 56;
public static readonly COMMENT = 57;
public static readonly LINE_COMMENT = 58;
public static readonly RULE_sourceFile = 0;
public static readonly RULE_pragmaDirective = 1;
public static readonly RULE_pragmaName = 2;
public static readonly RULE_pragmaValue = 3;
public static readonly RULE_versionConstraint = 4;
public static readonly RULE_versionOperator = 5;
public static readonly RULE_contractDefinition = 6;
public static readonly RULE_functionDefinition = 7;
public static readonly RULE_parameterList = 8;
public static readonly RULE_parameter = 9;
public static readonly RULE_block = 10;
public static readonly RULE_statement = 11;
public static readonly RULE_variableDefinition = 12;
public static readonly RULE_tupleAssignment = 13;
public static readonly RULE_assignStatement = 14;
public static readonly RULE_timeOpStatement = 15;
public static readonly RULE_requireStatement = 16;
public static readonly RULE_ifStatement = 17;
public static readonly RULE_functionCall = 18;
public static readonly RULE_expressionList = 19;
public static readonly RULE_expression = 20;
public static readonly RULE_literal = 21;
public static readonly RULE_numberLiteral = 22;
public static readonly RULE_typeName = 23;
// tslint:disable:no-trailing-whitespace
public static readonly ruleNames: string[] = [
"sourceFile", "pragmaDirective", "pragmaName", "pragmaValue", "versionConstraint",
"versionOperator", "contractDefinition", "functionDefinition", "parameterList",
"parameter", "block", "statement", "variableDefinition", "tupleAssignment",
"assignStatement", "timeOpStatement", "requireStatement", "ifStatement",
"functionCall", "expressionList", "expression", "literal", "numberLiteral",
"typeName",
];
private static readonly _LITERAL_NAMES: Array<string | undefined> = [
undefined, "'pragma'", "';'", "'cashscript'", "'^'", "'~'", "'>='", "'>'",
"'<'", "'<='", "'='", "'contract'", "'{'", "'}'", "'function'", "'('",
"','", "')'", "'require'", "'if'", "'else'", "'new'", "'['", "']'", "'.reverse()'",
"'.length'", "'!'", "'-'", "'.split'", "'/'", "'%'", "'+'", "'=='", "'!='",
"'&'", "'|'", "'&&'", "'||'", "'int'", "'bool'", "'string'", "'pubkey'",
"'sig'", "'datasig'",
];
private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, "VersionLiteral", "BooleanLiteral", "NumberUnit",
"NumberLiteral", "Bytes", "Bound", "StringLiteral", "DateLiteral", "HexLiteral",
"TxVar", "PreimageField", "Identifier", "WHITESPACE", "COMMENT", "LINE_COMMENT",
];
public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(CashScriptParser._LITERAL_NAMES, CashScriptParser._SYMBOLIC_NAMES, []);
// @Override
// @NotNull
public get vocabulary(): Vocabulary {
return CashScriptParser.VOCABULARY;
}
// tslint:enable:no-trailing-whitespace
// @Override
public get grammarFileName(): string { return "CashScript.g4"; }
// @Override
public get ruleNames(): string[] { return CashScriptParser.ruleNames; }
// @Override
public get serializedATN(): string { return CashScriptParser._serializedATN; }
protected createFailedPredicateException(predicate?: string, message?: string): FailedPredicateException {
return new FailedPredicateException(this, predicate, message);
}
constructor(input: TokenStream) {
super(input);
this._interp = new ParserATNSimulator(CashScriptParser._ATN, this);
}
// @RuleVersion(0)
public sourceFile(): SourceFileContext {
let _localctx: SourceFileContext = new SourceFileContext(this._ctx, this.state);
this.enterRule(_localctx, 0, CashScriptParser.RULE_sourceFile);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 51;
this._errHandler.sync(this);
_la = this._input.LA(1);
while (_la === CashScriptParser.T__0) {
{
{
this.state = 48;
this.pragmaDirective();
}
}
this.state = 53;
this._errHandler.sync(this);
_la = this._input.LA(1);
}
this.state = 54;
this.contractDefinition();
this.state = 55;
this.match(CashScriptParser.EOF);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public pragmaDirective(): PragmaDirectiveContext {
let _localctx: PragmaDirectiveContext = new PragmaDirectiveContext(this._ctx, this.state);
this.enterRule(_localctx, 2, CashScriptParser.RULE_pragmaDirective);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 57;
this.match(CashScriptParser.T__0);
this.state = 58;
this.pragmaName();
this.state = 59;
this.pragmaValue();
this.state = 60;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public pragmaName(): PragmaNameContext {
let _localctx: PragmaNameContext = new PragmaNameContext(this._ctx, this.state);
this.enterRule(_localctx, 4, CashScriptParser.RULE_pragmaName);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 62;
this.match(CashScriptParser.T__2);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public pragmaValue(): PragmaValueContext {
let _localctx: PragmaValueContext = new PragmaValueContext(this._ctx, this.state);
this.enterRule(_localctx, 6, CashScriptParser.RULE_pragmaValue);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 64;
this.versionConstraint();
this.state = 66;
this._errHandler.sync(this);
_la = this._input.LA(1);
if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__3) | (1 << CashScriptParser.T__4) | (1 << CashScriptParser.T__5) | (1 << CashScriptParser.T__6) | (1 << CashScriptParser.T__7) | (1 << CashScriptParser.T__8) | (1 << CashScriptParser.T__9))) !== 0) || _la === CashScriptParser.VersionLiteral) {
{
this.state = 65;
this.versionConstraint();
}
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public versionConstraint(): VersionConstraintContext {
let _localctx: VersionConstraintContext = new VersionConstraintContext(this._ctx, this.state);
this.enterRule(_localctx, 8, CashScriptParser.RULE_versionConstraint);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 69;
this._errHandler.sync(this);
_la = this._input.LA(1);
if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__3) | (1 << CashScriptParser.T__4) | (1 << CashScriptParser.T__5) | (1 << CashScriptParser.T__6) | (1 << CashScriptParser.T__7) | (1 << CashScriptParser.T__8) | (1 << CashScriptParser.T__9))) !== 0)) {
{
this.state = 68;
this.versionOperator();
}
}
this.state = 71;
this.match(CashScriptParser.VersionLiteral);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public versionOperator(): VersionOperatorContext {
let _localctx: VersionOperatorContext = new VersionOperatorContext(this._ctx, this.state);
this.enterRule(_localctx, 10, CashScriptParser.RULE_versionOperator);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 73;
_la = this._input.LA(1);
if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__3) | (1 << CashScriptParser.T__4) | (1 << CashScriptParser.T__5) | (1 << CashScriptParser.T__6) | (1 << CashScriptParser.T__7) | (1 << CashScriptParser.T__8) | (1 << CashScriptParser.T__9))) !== 0))) {
this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public contractDefinition(): ContractDefinitionContext {
let _localctx: ContractDefinitionContext = new ContractDefinitionContext(this._ctx, this.state);
this.enterRule(_localctx, 12, CashScriptParser.RULE_contractDefinition);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 75;
this.match(CashScriptParser.T__10);
this.state = 76;
this.match(CashScriptParser.Identifier);
this.state = 77;
this.parameterList();
this.state = 78;
this.match(CashScriptParser.T__11);
this.state = 82;
this._errHandler.sync(this);
_la = this._input.LA(1);
while (_la === CashScriptParser.T__13) {
{
{
this.state = 79;
this.functionDefinition();
}
}
this.state = 84;
this._errHandler.sync(this);
_la = this._input.LA(1);
}
this.state = 85;
this.match(CashScriptParser.T__12);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public functionDefinition(): FunctionDefinitionContext {
let _localctx: FunctionDefinitionContext = new FunctionDefinitionContext(this._ctx, this.state);
this.enterRule(_localctx, 14, CashScriptParser.RULE_functionDefinition);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 87;
this.match(CashScriptParser.T__13);
this.state = 88;
this.match(CashScriptParser.Identifier);
this.state = 89;
this.parameterList();
this.state = 90;
this.match(CashScriptParser.T__11);
this.state = 94;
this._errHandler.sync(this);
_la = this._input.LA(1);
while (_la === CashScriptParser.T__17 || _la === CashScriptParser.T__18 || ((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.Bytes - 38)) | (1 << (CashScriptParser.Identifier - 38)))) !== 0)) {
{
{
this.state = 91;
this.statement();
}
}
this.state = 96;
this._errHandler.sync(this);
_la = this._input.LA(1);
}
this.state = 97;
this.match(CashScriptParser.T__12);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public parameterList(): ParameterListContext {
let _localctx: ParameterListContext = new ParameterListContext(this._ctx, this.state);
this.enterRule(_localctx, 16, CashScriptParser.RULE_parameterList);
let _la: number;
try {
let _alt: number;
this.enterOuterAlt(_localctx, 1);
{
this.state = 99;
this.match(CashScriptParser.T__14);
this.state = 111;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.Bytes - 38)))) !== 0)) {
{
this.state = 100;
this.parameter();
this.state = 105;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 5, this._ctx);
while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) {
if (_alt === 1) {
{
{
this.state = 101;
this.match(CashScriptParser.T__15);
this.state = 102;
this.parameter();
}
}
}
this.state = 107;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 5, this._ctx);
}
this.state = 109;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === CashScriptParser.T__15) {
{
this.state = 108;
this.match(CashScriptParser.T__15);
}
}
}
}
this.state = 113;
this.match(CashScriptParser.T__16);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public parameter(): ParameterContext {
let _localctx: ParameterContext = new ParameterContext(this._ctx, this.state);
this.enterRule(_localctx, 18, CashScriptParser.RULE_parameter);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 115;
this.typeName();
this.state = 116;
this.match(CashScriptParser.Identifier);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public block(): BlockContext {
let _localctx: BlockContext = new BlockContext(this._ctx, this.state);
this.enterRule(_localctx, 20, CashScriptParser.RULE_block);
let _la: number;
try {
this.state = 127;
this._errHandler.sync(this);
switch (this._input.LA(1)) {
case CashScriptParser.T__11:
this.enterOuterAlt(_localctx, 1);
{
this.state = 118;
this.match(CashScriptParser.T__11);
this.state = 122;
this._errHandler.sync(this);
_la = this._input.LA(1);
while (_la === CashScriptParser.T__17 || _la === CashScriptParser.T__18 || ((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.Bytes - 38)) | (1 << (CashScriptParser.Identifier - 38)))) !== 0)) {
{
{
this.state = 119;
this.statement();
}
}
this.state = 124;
this._errHandler.sync(this);
_la = this._input.LA(1);
}
this.state = 125;
this.match(CashScriptParser.T__12);
}
break;
case CashScriptParser.T__17:
case CashScriptParser.T__18:
case CashScriptParser.T__37:
case CashScriptParser.T__38:
case CashScriptParser.T__39:
case CashScriptParser.T__40:
case CashScriptParser.T__41:
case CashScriptParser.T__42:
case CashScriptParser.Bytes:
case CashScriptParser.Identifier:
this.enterOuterAlt(_localctx, 2);
{
this.state = 126;
this.statement();
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public statement(): StatementContext {
let _localctx: StatementContext = new StatementContext(this._ctx, this.state);
this.enterRule(_localctx, 22, CashScriptParser.RULE_statement);
try {
this.state = 135;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 10, this._ctx) ) {
case 1:
this.enterOuterAlt(_localctx, 1);
{
this.state = 129;
this.variableDefinition();
}
break;
case 2:
this.enterOuterAlt(_localctx, 2);
{
this.state = 130;
this.tupleAssignment();
}
break;
case 3:
this.enterOuterAlt(_localctx, 3);
{
this.state = 131;
this.assignStatement();
}
break;
case 4:
this.enterOuterAlt(_localctx, 4);
{
this.state = 132;
this.timeOpStatement();
}
break;
case 5:
this.enterOuterAlt(_localctx, 5);
{
this.state = 133;
this.requireStatement();
}
break;
case 6:
this.enterOuterAlt(_localctx, 6);
{
this.state = 134;
this.ifStatement();
}
break;
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public variableDefinition(): VariableDefinitionContext {
let _localctx: VariableDefinitionContext = new VariableDefinitionContext(this._ctx, this.state);
this.enterRule(_localctx, 24, CashScriptParser.RULE_variableDefinition);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 137;
this.typeName();
this.state = 138;
this.match(CashScriptParser.Identifier);
this.state = 139;
this.match(CashScriptParser.T__9);
this.state = 140;
this.expression(0);
this.state = 141;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public tupleAssignment(): TupleAssignmentContext {
let _localctx: TupleAssignmentContext = new TupleAssignmentContext(this._ctx, this.state);
this.enterRule(_localctx, 26, CashScriptParser.RULE_tupleAssignment);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 143;
this.typeName();
this.state = 144;
this.match(CashScriptParser.Identifier);
this.state = 145;
this.match(CashScriptParser.T__15);
this.state = 146;
this.typeName();
this.state = 147;
this.match(CashScriptParser.Identifier);
this.state = 148;
this.match(CashScriptParser.T__9);
this.state = 149;
this.expression(0);
this.state = 150;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public assignStatement(): AssignStatementContext {
let _localctx: AssignStatementContext = new AssignStatementContext(this._ctx, this.state);
this.enterRule(_localctx, 28, CashScriptParser.RULE_assignStatement);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 152;
this.match(CashScriptParser.Identifier);
this.state = 153;
this.match(CashScriptParser.T__9);
this.state = 154;
this.expression(0);
this.state = 155;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public timeOpStatement(): TimeOpStatementContext {
let _localctx: TimeOpStatementContext = new TimeOpStatementContext(this._ctx, this.state);
this.enterRule(_localctx, 30, CashScriptParser.RULE_timeOpStatement);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 157;
this.match(CashScriptParser.T__17);
this.state = 158;
this.match(CashScriptParser.T__14);
this.state = 159;
this.match(CashScriptParser.TxVar);
this.state = 160;
this.match(CashScriptParser.T__5);
this.state = 161;
this.expression(0);
this.state = 162;
this.match(CashScriptParser.T__16);
this.state = 163;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public requireStatement(): RequireStatementContext {
let _localctx: RequireStatementContext = new RequireStatementContext(this._ctx, this.state);
this.enterRule(_localctx, 32, CashScriptParser.RULE_requireStatement);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 165;
this.match(CashScriptParser.T__17);
this.state = 166;
this.match(CashScriptParser.T__14);
this.state = 167;
this.expression(0);
this.state = 168;
this.match(CashScriptParser.T__16);
this.state = 169;
this.match(CashScriptParser.T__1);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public ifStatement(): IfStatementContext {
let _localctx: IfStatementContext = new IfStatementContext(this._ctx, this.state);
this.enterRule(_localctx, 34, CashScriptParser.RULE_ifStatement);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 171;
this.match(CashScriptParser.T__18);
this.state = 172;
this.match(CashScriptParser.T__14);
this.state = 173;
this.expression(0);
this.state = 174;
this.match(CashScriptParser.T__16);
this.state = 175;
_localctx._ifBlock = this.block();
this.state = 178;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 11, this._ctx) ) {
case 1:
{
this.state = 176;
this.match(CashScriptParser.T__19);
this.state = 177;
_localctx._elseBlock = this.block();
}
break;
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public functionCall(): FunctionCallContext {
let _localctx: FunctionCallContext = new FunctionCallContext(this._ctx, this.state);
this.enterRule(_localctx, 36, CashScriptParser.RULE_functionCall);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 180;
this.match(CashScriptParser.Identifier);
this.state = 181;
this.expressionList();
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public expressionList(): ExpressionListContext {
let _localctx: ExpressionListContext = new ExpressionListContext(this._ctx, this.state);
this.enterRule(_localctx, 38, CashScriptParser.RULE_expressionList);
let _la: number;
try {
let _alt: number;
this.enterOuterAlt(_localctx, 1);
{
this.state = 183;
this.match(CashScriptParser.T__14);
this.state = 195;
this._errHandler.sync(this);
_la = this._input.LA(1);
if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__14) | (1 << CashScriptParser.T__20) | (1 << CashScriptParser.T__21) | (1 << CashScriptParser.T__25) | (1 << CashScriptParser.T__26))) !== 0) || ((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.BooleanLiteral - 38)) | (1 << (CashScriptParser.NumberLiteral - 38)) | (1 << (CashScriptParser.Bytes - 38)) | (1 << (CashScriptParser.StringLiteral - 38)) | (1 << (CashScriptParser.DateLiteral - 38)) | (1 << (CashScriptParser.HexLiteral - 38)) | (1 << (CashScriptParser.PreimageField - 38)) | (1 << (CashScriptParser.Identifier - 38)))) !== 0)) {
{
this.state = 184;
this.expression(0);
this.state = 189;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx);
while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) {
if (_alt === 1) {
{
{
this.state = 185;
this.match(CashScriptParser.T__15);
this.state = 186;
this.expression(0);
}
}
}
this.state = 191;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx);
}
this.state = 193;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === CashScriptParser.T__15) {
{
this.state = 192;
this.match(CashScriptParser.T__15);
}
}
}
}
this.state = 197;
this.match(CashScriptParser.T__16);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
public expression(): ExpressionContext;
public expression(_p: number): ExpressionContext;
// @RuleVersion(0)
public expression(_p?: number): ExpressionContext {
if (_p === undefined) {
_p = 0;
}
let _parentctx: ParserRuleContext = this._ctx;
let _parentState: number = this.state;
let _localctx: ExpressionContext = new ExpressionContext(this._ctx, _parentState);
let _prevctx: ExpressionContext = _localctx;
let _startState: number = 40;
this.enterRecursionRule(_localctx, 40, CashScriptParser.RULE_expression, _p);
let _la: number;
try {
let _alt: number;
this.enterOuterAlt(_localctx, 1);
{
this.state = 240;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 20, this._ctx) ) {
case 1:
{
_localctx = new ParenthesisedContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 200;
this.match(CashScriptParser.T__14);
this.state = 201;
this.expression(0);
this.state = 202;
this.match(CashScriptParser.T__16);
}
break;
case 2:
{
_localctx = new CastContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 204;
this.typeName();
this.state = 205;
this.match(CashScriptParser.T__14);
this.state = 206;
(_localctx as CastContext)._castable = this.expression(0);
this.state = 209;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 15, this._ctx) ) {
case 1:
{
this.state = 207;
this.match(CashScriptParser.T__15);
this.state = 208;
(_localctx as CastContext)._size = this.expression(0);
}
break;
}
this.state = 212;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === CashScriptParser.T__15) {
{
this.state = 211;
this.match(CashScriptParser.T__15);
}
}
this.state = 214;
this.match(CashScriptParser.T__16);
}
break;
case 3:
{
_localctx = new FunctionCallExpressionContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 216;
this.functionCall();
}
break;
case 4:
{
_localctx = new InstantiationContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 217;
this.match(CashScriptParser.T__20);
this.state = 218;
this.match(CashScriptParser.Identifier);
this.state = 219;
this.expressionList();
}
break;
case 5:
{
_localctx = new UnaryOpContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 220;
(_localctx as UnaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!(_la === CashScriptParser.T__25 || _la === CashScriptParser.T__26)) {
(_localctx as UnaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
this.state = 221;
this.expression(15);
}
break;
case 6:
{
_localctx = new ArrayContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 222;
this.match(CashScriptParser.T__21);
this.state = 234;
this._errHandler.sync(this);
_la = this._input.LA(1);
if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__14) | (1 << CashScriptParser.T__20) | (1 << CashScriptParser.T__21) | (1 << CashScriptParser.T__25) | (1 << CashScriptParser.T__26))) !== 0) || ((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.BooleanLiteral - 38)) | (1 << (CashScriptParser.NumberLiteral - 38)) | (1 << (CashScriptParser.Bytes - 38)) | (1 << (CashScriptParser.StringLiteral - 38)) | (1 << (CashScriptParser.DateLiteral - 38)) | (1 << (CashScriptParser.HexLiteral - 38)) | (1 << (CashScriptParser.PreimageField - 38)) | (1 << (CashScriptParser.Identifier - 38)))) !== 0)) {
{
this.state = 223;
this.expression(0);
this.state = 228;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 17, this._ctx);
while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) {
if (_alt === 1) {
{
{
this.state = 224;
this.match(CashScriptParser.T__15);
this.state = 225;
this.expression(0);
}
}
}
this.state = 230;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 17, this._ctx);
}
this.state = 232;
this._errHandler.sync(this);
_la = this._input.LA(1);
if (_la === CashScriptParser.T__15) {
{
this.state = 231;
this.match(CashScriptParser.T__15);
}
}
}
}
this.state = 236;
this.match(CashScriptParser.T__22);
}
break;
case 7:
{
_localctx = new PreimageFieldContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 237;
this.match(CashScriptParser.PreimageField);
}
break;
case 8:
{
_localctx = new IdentifierContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 238;
this.match(CashScriptParser.Identifier);
}
break;
case 9:
{
_localctx = new LiteralExpressionContext(_localctx);
this._ctx = _localctx;
_prevctx = _localctx;
this.state = 239;
this.literal();
}
break;
}
this._ctx._stop = this._input.tryLT(-1);
this.state = 283;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 22, this._ctx);
while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) {
if (_alt === 1) {
if (this._parseListeners != null) {
this.triggerExitRuleEvent();
}
_prevctx = _localctx;
{
this.state = 281;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 21, this._ctx) ) {
case 1:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 242;
if (!(this.precpred(this._ctx, 13))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 13)");
}
this.state = 243;
(_localctx as BinaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!(_la === CashScriptParser.T__28 || _la === CashScriptParser.T__29)) {
(_localctx as BinaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
this.state = 244;
(_localctx as BinaryOpContext)._right = this.expression(14);
}
break;
case 2:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 245;
if (!(this.precpred(this._ctx, 12))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 12)");
}
this.state = 246;
(_localctx as BinaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!(_la === CashScriptParser.T__26 || _la === CashScriptParser.T__30)) {
(_localctx as BinaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
this.state = 247;
(_localctx as BinaryOpContext)._right = this.expression(13);
}
break;
case 3:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 248;
if (!(this.precpred(this._ctx, 11))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 11)");
}
this.state = 249;
(_localctx as BinaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << CashScriptParser.T__5) | (1 << CashScriptParser.T__6) | (1 << CashScriptParser.T__7) | (1 << CashScriptParser.T__8))) !== 0))) {
(_localctx as BinaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
this.state = 250;
(_localctx as BinaryOpContext)._right = this.expression(12);
}
break;
case 4:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 251;
if (!(this.precpred(this._ctx, 10))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 10)");
}
this.state = 252;
(_localctx as BinaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!(_la === CashScriptParser.T__31 || _la === CashScriptParser.T__32)) {
(_localctx as BinaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
this.state = 253;
(_localctx as BinaryOpContext)._right = this.expression(11);
}
break;
case 5:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 254;
if (!(this.precpred(this._ctx, 9))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 9)");
}
this.state = 255;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__33);
this.state = 256;
(_localctx as BinaryOpContext)._right = this.expression(10);
}
break;
case 6:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 257;
if (!(this.precpred(this._ctx, 8))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 8)");
}
this.state = 258;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__3);
this.state = 259;
(_localctx as BinaryOpContext)._right = this.expression(9);
}
break;
case 7:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 260;
if (!(this.precpred(this._ctx, 7))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 7)");
}
this.state = 261;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__34);
this.state = 262;
(_localctx as BinaryOpContext)._right = this.expression(8);
}
break;
case 8:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 263;
if (!(this.precpred(this._ctx, 6))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 6)");
}
this.state = 264;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__35);
this.state = 265;
(_localctx as BinaryOpContext)._right = this.expression(7);
}
break;
case 9:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 266;
if (!(this.precpred(this._ctx, 5))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 5)");
}
this.state = 267;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__36);
this.state = 268;
(_localctx as BinaryOpContext)._right = this.expression(6);
}
break;
case 10:
{
_localctx = new TupleIndexOpContext(new ExpressionContext(_parentctx, _parentState));
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 269;
if (!(this.precpred(this._ctx, 17))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 17)");
}
this.state = 270;
this.match(CashScriptParser.T__21);
this.state = 271;
(_localctx as TupleIndexOpContext)._index = this.match(CashScriptParser.NumberLiteral);
this.state = 272;
this.match(CashScriptParser.T__22);
}
break;
case 11:
{
_localctx = new UnaryOpContext(new ExpressionContext(_parentctx, _parentState));
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 273;
if (!(this.precpred(this._ctx, 16))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 16)");
}
this.state = 274;
(_localctx as UnaryOpContext)._op = this._input.LT(1);
_la = this._input.LA(1);
if (!(_la === CashScriptParser.T__23 || _la === CashScriptParser.T__24)) {
(_localctx as UnaryOpContext)._op = this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
}
break;
case 12:
{
_localctx = new BinaryOpContext(new ExpressionContext(_parentctx, _parentState));
(_localctx as BinaryOpContext)._left = _prevctx;
this.pushNewRecursionContext(_localctx, _startState, CashScriptParser.RULE_expression);
this.state = 275;
if (!(this.precpred(this._ctx, 14))) {
throw this.createFailedPredicateException("this.precpred(this._ctx, 14)");
}
this.state = 276;
(_localctx as BinaryOpContext)._op = this.match(CashScriptParser.T__27);
this.state = 277;
this.match(CashScriptParser.T__14);
this.state = 278;
(_localctx as BinaryOpContext)._right = this.expression(0);
this.state = 279;
this.match(CashScriptParser.T__16);
}
break;
}
}
}
this.state = 285;
this._errHandler.sync(this);
_alt = this.interpreter.adaptivePredict(this._input, 22, this._ctx);
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.unrollRecursionContexts(_parentctx);
}
return _localctx;
}
// @RuleVersion(0)
public literal(): LiteralContext {
let _localctx: LiteralContext = new LiteralContext(this._ctx, this.state);
this.enterRule(_localctx, 42, CashScriptParser.RULE_literal);
try {
this.state = 291;
this._errHandler.sync(this);
switch (this._input.LA(1)) {
case CashScriptParser.BooleanLiteral:
this.enterOuterAlt(_localctx, 1);
{
this.state = 286;
this.match(CashScriptParser.BooleanLiteral);
}
break;
case CashScriptParser.NumberLiteral:
this.enterOuterAlt(_localctx, 2);
{
this.state = 287;
this.numberLiteral();
}
break;
case CashScriptParser.StringLiteral:
this.enterOuterAlt(_localctx, 3);
{
this.state = 288;
this.match(CashScriptParser.StringLiteral);
}
break;
case CashScriptParser.DateLiteral:
this.enterOuterAlt(_localctx, 4);
{
this.state = 289;
this.match(CashScriptParser.DateLiteral);
}
break;
case CashScriptParser.HexLiteral:
this.enterOuterAlt(_localctx, 5);
{
this.state = 290;
this.match(CashScriptParser.HexLiteral);
}
break;
default:
throw new NoViableAltException(this);
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public numberLiteral(): NumberLiteralContext {
let _localctx: NumberLiteralContext = new NumberLiteralContext(this._ctx, this.state);
this.enterRule(_localctx, 44, CashScriptParser.RULE_numberLiteral);
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 293;
this.match(CashScriptParser.NumberLiteral);
this.state = 295;
this._errHandler.sync(this);
switch ( this.interpreter.adaptivePredict(this._input, 24, this._ctx) ) {
case 1:
{
this.state = 294;
this.match(CashScriptParser.NumberUnit);
}
break;
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
// @RuleVersion(0)
public typeName(): TypeNameContext {
let _localctx: TypeNameContext = new TypeNameContext(this._ctx, this.state);
this.enterRule(_localctx, 46, CashScriptParser.RULE_typeName);
let _la: number;
try {
this.enterOuterAlt(_localctx, 1);
{
this.state = 297;
_la = this._input.LA(1);
if (!(((((_la - 38)) & ~0x1F) === 0 && ((1 << (_la - 38)) & ((1 << (CashScriptParser.T__37 - 38)) | (1 << (CashScriptParser.T__38 - 38)) | (1 << (CashScriptParser.T__39 - 38)) | (1 << (CashScriptParser.T__40 - 38)) | (1 << (CashScriptParser.T__41 - 38)) | (1 << (CashScriptParser.T__42 - 38)) | (1 << (CashScriptParser.Bytes - 38)))) !== 0))) {
this._errHandler.recoverInline(this);
} else {
if (this._input.LA(1) === Token.EOF) {
this.matchedEOF = true;
}
this._errHandler.reportMatch(this);
this.consume();
}
}
}
catch (re) {
if (re instanceof RecognitionException) {
_localctx.exception = re;
this._errHandler.reportError(this, re);
this._errHandler.recover(this, re);
} else {
throw re;
}
}
finally {
this.exitRule();
}
return _localctx;
}
public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean {
switch (ruleIndex) {
case 20:
return this.expression_sempred(_localctx as ExpressionContext, predIndex);
}
return true;
}
private expression_sempred(_localctx: ExpressionContext, predIndex: number): boolean {
switch (predIndex) {
case 0:
return this.precpred(this._ctx, 13);
case 1:
return this.precpred(this._ctx, 12);
case 2:
return this.precpred(this._ctx, 11);
case 3:
return this.precpred(this._ctx, 10);
case 4:
return this.precpred(this._ctx, 9);
case 5:
return this.precpred(this._ctx, 8);
case 6:
return this.precpred(this._ctx, 7);
case 7:
return this.precpred(this._ctx, 6);
case 8:
return this.precpred(this._ctx, 5);
case 9:
return this.precpred(this._ctx, 17);
case 10:
return this.precpred(this._ctx, 16);
case 11:
return this.precpred(this._ctx, 14);
}
return true;
}
public static readonly _serializedATN: string =
"\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03<\u012E\x04\x02" +
"\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" +
"\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r\x04" +
"\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t\x12\x04" +
"\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t\x17\x04" +
"\x18\t\x18\x04\x19\t\x19\x03\x02\x07\x024\n\x02\f\x02\x0E\x027\v\x02\x03" +
"\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x04\x03" +
"\x04\x03\x05\x03\x05\x05\x05E\n\x05\x03\x06\x05\x06H\n\x06\x03\x06\x03" +
"\x06\x03\x07\x03\x07\x03\b\x03\b\x03\b\x03\b\x03\b\x07\bS\n\b\f\b\x0E" +
"\bV\v\b\x03\b\x03\b\x03\t\x03\t\x03\t\x03\t\x03\t\x07\t_\n\t\f\t\x0E\t" +
"b\v\t\x03\t\x03\t\x03\n\x03\n\x03\n\x03\n\x07\nj\n\n\f\n\x0E\nm\v\n\x03" +
"\n\x05\np\n\n\x05\nr\n\n\x03\n\x03\n\x03\v\x03\v\x03\v\x03\f\x03\f\x07" +
"\f{\n\f\f\f\x0E\f~\v\f\x03\f\x03\f\x05\f\x82\n\f\x03\r\x03\r\x03\r\x03" +
"\r\x03\r\x03\r\x05\r\x8A\n\r\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03\x0E\x03" +
"\x0E\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03" +
"\x0F\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x11\x03" +
"\x11\x03\x11\x03\x11\x03\x11\x03\x11\x03\x12\x03\x12\x03\x12\x03\x12\x03" +
"\x12\x03\x12\x03\x13\x03\x13\x03\x13\x03\x13\x03\x13\x03\x13\x03\x13\x05" +
"\x13\xB5\n\x13\x03\x14\x03\x14\x03\x14\x03\x15\x03\x15\x03\x15\x03\x15" +
"\x07\x15\xBE\n\x15\f\x15\x0E\x15\xC1\v\x15\x03\x15\x05\x15\xC4\n\x15\x05" +
"\x15\xC6\n\x15\x03\x15\x03\x15\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16" +
"\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x05\x16\xD4\n\x16\x03\x16\x05" +
"\x16\xD7\n\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16" +
"\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x07\x16\xE5\n\x16\f\x16\x0E\x16" +
"\xE8\v\x16\x03\x16\x05\x16\xEB\n\x16\x05\x16\xED\n\x16\x03\x16\x03\x16" +
"\x03\x16\x03\x16\x05\x16\xF3\n\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03" +
"\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03" +
"\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03" +
"\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03" +
"\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x03\x16\x07\x16\u011C" +
"\n\x16\f\x16\x0E\x16\u011F\v\x16\x03\x17\x03\x17\x03\x17\x03\x17\x03\x17" +
"\x05\x17\u0126\n\x17\x03\x18\x03\x18\x05\x18\u012A\n\x18\x03\x19\x03\x19" +
"\x03\x19\x02\x02\x03*\x1A\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E" +
"\x02\x10\x02\x12\x02\x14\x02\x16\x02\x18\x02\x1A\x02\x1C\x02\x1E\x02 " +
"\x02\"\x02$\x02&\x02(\x02*\x02,\x02.\x020\x02\x02\n\x03\x02\x06\f\x03" +
"\x02\x1C\x1D\x03\x02\x1F \x04\x02\x1D\x1D!!\x03\x02\b\v\x03\x02\"#\x03" +
"\x02\x1A\x1B\x04\x02(-22\x02\u0146\x025\x03\x02\x02\x02\x04;\x03\x02\x02" +
"\x02\x06@\x03\x02\x02\x02\bB\x03\x02\x02\x02\nG\x03\x02\x02\x02\fK\x03" +
"\x02\x02\x02\x0EM\x03\x02\x02\x02\x10Y\x03\x02\x02\x02\x12e\x03\x02\x02" +
"\x02\x14u\x03\x02\x02\x02\x16\x81\x03\x02\x02\x02\x18\x89\x03\x02\x02" +
"\x02\x1A\x8B\x03\x02\x02\x02\x1C\x91\x03\x02\x02\x02\x1E\x9A\x03\x02\x02" +
"\x02 \x9F\x03\x02\x02\x02\"\xA7\x03\x02\x02\x02$\xAD\x03\x02\x02\x02&" +
"\xB6\x03\x02\x02\x02(\xB9\x03\x02\x02\x02*\xF2\x03\x02\x02\x02,\u0125" +
"\x03\x02\x02\x02.\u0127\x03\x02\x02\x020\u012B\x03\x02\x02\x0224\x05\x04" +
"\x03\x0232\x03\x02\x02\x0247\x03\x02\x02\x0253\x03\x02\x02\x0256\x03\x02" +
"\x02\x0268\x03\x02\x02\x0275\x03\x02\x02\x0289\x05\x0E\b\x029:\x07\x02" +
"\x02\x03:\x03\x03\x02\x02\x02;<\x07\x03\x02\x02<=\x05\x06\x04\x02=>\x05" +
"\b\x05\x02>?\x07\x04\x02\x02?\x05\x03\x02\x02\x02@A\x07\x05\x02\x02A\x07" +
"\x03\x02\x02\x02BD\x05\n\x06\x02CE\x05\n\x06\x02DC\x03\x02\x02\x02DE\x03" +
"\x02\x02\x02E\t\x03\x02\x02\x02FH\x05\f\x07\x02GF\x03\x02\x02\x02GH\x03" +
"\x02\x02\x02HI\x03\x02\x02\x02IJ\x07.\x02\x02J\v\x03\x02\x02\x02KL\t\x02" +
"\x02\x02L\r\x03\x02\x02\x02MN\x07\r\x02\x02NO\x079\x02\x02OP\x05\x12\n" +
"\x02PT\x07\x0E\x02\x02QS\x05\x10\t\x02RQ\x03\x02\x02\x02SV\x03\x02\x02" +
"\x02TR\x03\x02\x02\x02TU\x03\x02\x02\x02UW\x03\x02\x02\x02VT\x03\x02\x02" +
"\x02WX\x07\x0F\x02\x02X\x0F\x03\x02\x02\x02YZ\x07\x10\x02\x02Z[\x079\x02" +
"\x02[\\\x05\x12\n\x02\\`\x07\x0E\x02\x02]_\x05\x18\r\x02^]\x03\x02\x02" +
"\x02_b\x03\x02\x02\x02`^\x03\x02\x02\x02`a\x03\x02\x02\x02ac\x03\x02\x02" +
"\x02b`\x03\x02\x02\x02cd\x07\x0F\x02\x02d\x11\x03\x02\x02\x02eq\x07\x11" +
"\x02\x02fk\x05\x14\v\x02gh\x07\x12\x02\x02hj\x05\x14\v\x02ig\x03\x02\x02" +
"\x02jm\x03\x02\x02\x02ki\x03\x02\x02\x02kl\x03\x02\x02\x02lo\x03\x02\x02" +
"\x02mk\x03\x02\x02\x02np\x07\x12\x02\x02on\x03\x02\x02\x02op\x03\x02\x02" +
"\x02pr\x03\x02\x02\x02qf\x03\x02\x02\x02qr\x03\x02\x02\x02rs\x03\x02\x02" +
"\x02st\x07\x13\x02\x02t\x13\x03\x02\x02\x02uv\x050\x19\x02vw\x079\x02" +
"\x02w\x15\x03\x02\x02\x02x|\x07\x0E\x02\x02y{\x05\x18\r\x02zy\x03\x02" +
"\x02\x02{~\x03\x02\x02\x02|z\x03\x02\x02\x02|}\x03\x02\x02\x02}\x7F\x03" +
"\x02\x02\x02~|\x03\x02\x02\x02\x7F\x82\x07\x0F\x02\x02\x80\x82\x05\x18" +
"\r\x02\x81x\x03\x02\x02\x02\x81\x80\x03\x02\x02\x02\x82\x17\x03\x02\x02" +
"\x02\x83\x8A\x05\x1A\x0E\x02\x84\x8A\x05\x1C\x0F\x02\x85\x8A\x05\x1E\x10" +
"\x02\x86\x8A\x05 \x11\x02\x87\x8A\x05\"\x12\x02\x88\x8A\x05$\x13\x02\x89" +
"\x83\x03\x02\x02\x02\x89\x84\x03\x02\x02\x02\x89\x85\x03\x02\x02\x02\x89" +
"\x86\x03\x02\x02\x02\x89\x87\x03\x02\x02\x02\x89\x88\x03\x02\x02\x02\x8A" +
"\x19\x03\x02\x02\x02\x8B\x8C\x050\x19\x02\x8C\x8D\x079\x02\x02\x8D\x8E" +
"\x07\f\x02\x02\x8E\x8F\x05*\x16\x02\x8F\x90\x07\x04\x02\x02\x90\x1B\x03" +
"\x02\x02\x02\x91\x92\x050\x19\x02\x92\x93\x079\x02\x02\x93\x94\x07\x12" +
"\x02\x02\x94\x95\x050\x19\x02\x95\x96\x079\x02\x02\x96\x97\x07\f\x02\x02" +
"\x97\x98\x05*\x16\x02\x98\x99\x07\x04\x02\x02\x99\x1D\x03\x02\x02\x02" +
"\x9A\x9B\x079\x02\x02\x9B\x9C\x07\f\x02\x02\x9C\x9D\x05*\x16\x02\x9D\x9E" +
"\x07\x04\x02\x02\x9E\x1F\x03\x02\x02\x02\x9F\xA0\x07\x14\x02\x02\xA0\xA1" +
"\x07\x11\x02\x02\xA1\xA2\x077\x02\x02\xA2\xA3\x07\b\x02\x02\xA3\xA4\x05" +
"*\x16\x02\xA4\xA5\x07\x13\x02\x02\xA5\xA6\x07\x04\x02\x02\xA6!\x03\x02" +
"\x02\x02\xA7\xA8\x07\x14\x02\x02\xA8\xA9\x07\x11\x02\x02\xA9\xAA\x05*" +
"\x16\x02\xAA\xAB\x07\x13\x02\x02\xAB\xAC\x07\x04\x02\x02\xAC#\x03\x02" +
"\x02\x02\xAD\xAE\x07\x15\x02\x02\xAE\xAF\x07\x11\x02\x02\xAF\xB0\x05*" +
"\x16\x02\xB0\xB1\x07\x13\x02\x02\xB1\xB4\x05\x16\f\x02\xB2\xB3\x07\x16" +
"\x02\x02\xB3\xB5\x05\x16\f\x02\xB4\xB2\x03\x02\x02\x02\xB4\xB5\x03\x02" +
"\x02\x02\xB5%\x03\x02\x02\x02\xB6\xB7\x079\x02\x02\xB7\xB8\x05(\x15\x02" +
"\xB8\'\x03\x02\x02\x02\xB9\xC5\x07\x11\x02\x02\xBA\xBF\x05*\x16\x02\xBB" +
"\xBC\x07\x12\x02\x02\xBC\xBE\x05*\x16\x02\xBD\xBB\x03\x02\x02\x02\xBE" +
"\xC1\x03\x02\x02\x02\xBF\xBD\x03\x02\x02\x02\xBF\xC0\x03\x02\x02\x02\xC0" +
"\xC3\x03\x02\x02\x02\xC1\xBF\x03\x02\x02\x02\xC2\xC4\x07\x12\x02\x02\xC3" +
"\xC2\x03\x02\x02\x02\xC3\xC4\x03\x02\x02\x02\xC4\xC6\x03\x02\x02\x02\xC5" +
"\xBA\x03\x02\x02\x02\xC5\xC6\x03\x02\x02\x02\xC6\xC7\x03\x02\x02\x02\xC7" +
"\xC8\x07\x13\x02\x02\xC8)\x03\x02\x02\x02\xC9\xCA\b\x16\x01\x02\xCA\xCB" +
"\x07\x11\x02\x02\xCB\xCC\x05*\x16\x02\xCC\xCD\x07\x13\x02\x02\xCD\xF3" +
"\x03\x02\x02\x02\xCE\xCF\x050\x19\x02\xCF\xD0\x07\x11\x02\x02\xD0\xD3" +
"\x05*\x16\x02\xD1\xD2\x07\x12\x02\x02\xD2\xD4\x05*\x16\x02\xD3\xD1\x03" +
"\x02\x02\x02\xD3\xD4\x03\x02\x02\x02\xD4\xD6\x03\x02\x02\x02\xD5\xD7\x07" +
"\x12\x02\x02\xD6\xD5\x03\x02\x02\x02\xD6\xD7\x03\x02\x02\x02\xD7\xD8\x03" +
"\x02\x02\x02\xD8\xD9\x07\x13\x02\x02\xD9\xF3\x03\x02\x02\x02\xDA\xF3\x05" +
"&\x14\x02\xDB\xDC\x07\x17\x02\x02\xDC\xDD\x079\x02\x02\xDD\xF3\x05(\x15" +
"\x02\xDE\xDF\t\x03\x02\x02\xDF\xF3\x05*\x16\x11\xE0\xEC\x07\x18\x02\x02" +
"\xE1\xE6\x05*\x16\x02\xE2\xE3\x07\x12\x02\x02\xE3\xE5\x05*\x16\x02\xE4" +
"\xE2\x03\x02\x02\x02\xE5\xE8\x03\x02\x02\x02\xE6\xE4\x03\x02\x02\x02\xE6" +
"\xE7\x03\x02\x02\x02\xE7\xEA\x03\x02\x02\x02\xE8\xE6\x03\x02\x02\x02\xE9" +
"\xEB\x07\x12\x02\x02\xEA\xE9\x03\x02\x02\x02\xEA\xEB\x03\x02\x02\x02\xEB" +
"\xED\x03\x02\x02\x02\xEC\xE1\x03\x02\x02\x02\xEC\xED\x03\x02\x02\x02\xED" +
"\xEE\x03\x02\x02\x02\xEE\xF3\x07\x19\x02\x02\xEF\xF3\x078\x02\x02\xF0" +
"\xF3\x079\x02\x02\xF1\xF3\x05,\x17\x02\xF2\xC9\x03\x02\x02\x02\xF2\xCE" +
"\x03\x02\x02\x02\xF2\xDA\x03\x02\x02\x02\xF2\xDB\x03\x02\x02\x02\xF2\xDE" +
"\x03\x02\x02\x02\xF2\xE0\x03\x02\x02\x02\xF2\xEF\x03\x02\x02\x02\xF2\xF0" +
"\x03\x02\x02\x02\xF2\xF1\x03\x02\x02\x02\xF3\u011D\x03\x02\x02\x02\xF4" +
"\xF5\f\x0F\x02\x02\xF5\xF6\t\x04\x02\x02\xF6\u011C\x05*\x16\x10\xF7\xF8" +
"\f\x0E\x02\x02\xF8\xF9\t\x05\x02\x02\xF9\u011C\x05*\x16\x0F\xFA\xFB\f" +
"\r\x02\x02\xFB\xFC\t\x06\x02\x02\xFC\u011C\x05*\x16\x0E\xFD\xFE\f\f\x02" +
"\x02\xFE\xFF\t\x07\x02\x02\xFF\u011C\x05*\x16\r\u0100\u0101\f\v\x02\x02" +
"\u0101\u0102\x07$\x02\x02\u0102\u011C\x05*\x16\f\u0103\u0104\f\n\x02\x02" +
"\u0104\u0105\x07\x06\x02\x02\u0105\u011C\x05*\x16\v\u0106\u0107\f\t\x02" +
"\x02\u0107\u0108\x07%\x02\x02\u0108\u011C\x05*\x16\n\u0109\u010A\f\b\x02" +
"\x02\u010A\u010B\x07&\x02\x02\u010B\u011C\x05*\x16\t\u010C\u010D\f\x07" +
"\x02\x02\u010D\u010E\x07\'\x02\x02\u010E\u011C\x05*\x16\b\u010F\u0110" +
"\f\x13\x02\x02\u0110\u0111\x07\x18\x02\x02\u0111\u0112\x071\x02\x02\u0112" +
"\u011C\x07\x19\x02\x02\u0113\u0114\f\x12\x02\x02\u0114\u011C\t\b\x02\x02" +
"\u0115\u0116\f\x10\x02\x02\u0116\u0117\x07\x1E\x02\x02\u0117\u0118\x07" +
"\x11\x02\x02\u0118\u0119\x05*\x16\x02\u0119\u011A\x07\x13\x02\x02\u011A" +
"\u011C\x03\x02\x02\x02\u011B\xF4\x03\x02\x02\x02\u011B\xF7\x03\x02\x02" +
"\x02\u011B\xFA\x03\x02\x02\x02\u011B\xFD\x03\x02\x02\x02\u011B\u0100\x03" +
"\x02\x02\x02\u011B\u0103\x03\x02\x02\x02\u011B\u0106\x03\x02\x02\x02\u011B" +
"\u0109\x03\x02\x02\x02\u011B\u010C\x03\x02\x02\x02\u011B\u010F\x03\x02" +
"\x02\x02\u011B\u0113\x03\x02\x02\x02\u011B\u0115\x03\x02\x02\x02\u011C" +
"\u011F\x03\x02\x02\x02\u011D\u011B\x03\x02\x02\x02\u011D\u011E\x03\x02" +
"\x02\x02\u011E+\x03\x02\x02\x02\u011F\u011D\x03\x02\x02\x02\u0120\u0126" +
"\x07/\x02\x02\u0121\u0126\x05.\x18\x02\u0122\u0126\x074\x02\x02\u0123" +
"\u0126\x075\x02\x02\u0124\u0126\x076\x02\x02\u0125\u0120\x03\x02\x02\x02" +
"\u0125\u0121\x03\x02\x02\x02\u0125\u0122\x03\x02\x02\x02\u0125\u0123\x03" +
"\x02\x02\x02\u0125\u0124\x03\x02\x02\x02\u0126-\x03\x02\x02\x02\u0127" +
"\u0129\x071\x02\x02\u0128\u012A\x070\x02\x02\u0129\u0128\x03\x02\x02\x02" +
"\u0129\u012A\x03\x02\x02\x02\u012A/\x03\x02\x02\x02\u012B\u012C\t\t\x02" +
"\x02\u012C1\x03\x02\x02\x02\x1B5DGT`koq|\x81\x89\xB4\xBF\xC3\xC5\xD3\xD6" +
"\xE6\xEA\xEC\xF2\u011B\u011D\u0125\u0129";
public static __ATN: ATN;
public static get _ATN(): ATN {
if (!CashScriptParser.__ATN) {
CashScriptParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(CashScriptParser._serializedATN));
}
return CashScriptParser.__ATN;
}
}
export class SourceFileContext extends ParserRuleContext {
public contractDefinition(): ContractDefinitionContext {
return this.getRuleContext(0, ContractDefinitionContext);
}
public EOF(): TerminalNode { return this.getToken(CashScriptParser.EOF, 0); }
public pragmaDirective(): PragmaDirectiveContext[];
public pragmaDirective(i: number): PragmaDirectiveContext;
public pragmaDirective(i?: number): PragmaDirectiveContext | PragmaDirectiveContext[] {
if (i === undefined) {
return this.getRuleContexts(PragmaDirectiveContext);
} else {
return this.getRuleContext(i, PragmaDirectiveContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_sourceFile; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterSourceFile) {
listener.enterSourceFile(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitSourceFile) {
listener.exitSourceFile(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitSourceFile) {
return visitor.visitSourceFile(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class PragmaDirectiveContext extends ParserRuleContext {
public pragmaName(): PragmaNameContext {
return this.getRuleContext(0, PragmaNameContext);
}
public pragmaValue(): PragmaValueContext {
return this.getRuleContext(0, PragmaValueContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_pragmaDirective; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterPragmaDirective) {
listener.enterPragmaDirective(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitPragmaDirective) {
listener.exitPragmaDirective(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitPragmaDirective) {
return visitor.visitPragmaDirective(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class PragmaNameContext extends ParserRuleContext {
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_pragmaName; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterPragmaName) {
listener.enterPragmaName(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitPragmaName) {
listener.exitPragmaName(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitPragmaName) {
return visitor.visitPragmaName(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class PragmaValueContext extends ParserRuleContext {
public versionConstraint(): VersionConstraintContext[];
public versionConstraint(i: number): VersionConstraintContext;
public versionConstraint(i?: number): VersionConstraintContext | VersionConstraintContext[] {
if (i === undefined) {
return this.getRuleContexts(VersionConstraintContext);
} else {
return this.getRuleContext(i, VersionConstraintContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_pragmaValue; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterPragmaValue) {
listener.enterPragmaValue(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitPragmaValue) {
listener.exitPragmaValue(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitPragmaValue) {
return visitor.visitPragmaValue(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class VersionConstraintContext extends ParserRuleContext {
public VersionLiteral(): TerminalNode { return this.getToken(CashScriptParser.VersionLiteral, 0); }
public versionOperator(): VersionOperatorContext | undefined {
return this.tryGetRuleContext(0, VersionOperatorContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_versionConstraint; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterVersionConstraint) {
listener.enterVersionConstraint(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitVersionConstraint) {
listener.exitVersionConstraint(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitVersionConstraint) {
return visitor.visitVersionConstraint(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class VersionOperatorContext extends ParserRuleContext {
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_versionOperator; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterVersionOperator) {
listener.enterVersionOperator(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitVersionOperator) {
listener.exitVersionOperator(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitVersionOperator) {
return visitor.visitVersionOperator(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ContractDefinitionContext extends ParserRuleContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public parameterList(): ParameterListContext {
return this.getRuleContext(0, ParameterListContext);
}
public functionDefinition(): FunctionDefinitionContext[];
public functionDefinition(i: number): FunctionDefinitionContext;
public functionDefinition(i?: number): FunctionDefinitionContext | FunctionDefinitionContext[] {
if (i === undefined) {
return this.getRuleContexts(FunctionDefinitionContext);
} else {
return this.getRuleContext(i, FunctionDefinitionContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_contractDefinition; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterContractDefinition) {
listener.enterContractDefinition(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitContractDefinition) {
listener.exitContractDefinition(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitContractDefinition) {
return visitor.visitContractDefinition(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class FunctionDefinitionContext extends ParserRuleContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public parameterList(): ParameterListContext {
return this.getRuleContext(0, ParameterListContext);
}
public statement(): StatementContext[];
public statement(i: number): StatementContext;
public statement(i?: number): StatementContext | StatementContext[] {
if (i === undefined) {
return this.getRuleContexts(StatementContext);
} else {
return this.getRuleContext(i, StatementContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_functionDefinition; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterFunctionDefinition) {
listener.enterFunctionDefinition(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitFunctionDefinition) {
listener.exitFunctionDefinition(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitFunctionDefinition) {
return visitor.visitFunctionDefinition(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ParameterListContext extends ParserRuleContext {
public parameter(): ParameterContext[];
public parameter(i: number): ParameterContext;
public parameter(i?: number): ParameterContext | ParameterContext[] {
if (i === undefined) {
return this.getRuleContexts(ParameterContext);
} else {
return this.getRuleContext(i, ParameterContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_parameterList; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterParameterList) {
listener.enterParameterList(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitParameterList) {
listener.exitParameterList(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitParameterList) {
return visitor.visitParameterList(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ParameterContext extends ParserRuleContext {
public typeName(): TypeNameContext {
return this.getRuleContext(0, TypeNameContext);
}
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_parameter; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterParameter) {
listener.enterParameter(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitParameter) {
listener.exitParameter(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitParameter) {
return visitor.visitParameter(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class BlockContext extends ParserRuleContext {
public statement(): StatementContext[];
public statement(i: number): StatementContext;
public statement(i?: number): StatementContext | StatementContext[] {
if (i === undefined) {
return this.getRuleContexts(StatementContext);
} else {
return this.getRuleContext(i, StatementContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_block; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterBlock) {
listener.enterBlock(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitBlock) {
listener.exitBlock(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitBlock) {
return visitor.visitBlock(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class StatementContext extends ParserRuleContext {
public variableDefinition(): VariableDefinitionContext | undefined {
return this.tryGetRuleContext(0, VariableDefinitionContext);
}
public tupleAssignment(): TupleAssignmentContext | undefined {
return this.tryGetRuleContext(0, TupleAssignmentContext);
}
public assignStatement(): AssignStatementContext | undefined {
return this.tryGetRuleContext(0, AssignStatementContext);
}
public timeOpStatement(): TimeOpStatementContext | undefined {
return this.tryGetRuleContext(0, TimeOpStatementContext);
}
public requireStatement(): RequireStatementContext | undefined {
return this.tryGetRuleContext(0, RequireStatementContext);
}
public ifStatement(): IfStatementContext | undefined {
return this.tryGetRuleContext(0, IfStatementContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_statement; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterStatement) {
listener.enterStatement(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitStatement) {
listener.exitStatement(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitStatement) {
return visitor.visitStatement(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class VariableDefinitionContext extends ParserRuleContext {
public typeName(): TypeNameContext {
return this.getRuleContext(0, TypeNameContext);
}
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_variableDefinition; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterVariableDefinition) {
listener.enterVariableDefinition(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitVariableDefinition) {
listener.exitVariableDefinition(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitVariableDefinition) {
return visitor.visitVariableDefinition(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class TupleAssignmentContext extends ParserRuleContext {
public typeName(): TypeNameContext[];
public typeName(i: number): TypeNameContext;
public typeName(i?: number): TypeNameContext | TypeNameContext[] {
if (i === undefined) {
return this.getRuleContexts(TypeNameContext);
} else {
return this.getRuleContext(i, TypeNameContext);
}
}
public Identifier(): TerminalNode[];
public Identifier(i: number): TerminalNode;
public Identifier(i?: number): TerminalNode | TerminalNode[] {
if (i === undefined) {
return this.getTokens(CashScriptParser.Identifier);
} else {
return this.getToken(CashScriptParser.Identifier, i);
}
}
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_tupleAssignment; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterTupleAssignment) {
listener.enterTupleAssignment(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitTupleAssignment) {
listener.exitTupleAssignment(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitTupleAssignment) {
return visitor.visitTupleAssignment(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class AssignStatementContext extends ParserRuleContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_assignStatement; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterAssignStatement) {
listener.enterAssignStatement(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitAssignStatement) {
listener.exitAssignStatement(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitAssignStatement) {
return visitor.visitAssignStatement(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class TimeOpStatementContext extends ParserRuleContext {
public TxVar(): TerminalNode { return this.getToken(CashScriptParser.TxVar, 0); }
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_timeOpStatement; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterTimeOpStatement) {
listener.enterTimeOpStatement(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitTimeOpStatement) {
listener.exitTimeOpStatement(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitTimeOpStatement) {
return visitor.visitTimeOpStatement(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class RequireStatementContext extends ParserRuleContext {
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_requireStatement; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterRequireStatement) {
listener.enterRequireStatement(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitRequireStatement) {
listener.exitRequireStatement(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitRequireStatement) {
return visitor.visitRequireStatement(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class IfStatementContext extends ParserRuleContext {
public _ifBlock!: BlockContext;
public _elseBlock!: BlockContext;
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
public block(): BlockContext[];
public block(i: number): BlockContext;
public block(i?: number): BlockContext | BlockContext[] {
if (i === undefined) {
return this.getRuleContexts(BlockContext);
} else {
return this.getRuleContext(i, BlockContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_ifStatement; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterIfStatement) {
listener.enterIfStatement(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitIfStatement) {
listener.exitIfStatement(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitIfStatement) {
return visitor.visitIfStatement(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class FunctionCallContext extends ParserRuleContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public expressionList(): ExpressionListContext {
return this.getRuleContext(0, ExpressionListContext);
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_functionCall; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterFunctionCall) {
listener.enterFunctionCall(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitFunctionCall) {
listener.exitFunctionCall(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitFunctionCall) {
return visitor.visitFunctionCall(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ExpressionListContext extends ParserRuleContext {
public expression(): ExpressionContext[];
public expression(i: number): ExpressionContext;
public expression(i?: number): ExpressionContext | ExpressionContext[] {
if (i === undefined) {
return this.getRuleContexts(ExpressionContext);
} else {
return this.getRuleContext(i, ExpressionContext);
}
}
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_expressionList; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterExpressionList) {
listener.enterExpressionList(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitExpressionList) {
listener.exitExpressionList(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitExpressionList) {
return visitor.visitExpressionList(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ExpressionContext extends ParserRuleContext {
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_expression; }
public copyFrom(ctx: ExpressionContext): void {
super.copyFrom(ctx);
}
}
export class ParenthesisedContext extends ExpressionContext {
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterParenthesised) {
listener.enterParenthesised(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitParenthesised) {
listener.exitParenthesised(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitParenthesised) {
return visitor.visitParenthesised(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class CastContext extends ExpressionContext {
public _castable!: ExpressionContext;
public _size!: ExpressionContext;
public typeName(): TypeNameContext {
return this.getRuleContext(0, TypeNameContext);
}
public expression(): ExpressionContext[];
public expression(i: number): ExpressionContext;
public expression(i?: number): ExpressionContext | ExpressionContext[] {
if (i === undefined) {
return this.getRuleContexts(ExpressionContext);
} else {
return this.getRuleContext(i, ExpressionContext);
}
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterCast) {
listener.enterCast(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitCast) {
listener.exitCast(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitCast) {
return visitor.visitCast(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class FunctionCallExpressionContext extends ExpressionContext {
public functionCall(): FunctionCallContext {
return this.getRuleContext(0, FunctionCallContext);
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterFunctionCallExpression) {
listener.enterFunctionCallExpression(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitFunctionCallExpression) {
listener.exitFunctionCallExpression(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitFunctionCallExpression) {
return visitor.visitFunctionCallExpression(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class InstantiationContext extends ExpressionContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
public expressionList(): ExpressionListContext {
return this.getRuleContext(0, ExpressionListContext);
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterInstantiation) {
listener.enterInstantiation(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitInstantiation) {
listener.exitInstantiation(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitInstantiation) {
return visitor.visitInstantiation(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class TupleIndexOpContext extends ExpressionContext {
public _index!: Token;
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
public NumberLiteral(): TerminalNode { return this.getToken(CashScriptParser.NumberLiteral, 0); }
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterTupleIndexOp) {
listener.enterTupleIndexOp(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitTupleIndexOp) {
listener.exitTupleIndexOp(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitTupleIndexOp) {
return visitor.visitTupleIndexOp(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class UnaryOpContext extends ExpressionContext {
public _op!: Token;
public expression(): ExpressionContext {
return this.getRuleContext(0, ExpressionContext);
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterUnaryOp) {
listener.enterUnaryOp(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitUnaryOp) {
listener.exitUnaryOp(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitUnaryOp) {
return visitor.visitUnaryOp(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class BinaryOpContext extends ExpressionContext {
public _left!: ExpressionContext;
public _op!: Token;
public _right!: ExpressionContext;
public expression(): ExpressionContext[];
public expression(i: number): ExpressionContext;
public expression(i?: number): ExpressionContext | ExpressionContext[] {
if (i === undefined) {
return this.getRuleContexts(ExpressionContext);
} else {
return this.getRuleContext(i, ExpressionContext);
}
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterBinaryOp) {
listener.enterBinaryOp(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitBinaryOp) {
listener.exitBinaryOp(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitBinaryOp) {
return visitor.visitBinaryOp(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class ArrayContext extends ExpressionContext {
public expression(): ExpressionContext[];
public expression(i: number): ExpressionContext;
public expression(i?: number): ExpressionContext | ExpressionContext[] {
if (i === undefined) {
return this.getRuleContexts(ExpressionContext);
} else {
return this.getRuleContext(i, ExpressionContext);
}
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterArray) {
listener.enterArray(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitArray) {
listener.exitArray(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitArray) {
return visitor.visitArray(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class PreimageFieldContext extends ExpressionContext {
public PreimageField(): TerminalNode { return this.getToken(CashScriptParser.PreimageField, 0); }
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterPreimageField) {
listener.enterPreimageField(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitPreimageField) {
listener.exitPreimageField(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitPreimageField) {
return visitor.visitPreimageField(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class IdentifierContext extends ExpressionContext {
public Identifier(): TerminalNode { return this.getToken(CashScriptParser.Identifier, 0); }
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterIdentifier) {
listener.enterIdentifier(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitIdentifier) {
listener.exitIdentifier(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitIdentifier) {
return visitor.visitIdentifier(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class LiteralExpressionContext extends ExpressionContext {
public literal(): LiteralContext {
return this.getRuleContext(0, LiteralContext);
}
constructor(ctx: ExpressionContext) {
super(ctx.parent, ctx.invokingState);
this.copyFrom(ctx);
}
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterLiteralExpression) {
listener.enterLiteralExpression(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitLiteralExpression) {
listener.exitLiteralExpression(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitLiteralExpression) {
return visitor.visitLiteralExpression(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class LiteralContext extends ParserRuleContext {
public BooleanLiteral(): TerminalNode | undefined { return this.tryGetToken(CashScriptParser.BooleanLiteral, 0); }
public numberLiteral(): NumberLiteralContext | undefined {
return this.tryGetRuleContext(0, NumberLiteralContext);
}
public StringLiteral(): TerminalNode | undefined { return this.tryGetToken(CashScriptParser.StringLiteral, 0); }
public DateLiteral(): TerminalNode | undefined { return this.tryGetToken(CashScriptParser.DateLiteral, 0); }
public HexLiteral(): TerminalNode | undefined { return this.tryGetToken(CashScriptParser.HexLiteral, 0); }
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_literal; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterLiteral) {
listener.enterLiteral(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitLiteral) {
listener.exitLiteral(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitLiteral) {
return visitor.visitLiteral(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class NumberLiteralContext extends ParserRuleContext {
public NumberLiteral(): TerminalNode { return this.getToken(CashScriptParser.NumberLiteral, 0); }
public NumberUnit(): TerminalNode | undefined { return this.tryGetToken(CashScriptParser.NumberUnit, 0); }
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_numberLiteral; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterNumberLiteral) {
listener.enterNumberLiteral(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitNumberLiteral) {
listener.exitNumberLiteral(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitNumberLiteral) {
return visitor.visitNumberLiteral(this);
} else {
return visitor.visitChildren(this);
}
}
}
export class TypeNameContext extends ParserRuleContext {
public Bytes(): TerminalNode { return this.getToken(CashScriptParser.Bytes, 0); }
constructor(parent: ParserRuleContext | undefined, invokingState: number) {
super(parent, invokingState);
}
// @Override
public get ruleIndex(): number { return CashScriptParser.RULE_typeName; }
// @Override
public enterRule(listener: CashScriptListener): void {
if (listener.enterTypeName) {
listener.enterTypeName(this);
}
}
// @Override
public exitRule(listener: CashScriptListener): void {
if (listener.exitTypeName) {
listener.exitTypeName(this);
}
}
// @Override
public accept<Result>(visitor: CashScriptVisitor<Result>): Result {
if (visitor.visitTypeName) {
return visitor.visitTypeName(this);
} else {
return visitor.visitChildren(this);
}
}
} | the_stack |
import * as JVMTypes from '../../includes/JVMTypes';
import * as DoppioJVM from '../doppiojvm';
import JVMThread = DoppioJVM.VM.Threading.JVMThread;
import ReferenceClassData = DoppioJVM.VM.ClassFile.ReferenceClassData;
import logging = DoppioJVM.Debug.Logging;
import util = DoppioJVM.VM.Util;
import Long = DoppioJVM.VM.Long;
import AbstractClasspathJar = DoppioJVM.VM.ClassFile.AbstractClasspathJar;
import * as BrowserFS from 'browserfs';
import * as path from 'path';
import * as fs from 'fs';
import ThreadStatus = DoppioJVM.VM.Enums.ThreadStatus;
import ArrayClassData = DoppioJVM.VM.ClassFile.ArrayClassData;
import PrimitiveClassData = DoppioJVM.VM.ClassFile.PrimitiveClassData;
import assert = DoppioJVM.Debug.Assert;
import * as deflate from 'pako/lib/zlib/deflate';
import * as inflate from 'pako/lib/zlib/inflate';
import crc32 = require('pako/lib/zlib/crc32');
import adler32 = require('pako/lib/zlib/adler32');
import * as ZStreamCons from 'pako/lib/zlib/zstream';
import * as GZHeader from 'pako/lib/zlib/gzheader';
import i82u8 = util.i82u8;
import isInt8Array = util.isInt8Array;
import u82i8 = util.u82i8;
import ZStream = Pako.ZStream;
import ZlibReturnCode = Pako.ZlibReturnCode;
import ZlibFlushValue = Pako.ZlibFlushValue;
let BFSUtils = BrowserFS.BFSRequire('bfs_utils');
const MAX_WBITS = 15;
// For type information only.
import {default as TZipFS, CentralDirectory as TCentralDirectory} from 'browserfs/dist/node/backend/ZipFS';
let CanUseCopyFastPath = false;
if (typeof Int8Array !== "undefined") {
let i8arr = new Int8Array(1);
let b = new Buffer(<any> i8arr.buffer);
i8arr[0] = 100;
CanUseCopyFastPath = i8arr[0] == b.readInt8(0);
}
export default function (): any {
let ZipFiles: {[id: number]: TZipFS} = {};
let ZipEntries: {[id: number]: TCentralDirectory} = {};
let ZStreams: {[id: number]: ZStream} = {};
// Start at 1, as 0 is interpreted as an error.
let NextId: number = 1;
function OpenItem<T>(item: T, map: {[id: number]: T}): number {
let id = NextId++;
map[id] = item;
return id;
}
function GetItem<T>(thread: JVMThread, id: number, map: {[id: number]: T}, errMsg: string): T {
let item = map[id];
if (!item) {
thread.throwNewException("Ljava/lang/IllegalStateException;", errMsg);
return null;
} else {
return item;
}
}
function CloseItem<T>(id: number, map: {[id: number]: T}): void {
delete map[id];
}
function OpenZipFile(zfile: TZipFS): number {
return OpenItem(zfile, ZipFiles);
}
function CloseZipFile(id: number): void {
CloseItem(id, ZipFiles);
}
/**
* Returns the zip file, if it exists.
* Otherwise, throws an IllegalStateException.
*/
function GetZipFile(thread: JVMThread, id: number): TZipFS {
return GetItem(thread, id, ZipFiles, `ZipFile not found.`);
}
function OpenZipEntry(zentry: TCentralDirectory): number {
return OpenItem(zentry, ZipEntries);
}
function CloseZipEntry(id: number): void {
CloseItem(id, ZipEntries);
}
/**
* Returns the zip entry, if it exists.
* Otherwise, throws an IllegalStateException.
*/
function GetZipEntry(thread: JVMThread, id: number): TCentralDirectory {
return GetItem(thread, id, ZipEntries, `Invalid ZipEntry.`);
}
function OpenZStream(inflaterState: ZStream): number {
return OpenItem(inflaterState, ZStreams);
}
function CloseZStream(id: number): void {
CloseItem(id, ZStreams);
}
function GetZStream(thread: JVMThread, id: number): ZStream {
return GetItem(thread, id, ZStreams, `Inflater not found.`);
}
/**
* The type of a JZEntry field. Copied from java.util.zip.ZipFile.
*/
const enum JZEntryType {
JZENTRY_NAME = 0,
JZENTRY_EXTRA = 1,
JZENTRY_COMMENT = 2,
}
class java_util_concurrent_atomic_AtomicLong {
public static 'VMSupportsCS8()Z'(thread: JVMThread): boolean {
return true;
}
}
class java_util_jar_JarFile {
/**
* Returns an array of strings representing the names of all entries
* that begin with "META-INF/" (case ignored). This native method is
* used in JarFile as an optimization when looking up manifest and
* signature file entries. Returns null if no entries were found.
*/
public static 'getMetaInfEntryNames()[Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.java_util_jar_JarFile): JVMTypes.JVMArray<JVMTypes.java_lang_String> {
let zip = GetZipFile(thread, javaThis['java/util/zip/ZipFile/jzfile'].toNumber());
if (zip) {
if (!zip.existsSync('/META-INF')) {
return null;
}
let explorePath: string[] = ['/META-INF'];
let bsCl = thread.getBsCl();
let foundFiles: JVMTypes.java_lang_String[] = [util.initString(bsCl, 'META-INF/')];
while (explorePath.length > 0) {
let p = explorePath.pop();
let dirListing = zip.readdirSync(p);
for (let i = 0; i < dirListing.length; i++) {
let newP = `${p}/${dirListing[i]}`;
if (zip.statSync(newP, false).isDirectory()) {
explorePath.push(newP);
// Add a final /, and strip off first /.
foundFiles.push(util.initString(bsCl, `${newP.slice(1)}/`));
} else {
// Strip off first /.
foundFiles.push(util.initString(bsCl, newP.slice(1)));
}
}
return util.newArrayFromData<JVMTypes.java_lang_String>(thread, bsCl, "[Ljava/lang/String;", foundFiles);
}
}
}
}
class java_util_logging_FileHandler {
public static 'isSetUID()Z'(thread: JVMThread): boolean {
// Our FS does not support setUID.
return false;
}
}
class java_util_TimeZone {
public static 'getSystemTimeZoneID(Ljava/lang/String;)Ljava/lang/String;'(thread: JVMThread, arg0: JVMTypes.java_lang_String): JVMTypes.java_lang_String {
// NOTE: Can be half of an hour (e.g. Newfoundland is GMT-3.5)
// NOTE: Is positive for negative offset.
let offset = new Date().getTimezoneOffset() / 60;
return thread.getJVM().internString(`GMT${offset > 0 ? '-' : '+'}${offset}`);
}
public static 'getSystemGMTOffsetID()Ljava/lang/String;'(thread: JVMThread): JVMTypes.java_lang_String {
// XXX may not be correct
return null;
}
}
class java_util_zip_Adler32 {
public static 'update(II)I'(thread: JVMThread, adler: number, byte: number): number {
return adler32(adler, [byte & 0xFF], 1, 0);
}
public static 'updateBytes(I[BII)I'(thread: JVMThread, adler: number, b: JVMTypes.JVMArray<number>, off: number, len: number): number {
return adler32(adler, i82u8(b.array, off, len), len, 0);
}
public static 'updateByteBuffer(IJII)I'(thread: JVMThread, adler: number, addr: Long, off: number, len: number): number {
let heap = thread.getJVM().getHeap();
let buff = heap.get_buffer(addr.toNumber() + off, len);
return adler32(adler, buff, buff.length, 0);
}
}
class java_util_zip_CRC32 {
public static 'update(II)I'(thread: JVMThread, crc: number, byte: number): number {
return crc32(crc, [byte & 0xFF], 1, 0);
}
public static 'updateBytes(I[BII)I'(thread: JVMThread, crc: number, b: JVMTypes.JVMArray<number>, off: number, len: number): number {
return crc32(crc, i82u8(b.array, off, len), len, 0);
}
public static 'updateByteBuffer(IJII)I'(thread: JVMThread, crc: number, addr: Long, off: number, len: number): number {
let heap = thread.getJVM().getHeap();
let buff = heap.get_buffer(addr.toNumber() + off, len);
return crc32(crc, buff, buff.length, 0);
}
}
class java_util_zip_Deflater {
public static 'initIDs()V'(thread: JVMThread): void {}
/**
* Initialize a new deflater. Using the zlib recommended default values.
*/
public static 'init(IIZ)J'(thread: JVMThread, level: number, strategy: number, nowrap: number): Long {
let DEF_MEM_LEVEL = 8; // Zlib recommended default
let Z_DEFLATED = 8; // This value is in the js version of pako under pako.Z_DEFLATED.
// Possibly it is set to private in the Typescript version. The default value is 8, so this should work fine
let strm = new ZStreamCons();
let ret = deflate.deflateInit2(strm, level, Z_DEFLATED, nowrap ? -MAX_WBITS : MAX_WBITS, DEF_MEM_LEVEL, strategy);
if (ret != ZlibReturnCode.Z_OK) {
let msg = ((strm.msg) ? strm.msg :
(ret == ZlibReturnCode.Z_STREAM_ERROR) ?
"inflateInit2 returned Z_STREAM_ERROR" :
"unknown error initializing zlib library");
thread.throwNewException("Ljava/lang/InternalError;", msg);
} else {
let num = OpenZStream(strm);
return Long.fromNumber(num);
}
}
/**
* Apparently this is explicitly not supported by pako.
* @see Notes at http://nodeca.github.io/pako/
*/
public static 'setDictionary(J[BII)V'(thread: JVMThread, arg0: Long, arg1: JVMTypes.JVMArray<number>, arg2: number, arg3: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
public static 'deflateBytes(J[BIII)I'(thread: JVMThread, javaThis: JVMTypes.java_util_zip_Deflater, addr: Long, b: JVMTypes.JVMArray<number>, off: number, len: number, flush: number): number {
let strm = GetZStream(thread, addr.toNumber());
if (!strm) return;
let thisBuf = javaThis['java/util/zip/Deflater/buf'];
let thisOff = javaThis['java/util/zip/Deflater/off'];
let thisLen = javaThis['java/util/zip/Deflater/len'];
let inBuf = thisBuf.array;
let outBuf = b.array;
strm.input = i82u8(inBuf, 0, inBuf.length);
strm.next_in = thisOff;
strm.avail_in = thisLen;
strm.output = i82u8(outBuf, 0, outBuf.length);
strm.next_out = off;
strm.avail_out = len;
if (javaThis['java/util/zip/Deflater/setParams']) {
let level = javaThis['java/util/zip/Deflater/level'];
let strategy = javaThis['java/util/zip/Deflater/level'];
//deflateParams is not yet supported by pako. We'll open a new ZStream with the new parameters instead.
// res = deflate.deflateParams(strm, level, strategy);
let newStream = new ZStreamCons();
let res = deflate.deflateInit2(newStream, level, strm.state.method, strm.state.windowBits, strm.state.memLevel, strategy);
ZStreams[addr.toNumber()] = newStream;
switch (res) {
case ZlibReturnCode.Z_OK:
javaThis['java/util/zip/Deflater/setParams'] = 0;
thisOff += thisLen - strm.avail_in;
javaThis['java/util/zip/Deflater/off'] = thisOff;
javaThis['java/util/zip/Deflater/len'] = strm.avail_in;
return len - strm.avail_out;
case ZlibReturnCode.Z_BUF_ERROR:
javaThis['java/util/zip/Deflater/setParams'] = 0;
return 0;
default:
thread.throwNewException("Ljava/lang/InternalError;", strm.msg);
}
} else {
let finish = javaThis['java/util/zip/Deflater/finish'];
let res = deflate.deflate(strm, finish ? ZlibFlushValue.Z_FINISH : flush);
switch (res) {
case ZlibReturnCode.Z_STREAM_END:
javaThis['java/util/zip/Deflater/finished'] = 1;
// intentionally fall through
case ZlibReturnCode.Z_OK:
thisOff += thisLen - strm.avail_in;
javaThis['java/util/zip/Deflater/off'] = thisOff;
javaThis['java/util/zip/Deflater/len'] = strm.avail_in;
return len - strm.avail_out;
case ZlibReturnCode.Z_BUF_ERROR:
return 0;
default:
thread.throwNewException('Ljava/lang/InternalError;', strm.msg);
}
}
}
public static 'getAdler(J)I'(thread: JVMThread, addr: Long): number {
let strm = GetZStream(thread, addr.toNumber());
if (strm) {
return strm.adler;
}
}
public static 'reset(J)V'(thread: JVMThread, addr: Long): void {
let strm = GetZStream(thread, addr.toNumber());
if (strm) {
if (deflate.deflateReset(strm) !== ZlibReturnCode.Z_OK) {
thread.throwNewException('Ljava/lang/InternalError;', strm.msg);
}
}
}
public static 'end(J)V'(thread: JVMThread, addr: Long): void {
let strm = GetZStream(thread, addr.toNumber());
if (strm) {
if (deflate.deflateEnd(strm) === ZlibReturnCode.Z_STREAM_ERROR) {
thread.throwNewException('Ljava/lang/InternalError;', strm.msg);
} else {
CloseZStream(addr.toNumber());
}
}
}
}
class java_util_zip_Inflater {
public static 'initIDs()V'(thread: JVMThread): void {
// NOP.
}
public static 'init(Z)J'(thread: JVMThread, nowrap: number): Long {
// Copying logic exactly from Java's native.
let strm = new ZStreamCons();
let ret = inflate.inflateInit2(strm, nowrap ? -MAX_WBITS : MAX_WBITS);
switch(ret) {
case ZlibReturnCode.Z_OK:
let num = OpenZStream(strm);
return Long.fromNumber(num);
default:
let msg = (strm.msg) ? strm.msg :
(ret == ZlibReturnCode.Z_STREAM_ERROR) ?
"inflateInit2 returned Z_STREAM_ERROR" :
"unknown error initializing zlib library";
thread.throwNewException("Ljava/lang/InternalError;", msg);
break;
}
}
/**
* Note: This function is explicitly not supported by pako, the library we use
* for inflation.
* @see Notes at http://nodeca.github.io/pako/
*/
public static 'setDictionary(J[BII)V'(thread: JVMThread, arg0: Long, arg1: JVMTypes.JVMArray<number>, arg2: number, arg3: number): void {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
}
/**
* NOTE: inflateBytes modifies the following properties on the Inflate object:
*
* - off
* - len
* - needDict
* - finished
*/
public static 'inflateBytes(J[BII)I'(thread: JVMThread, javaThis: JVMTypes.java_util_zip_Inflater, addr: Long, b: JVMTypes.JVMArray<number>, off: number, len: number): number {
let strm = GetZStream(thread, addr.toNumber());
if (!strm) {
return;
}
let thisBuf = javaThis['java/util/zip/Inflater/buf'];
let thisOff = javaThis['java/util/zip/Inflater/off'];
let thisLen = javaThis['java/util/zip/Inflater/len'];
// Return 0 when the buffer is empty, which tells Java to refill its buffer.
if (thisLen === 0 || len === 0) {
return 0;
}
let inBuf = thisBuf.array;
let outBuf = b.array;
// Set up the zstream.
strm.input = i82u8(inBuf, 0, inBuf.length);
strm.next_in = thisOff;
strm.avail_in = thisLen;
strm.output = i82u8(outBuf, 0, outBuf.length);
strm.next_out = off;
strm.avail_out = len;
// NOTE: JVM code does a partial flush, but Pako doesn't support it.
// Thus, we do a sync flush instead.
let ret = inflate.inflate(strm, ZlibFlushValue.Z_SYNC_FLUSH);
let lenRead = len - strm.avail_out;
if (!isInt8Array(outBuf)) {
// Slow path: No typed arrays. Copy decompressed data.
// u8 -> i8
let result = strm.output;
for (let i = 0; i < lenRead; i++) {
let byte = result[i + off];
if (byte > 127) {
// Sign extend.
byte |= 0xFFFFFF80
}
outBuf[i + off] = byte;
}
}
switch(ret) {
case ZlibReturnCode.Z_STREAM_END:
javaThis['java/util/zip/Inflater/finished'] = 1;
/* fall through */
case ZlibReturnCode.Z_OK:
thisOff += thisLen - strm.avail_in;
javaThis['java/util/zip/Inflater/off'] = thisOff;
javaThis['java/util/zip/Inflater/len'] = strm.avail_in;
return lenRead;
case ZlibReturnCode.Z_NEED_DICT:
javaThis['java/util/zip/Inflater/needDict'] = 1;
/* Might have consumed some input here! */
thisOff += thisLen - strm.avail_in;
javaThis['java/util/zip/Inflater/off'] = thisOff;
javaThis['java/util/zip/Inflater/len'] = strm.avail_in;
return 0;
case ZlibReturnCode.Z_BUF_ERROR:
return 0;
case ZlibReturnCode.Z_DATA_ERROR:
thread.throwNewException('Ljava/util/zip/DataFormatException;', strm.msg);
return;
default:
thread.throwNewException('Ljava/lang/InternalError;', strm.msg);
return;
}
}
public static 'getAdler(J)I'(thread: JVMThread, addr: Long): number {
let strm = GetZStream(thread, addr.toNumber());
if (strm) {
return strm.adler;
}
}
public static 'reset(J)V'(thread: JVMThread, addr: Long): void {
let addrNum = addr.toNumber();
let strm = GetZStream(thread, addrNum);
if (strm) {
/* There's a bug in Pako that prevents reset from working.
if (inflate.inflateReset(strm) !== ZlibReturnCode.Z_OK) {
thread.throwNewException('Ljava/lang/InternalError;', '');
}
*/
// Allocate a new stream, instead.
let newStrm = new ZStreamCons();
let ret = inflate.inflateInit2(newStrm, strm.state.wrap ? MAX_WBITS : -MAX_WBITS);
ZStreams[addrNum] = newStrm;
}
}
public static 'end(J)V'(thread: JVMThread, addr: Long): void {
let strm = GetZStream(thread, addr.toNumber());
if (strm) {
if (inflate.inflateEnd(strm) === ZlibReturnCode.Z_STREAM_ERROR) {
thread.throwNewException('Ljava/lang/InternalError;', strm.msg);
} else {
CloseZStream(addr.toNumber());
}
}
}
}
class java_util_zip_ZipFile {
public static 'initIDs()V'(thread: JVMThread): void {
// NOP.
}
/**
* Note: Returns 0 when entry does not exist.
*/
public static 'getEntry(J[BZ)J'(thread: JVMThread, jzfile: Long, nameBytes: JVMTypes.JVMArray<number>, addSlash: number): Long {
// ASSUMPTION: Name is UTF-8.
// Should actually compare the raw bytes.
let zipfs = GetZipFile(thread, jzfile.toNumber());
if (zipfs) {
let name = new Buffer(nameBytes.array).toString('utf8');
if (name[0] !== '/') {
name = `/${name}`;
}
name = path.resolve(name);
try {
return Long.fromNumber(OpenZipEntry(zipfs.getCentralDirectoryEntry(name)));
} catch (e) {
return Long.ZERO;
}
}
}
public static 'freeEntry(JJ)V'(thread: JVMThread, jzfile: Long, jzentry: Long): void {
CloseZipEntry(jzentry.toNumber());
}
public static 'getNextEntry(JI)J'(thread: JVMThread, jzfile: Long, index: number): Long {
let zipfs = GetZipFile(thread, jzfile.toNumber());
if (zipfs) {
try {
return Long.fromNumber(OpenZipEntry(zipfs.getCentralDirectoryEntryAt(index)));
} catch (e) {
return Long.ZERO;
}
}
}
public static 'close(J)V'(thread: JVMThread, jzfile: Long): void {
CloseZipFile(jzfile.toNumber());
}
public static 'open(Ljava/lang/String;IJZ)J'(thread: JVMThread, nameObj: JVMTypes.java_lang_String, mode: number, modified: Long, usemmap: number): Long {
// Ignore mmap option.
let name = nameObj.toString();
// Optimization: Check if this is a JAR file on the classpath.
let cpath = thread.getBsCl().getClassPathItems();
for (let i = 0; i < cpath.length; i++) {
let cpathItem = cpath[i];
if (cpathItem instanceof AbstractClasspathJar) {
if (path.resolve(cpathItem.getPath()) === path.resolve(name)) {
return Long.fromNumber(OpenZipFile((<AbstractClasspathJar> <any> cpathItem).getFS()));
}
}
}
// Async path.
thread.setStatus(ThreadStatus.ASYNC_WAITING);
fs.readFile(name, (err, data) => {
if (err) {
thread.throwNewException("Ljava/io/IOException;", err.message);
} else {
thread.asyncReturn(Long.fromNumber(OpenZipFile(new BrowserFS.FileSystem.ZipFS(data, name))), null);
}
});
}
public static 'getTotal(J)I'(thread: JVMThread, jzfile: Long): number {
let zipfs = GetZipFile(thread, jzfile.toNumber());
if (zipfs) {
return zipfs.getNumberOfCentralDirectoryEntries();
}
}
public static 'startsWithLOC(J)Z'(thread: JVMThread, arg0: Long): number {
// We do not support any zip files that do not begin with the proper signature.
// Boolean, so 1 === true.
return 1;
}
public static 'read(JJJ[BII)I'(thread: JVMThread, jzfile: Long, jzentry: Long, pos: Long, b: JVMTypes.JVMArray<number>, off: number, len: number): number {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
let posNum = pos.toNumber();
if (zipentry) {
if (len <= 0) {
return 0;
}
let data = zipentry.getRawData();
// Sanity check: Will likely never happen, as Java code ensures that this method is
// called in a sane manner.
if (posNum >= data.length) {
thread.throwNewException("Ljava/io/IOException;", "End of zip file.");
return;
}
if (posNum + len > data.length) {
len = data.length - posNum;
}
let arr = b.array;
if (CanUseCopyFastPath) {
let i8arr: Int8Array = <any> arr;
// XXX: DefinitelyTyped typings are out of date.
let b = new Buffer(<any> i8arr.buffer);
return data.copy(b, off + i8arr.byteOffset, posNum, posNum + len);
} else {
for (let i = 0; i < len; i++) {
arr[off + i] = data.readInt8(posNum + i);
}
return len;
}
}
}
public static 'getEntryTime(J)J'(thread: JVMThread, jzentry: Long): Long {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return Long.fromNumber(zipentry.rawLastModFileTime());
}
}
public static 'getEntryCrc(J)J'(thread: JVMThread, jzentry: Long): Long {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return Long.fromNumber(zipentry.crc32());
}
}
public static 'getEntryCSize(J)J'(thread: JVMThread, jzentry: Long): Long {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return Long.fromNumber(zipentry.compressedSize());
}
}
public static 'getEntrySize(J)J'(thread: JVMThread, jzentry: Long): Long {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return Long.fromNumber(zipentry.uncompressedSize());
}
}
public static 'getEntryMethod(J)I'(thread: JVMThread, jzentry: Long): number {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return zipentry.compressionMethod();
}
}
public static 'getEntryFlag(J)I'(thread: JVMThread, jzentry: Long): number {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
return zipentry.flag();
}
}
public static 'getCommentBytes(J)[B'(thread: JVMThread, jzfile: Long): JVMTypes.JVMArray<number> {
let zipfile = GetZipFile(thread, jzfile.toNumber());
if (zipfile) {
let eocd = zipfile.getEndOfCentralDirectory();
let comment = eocd.rawCdZipComment();
// Should be zero-copy in most situations.
return util.newArrayFromDataWithClass(thread, <ArrayClassData<number>> thread.getBsCl().getInitializedClass(thread, '[B'), <number[]> u82i8(comment, 0, comment.length));
}
}
public static 'getEntryBytes(JI)[B'(thread: JVMThread, jzentry: Long, type: JZEntryType): JVMTypes.JVMArray<number> {
let zipentry = GetZipEntry(thread, jzentry.toNumber());
if (zipentry) {
switch(type) {
case JZEntryType.JZENTRY_COMMENT:
return util.newArrayFromDataWithClass(thread, <ArrayClassData<number>> thread.getBsCl().getInitializedClass(thread, '[B'), <number[]> u82i8(zipentry.rawFileComment()));
case JZEntryType.JZENTRY_EXTRA:
return util.newArrayFromDataWithClass(thread, <ArrayClassData<number>> thread.getBsCl().getInitializedClass(thread, '[B'), <number[]> u82i8(zipentry.extraField()));
case JZEntryType.JZENTRY_NAME:
return util.newArrayFromDataWithClass(thread, <ArrayClassData<number>> thread.getBsCl().getInitializedClass(thread, '[B'), <number[]> u82i8(zipentry.rawFileName()));
default:
return null;
}
}
}
/**
* Called to get an exception message. Should never really need to be called.
*/
public static 'getZipMessage(J)Ljava/lang/String;'(thread: JVMThread, jzfile: Long): JVMTypes.java_lang_String {
return util.initString(thread.getBsCl(), "Something bad happened.");
}
}
return {
'java/util/concurrent/atomic/AtomicLong': java_util_concurrent_atomic_AtomicLong,
'java/util/jar/JarFile': java_util_jar_JarFile,
'java/util/logging/FileHandler': java_util_logging_FileHandler,
'java/util/TimeZone': java_util_TimeZone,
'java/util/zip/Adler32': java_util_zip_Adler32,
'java/util/zip/CRC32': java_util_zip_CRC32,
'java/util/zip/Deflater': java_util_zip_Deflater,
'java/util/zip/Inflater': java_util_zip_Inflater,
'java/util/zip/ZipFile': java_util_zip_ZipFile
};
}; | the_stack |
import { ArtboardFacade, LayerAttributesConfig } from './artboard-facade'
import { DesignExportFacade } from './design-export-facade'
import { DesignListItemFacade } from './design-list-item-facade'
import { LayerCollectionFacade } from './layer-collection-facade'
import { PageFacade } from './page-facade'
import { basename } from 'path'
import { inspect } from 'util'
import {
createEmptyDesign,
ArtboardId,
OctopusDocument,
ArtboardSelector,
ComponentId,
DesignLayerSelector,
IArtboard,
IDesign,
IPage,
LayerId,
ManifestData,
PageId,
PageSelector,
LayerOctopusData,
} from '@opendesign/octopus-reader'
import { sequence } from './utils/async-utils'
import { toFileKey } from './utils/id-utils'
import { memoize } from './utils/memoize-utils'
import { getDesignFormatByFileName } from './utils/design-format-utils'
import { enumerablizeWithPrototypeGetters } from './utils/object-utils'
import { createLayerEntitySelector } from './utils/selector-utils'
import type { CancelToken } from '@avocode/cancel-token'
import type { DesignId, DesignVersionId, IApiDesign } from '@opendesign/api'
import type {
Bounds,
IRenderingDesign,
BlendingMode,
LayerBounds,
} from '@opendesign/rendering'
import type { components } from 'open-design-api-types'
import type {
FontDescriptor,
LayerAttributes,
LayerFacade,
LayerOctopusAttributesConfig,
} from './layer-facade'
import type { Sdk } from './sdk'
import type { FontSource } from './local/font-source'
import type { BitmapAssetDescriptor, LocalDesign } from './local/local-design'
type DesignExportTargetFormatEnum = components['schemas']['DesignExportTargetFormatEnum']
export class DesignFacade {
/**
* The absolute path of the original design file. This is not available for designs loaded from the API.
* @category Identification
*/
readonly sourceFilename: string | null
private _sdk: Sdk
private _console: Console
private _designEntity: IDesign | null = null
private _localDesign: LocalDesign | null = null
private _apiDesign: IApiDesign | null = null
private _renderingDesign: IRenderingDesign | null = null
private _fontSource: FontSource | null = null
private _artboardFacades: Map<ArtboardId, ArtboardFacade> = new Map()
private _pageFacades: Map<PageId, PageFacade> = new Map()
private _manifestLoaded = false
private _pendingManifestUpdate: ManifestData | null = null
private _loadingArtboardPromises: Map<ArtboardId, Promise<void>> = new Map()
private _designExports: Map<
DesignExportTargetFormatEnum,
DesignExportFacade
> = new Map()
/** @internal */
constructor(params: {
sdk: Sdk
console?: Console | null
sourceFilename?: string | null
}) {
this.sourceFilename = params.sourceFilename || null
this._sdk = params.sdk
this._console = params.console || console
enumerablizeWithPrototypeGetters(this, {
enumerableOwnKeys: ['sourceFilename'],
omittedPrototypeKeys: ['octopusFilename'],
})
}
/**
* The ID of the referenced server-side design. This is not available when the API is not configured for the SDK.
* @category Identification
*/
get id(): DesignId | null {
const apiDesign = this._apiDesign
return apiDesign?.id || null
}
/**
* The ID of the referenced server-side design version. This is not available when the API is not configured for the SDK.
* @category Identification
*/
get versionId(): DesignVersionId | null {
const apiDesign = this._apiDesign
return apiDesign?.versionId || null
}
/**
* The key which can be used to name files in the file system.
*
* This is the ID of the referenced server-side design or (if the API is not configured) the basename of the local file.
*
* It can theoretically be `null` when the design is created only virtually in memory but such feature is yet to be implemented thus the value can safely be assumed as always available and for that reason, it is annotated as non-nullable.
*
* @category Identification
*
* @example
* ```typescript
* design.renderArtboardToFile(`./artboards/${design.fileKey}/${artboard.fileKey}.png`)
* ```
*/
get fileKey(): string {
const id = this.id
if (id) {
return toFileKey(id)
}
const localDesign = this._localDesign
if (localDesign) {
return basename(localDesign.filename)
}
// @ts-expect-error When empty in-memory designs are supported, this is going to be a valid value.
return null
}
/**
* The name of the design. This is the basename of the file by default or a custom name provided during design import.
* @category Data
*/
get name(): string | null {
const apiDesign = this._apiDesign
if (apiDesign) {
return apiDesign.name
}
const localDesign = this._localDesign
if (localDesign) {
return basename(localDesign.filename)
}
return null
}
/**
* The absolute path of the local cache. This is not available when the local cache is not configured for the SDK.
* @internal
* @category Identification
*/
get octopusFilename(): string | null {
const localDesign = this._localDesign
return localDesign?.filename || null
}
/** @internal */
toString(): string {
const designInfo = this.toJSON()
return `Design ${inspect(designInfo)}`
}
/** @internal */
[inspect.custom](): string {
return this.toString()
}
/** @internal */
toJSON(): unknown {
return { ...this }
}
/** @internal */
getManifest(): ManifestData {
if (this._pendingManifestUpdate) {
return this._pendingManifestUpdate
}
const entity = this._getDesignEntity()
return entity.getManifest()
}
/** @internal */
setManifest(nextManifest: ManifestData): void {
this._pendingManifestUpdate = nextManifest
this._manifestLoaded = true
this._getDesignEntity.clear()
this._getArtboardsMemoized.clear()
this._getPagesMemoized.clear()
}
private _getDesignEntity = memoize(
(): IDesign => {
const entity = this._designEntity || createEmptyDesign()
const pendingManifestUpdate = this._pendingManifestUpdate
if (pendingManifestUpdate) {
this._pendingManifestUpdate = null
entity.setManifest(pendingManifestUpdate)
this._getArtboardsMemoized.clear()
this._getPagesMemoized.clear()
}
return entity
}
)
/** @internal */
getLocalDesign(): LocalDesign | null {
return this._localDesign
}
/** @internal */
async setLocalDesign(
localDesign: LocalDesign,
options: {
cancelToken?: CancelToken | null
}
): Promise<void> {
if (!this._manifestLoaded) {
this.setManifest(await localDesign.getManifest(options))
}
this._localDesign = localDesign
}
/** @internal */
async setApiDesign(
apiDesign: IApiDesign,
options: {
cancelToken?: CancelToken | null
}
): Promise<void> {
if (!this._manifestLoaded) {
this.setManifest(await apiDesign.getManifest(options))
}
this._apiDesign = apiDesign
}
/** @internal */
setRenderingDesign(renderingDesign: IRenderingDesign): void {
this._renderingDesign = renderingDesign
}
/**
* Returns a complete list of versions of the design.
*
* Data of the design versions themselves are not downloaded at this point. Each item in the design version list can be expanded to a full-featured design entity.
*
* The design version list contains both processed and unprocessed design versions.
*
* The API has to be configured when using this method.
*
* @example
* ```typescript
* const versionList = await design.getVersions()
* const versionItem = versionList.find((version) => version.status === 'done')
* // Expand the design version list item to a full design entity
* const version = await versionItem.fetchDesign()
* // Continue working with the processed design version
* const versionArtboards = version.getArtboards()
* ```
*
* @category Design Versions
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected. A cancellation token can be created via {@link createCancelToken}.
* @returns An array of design list item objects which can be used for retrieving the design versions using the API.
*/
async getVersions(
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<Array<DesignListItemFacade>> {
const apiDesign = this._apiDesign
if (!apiDesign) {
throw new Error('The API is not configured.')
}
const apiDesignVersions = await apiDesign.getVersionList(options)
const versionItems = apiDesignVersions.map((apiDesignVersion) => {
const versionItem = new DesignListItemFacade(apiDesignVersion, {
sdk: this._sdk,
})
if (this._fontSource) {
versionItem.setFontSource(this._fontSource.clone())
}
return versionItem
})
return versionItems
}
/**
* Fetches a previously imported version of the design from the API.
*
* The API has to be configured when using this method. Local caching is established in case the local cache is configured.
*
* @example
* ```typescript
* const version = await design.getVersionById('<VERSION_ID>')
*
* // Continue working with the processed design version
* const versionArtboards = version.getArtboards()
* ```
*
* @category Design Versions
* @param designVersionId An ID of a server-side design version assigned during import (via `importVersionDesignFile()`).
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the local cache is not cleared once created). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
getVersionById(
designVersionId: DesignVersionId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignFacade> {
const apiDesign = this._apiDesign
if (!apiDesign) {
throw new Error('The API is not configured.')
}
return this._sdk.fetchDesignById(apiDesign.id, {
...options,
designVersionId,
})
}
/**
* Fetches a previously imported version of the design newer than the current version of the {@link DesignFacade} entity from the API.
*
* The API has to be configured when using this method. Local caching is established in case the local cache is configured.
*
* @example
* ```typescript
* const nextVersion = await design.getNextVersion()
*
* // Continue working with the processed design version
* const versionArtboards = nextVersion.getArtboards()
* ```
*
* @category Design Versions
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the local cache is not cleared once created). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
async getNextVersion(
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignFacade | null> {
const versionItems = await this.getVersions(options)
const currentVersionIndex = versionItems.findIndex((versionItem) => {
return versionItem.versionId === this.versionId
})
const nextVersionIndex =
currentVersionIndex > 0 ? currentVersionIndex - 1 : -1
const nextVersionItem =
nextVersionIndex > -1 ? versionItems[nextVersionIndex] : null
return nextVersionItem ? nextVersionItem.fetchDesign(options) : null
}
/**
* Fetches a previously imported version of the design older than the current version of the {@link DesignFacade} entity from the API.
*
* The API has to be configured when using this method. Local caching is established in case the local cache is configured.
*
* @example
* ```typescript
* const prevVersion = await design.getPrevVersion()
*
* // Continue working with the processed design version
* const versionArtboards = prevVersion.getArtboards()
* ```
*
* @category Design Versions
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the local cache is not cleared once created). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
async getPreviousVersion(
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignFacade | null> {
const versionItems = await this.getVersions()
const currentVersionIndex = versionItems.findIndex((versionItem) => {
return versionItem.versionId === this.versionId
})
const prevVersionIndex =
currentVersionIndex > -1 ? currentVersionIndex + 1 : -1
const prevVersionItem =
currentVersionIndex > -1 ? versionItems[prevVersionIndex] : null
return prevVersionItem ? prevVersionItem.fetchDesign(options) : null
}
/**
* Imports a local design file (Photoshop, Sketch, Xd, Illustrator) as a version of the design.
*
* All versions of a design must originate from the same design file format.
*
* The API has to be configured when using this method. This is also requires a file system (i.e. it is not available in the browser).
*
* The design file is automatically uploaded to the API and local caching is established.
*
* @example
* ```typescript
* const version = await design.importVersionDesignFile('data.sketch')
* console.log(version.sourceFilename) // == path.join(process.cwd(), 'data.sketch')
* console.log(version.id) // == server-generated UUID
*
* // Continue working with the processed design version
* const versionArtboards = version.getArtboards()
* ```
*
* @category Design Versions
* @param filePath An absolute design file path or a path relative to the current working directory.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the design is not deleted from the server when the token is cancelled during processing; the server still finishes the processing but the SDK stops watching its progress and does not download the result). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
importVersionDesignFile(
filePath: string,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignFacade> {
return this._sdk.importDesignFile(filePath, {
...options,
designId: this.id,
})
}
/**
* Imports a design file located at the specified URL as a version of the design.
*
* All versions of a design must originate from the same design file format.
*
* The API has to be configured when using this method.
*
* The design file is not downloaded to the local environment but rather imported via the API directly. Once imported via the API, the design version behaves exactly like a design version fetched via {@link DesignFacade.getVersionById}.
*
* @example
* ```typescript
* const version = await sdk.importVersionDesignLink('https://example.com/designs/data.sketch')
* console.log(version.id) // == server-generated UUID
*
* // Continue working with the processed design version
* const versionArtboards = version.getArtboards()
* ```
*
* @category Design Versions
* @param url A design file URL.
* @param options Options
* @param options.format The format of the design file in case it cannot be inferred from the URL.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the design is not deleted from the server when the token is cancelled during processing; the server still finishes the processing but the SDK stops watching its progress and does not download the result). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
importVersionDesignLink(
url: string,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignFacade> {
return this._sdk.importDesignLink(url, {
...options,
designId: this.id,
})
}
/**
* Imports a Figma design as a version of the design.
*
* All versions of a design must originate from the same design file format which makes this method usable only for designs originally also imported from Figma.
*
* The API has to be configured when using this method.
*
* The design is automatically imported by the API and local caching is established.
*
* @example Explicitly provided Figma token
* ```typescript
* const version = await design.importVersionFigmaDesign({
* figmaToken: '<FIGMA_TOKEN>',
* figmaFileKey: 'abc',
* })
*
* console.log(version.id) // == server-generated UUID
*
* // Continue working with the processed design version
* const artboards = version.getArtboards()
* ```
*
* @example Figma token not provided, using Figma OAuth connection
* ```typescript
* const version = await design.importVersionFigmaDesign({
* figmaFileKey: 'abc',
* })
*
* console.log(version.id) // == server-generated UUID
*
* // Continue working with the processed design version
* const artboards = version.getArtboards()
* ```
*
* @category Figma Design Usage
* @param params Info about the Figma design
* @param params.figmaFileKey A Figma design "file key" from the design URL (i.e. `abc` from `https://www.figma.com/file/abc/Sample-File`).
* @param params.figmaToken A Figma access token generated in the "Personal access tokens" section of [Figma account settings](https://www.figma.com/settings). This is only required when the user does not have a Figma account connected.
* @param params.figmaIds A listing of Figma design frames to use.
* @param params.designName A name override for the design version. The original Figma design name is used by default.
* @param params.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the design is not deleted from the server when the token is cancelled during processing; the server still finishes the processing but the SDK stops watching its progress and does not download the result). A cancellation token can be created via {@link createCancelToken}.
* @returns A design object which can be used for retrieving data from the design version using the API.
*/
importVersionFigmaDesign(params: {
figmaFileKey: string
figmaToken?: string | null
figmaIds?: Array<string>
designName?: string | null
cancelToken?: CancelToken | null
}): Promise<DesignFacade> {
return this._sdk.importFigmaDesign({
...params,
designId: this.id,
})
}
/**
* Returns a complete list of artboard object in the design. These can be used to work with artboard contents.
*
* @category Artboard Lookup
* @returns An artboard list.
*
* @example
* ```typescript
* const artboards = design.getArtboards()
* ```
*/
getArtboards(): Array<ArtboardFacade> {
return this._getArtboardsMemoized()
}
private _getArtboardsMemoized = memoize(
(): Array<ArtboardFacade> => {
const prevArtboardFacades = this._artboardFacades
const nextArtboardFacades: Map<ArtboardId, ArtboardFacade> = new Map()
const entity = this._getDesignEntity()
const artboardEntities = entity.getArtboards()
artboardEntities.forEach((artboardEntity) => {
const artboardId = artboardEntity.id
const artboardFacade =
prevArtboardFacades.get(artboardId) ||
this._createArtboardFacade(artboardEntity)
artboardFacade.setArtboardEntity(artboardEntity)
nextArtboardFacades.set(artboardId, artboardFacade)
})
this._artboardFacades = nextArtboardFacades
return [...nextArtboardFacades.values()]
}
)
/**
* Returns a single artboard object. These can be used to work with the artboard contents.
*
* @category Artboard Lookup
* @param artboardId An artboard ID.
* @returns An artboard object.
*
* @example
* ```typescript
* const artboard = design.getArtboardById('<ARTBOARD_ID>')
* ```
*/
getArtboardById(artboardId: ArtboardId): ArtboardFacade | null {
const prevArtboardFacade = this._artboardFacades.get(artboardId)
if (prevArtboardFacade) {
return prevArtboardFacade
}
const entity = this._getDesignEntity()
const artboardEntity = entity.getArtboardById(artboardId)
if (!artboardEntity) {
return null
}
const artboardFacade = this._createArtboardFacade(artboardEntity)
artboardFacade.setArtboardEntity(artboardEntity)
const nextArtboardFacades = new Map(this._artboardFacades.entries())
nextArtboardFacades.set(artboardId, artboardFacade)
return artboardFacade
}
/**
* Returns artboard objects for a specific page (in case the design is paged). These can be used to work with artboard contents.
*
* @category Artboard Lookup
* @param pageId A page ID.
* @returns An artboard list.
*
* @example
* ```typescript
* const pageArtboards = design.getPageArtboards('<PAGE_ID>')
* ```
*/
getPageArtboards(pageId: PageId): Array<ArtboardFacade> {
const entity = this._getDesignEntity()
const artboardEntities = entity.getPageArtboards(pageId)
return artboardEntities
.map((artboardEntity) => {
return this.getArtboardById(artboardEntity.id)
})
.filter(Boolean) as Array<ArtboardFacade>
}
/**
* Returns (main/master) component artboard objects. These can be used to work with artboard contents.
*
* @category Artboard Lookup
* @returns An artboard list.
*
* @example
* ```typescript
* const componentArtboards = design.getComponentArtboards()
* ```
*/
getComponentArtboards(): Array<ArtboardFacade> {
const entity = this._getDesignEntity()
const artboardEntities = entity.getComponentArtboards()
return artboardEntities
.map((artboardEntity) => {
return this.getArtboardById(artboardEntity.id)
})
.filter(Boolean) as Array<ArtboardFacade>
}
/**
* Returns an artboard object of a specific (main/master) component. These can be used to work with the artboard contents.
*
* @category Artboard Lookup
* @param componentId A component ID.
* @returns An artboard object.
*
* @example
* ```typescript
* const artboard = design.getArtboardByComponentId('<COMPONENT_ID>')
* ```
*/
getArtboardByComponentId(componentId: ComponentId): ArtboardFacade | null {
const entity = this._getDesignEntity()
const artboardEntity = entity.getArtboardByComponentId(componentId)
return artboardEntity ? this.getArtboardById(artboardEntity.id) : null
}
/**
* Returns info about whether the design is paged (i.e. has artboards organized on different pages).
*
* @category Page Lookup
* @returns Whether the design is paged.
*
* @example
* ```typescript
* const shouldRenderPageList = design.isPaged()
* ```
*/
isPaged(): boolean {
const entity = this._getDesignEntity()
return entity.isPaged()
}
/**
* Returns a complete list of page object in the design. These can be used to work with artboard contents.
*
* An empty list is returned for unpaged designs.
*
* @category Page Lookup
* @returns A page list.
*
* @example
* ```typescript
* const pages = design.getPages()
* ```
*/
getPages(): Array<PageFacade> {
return this._getPagesMemoized()
}
private _getPagesMemoized = memoize(
(): Array<PageFacade> => {
const prevPageFacades = this._pageFacades
const nextPageFacades: Map<PageId, PageFacade> = new Map()
const entity = this._getDesignEntity()
const pageEntities = entity.getPages()
pageEntities.forEach((pageEntity) => {
const pageId = pageEntity.id
const pageFacade =
prevPageFacades.get(pageId) || this._createPageFacade(pageEntity)
pageFacade.setPageEntity(pageEntity)
nextPageFacades.set(pageId, pageFacade)
})
this._pageFacades = nextPageFacades
return [...nextPageFacades.values()]
}
)
/**
* Returns a single page object. These can be used to work with the page contents and contents of artboards inside the page.
*
* @category Page Lookup
* @param pageId A page ID.
* @returns A page object.
*
* @example
* ```typescript
* const page = design.getPageById('<PAGE_ID>')
* ```
*/
getPageById(pageId: PageId): PageFacade | null {
const prevPageFacade = this._pageFacades.get(pageId)
if (prevPageFacade) {
return prevPageFacade
}
const entity = this._getDesignEntity()
const pageEntity = entity.getPageById(pageId)
if (!pageEntity) {
return null
}
const pageFacade = this._createPageFacade(pageEntity)
pageFacade.setPageEntity(pageEntity)
const nextPageFacades = new Map(this._pageFacades.entries())
nextPageFacades.set(pageId, pageFacade)
return pageFacade
}
private _createArtboardFacade(artboardEntity: IArtboard): ArtboardFacade {
const artboard = new ArtboardFacade(artboardEntity, { designFacade: this })
return artboard
}
private _createPageFacade(pageEntity: IPage): PageFacade {
const page = new PageFacade(pageEntity, { designFacade: this })
return page
}
/**
* Looks up the first artboard object matching the provided criteria.
*
* @category Artboard Lookup
* @param selector An artboard selector. All specified fields must be matched by the result.
* @returns An artboard object.
*
* @example
* ```typescript
* const productArtboard = design.findArtboard({ name: /Product/i })
* const productArtboard = design.findArtboard((artboard) => /Product/i.test(artboard.name))
* const oneOfArtboards123 = design.findArtboard({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findArtboard(
selector: ArtboardSelector | ((artboard: ArtboardFacade) => boolean)
): ArtboardFacade | null {
if (typeof selector === 'function') {
return this.getArtboards().find(selector) || null
}
const entity = this._getDesignEntity()
const artboardEntity = entity.findArtboard(selector)
return artboardEntity ? this.getArtboardById(artboardEntity.id) : null
}
/**
* Looks up all artboard objects matching the provided criteria.
*
* @category Artboard Lookup
* @param selector An artboard selector. All specified fields must be matched by the results.
* @returns An artboard list.
*
* @example
* ```typescript
* const productArtboards = design.findArtboards({ name: /Product/i })
* const productArtboards = design.findArtboards((artboard) => /Product/i.test(artboard.name))
* const artboards123 = design.findArtboards({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findArtboards(
selector: ArtboardSelector | ((artboard: ArtboardFacade) => boolean)
): Array<ArtboardFacade> {
if (typeof selector === 'function') {
return this.getArtboards().filter((artboard) => selector(artboard))
}
const entity = this._getDesignEntity()
const artboardEntities = entity.findArtboards(selector)
return artboardEntities
.map((artboardEntity) => {
return this.getArtboardById(artboardEntity.id)
})
.filter(Boolean) as Array<ArtboardFacade>
}
/**
* Looks up the first artboard object matching the provided criteria.
*
* @category Page Lookup
* @param selector A page selector. All specified fields must be matched by the result.
* @returns A page object.
*
* @example
* ```typescript
* const mobilePage = design.findPage({ name: /mobile/i })
* const mobilePage = design.findPage((page) => /mobile/i.test(page.name))
* const oneOfPages123 = design.findPage({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findPage(
selector: PageSelector | ((page: PageFacade) => boolean)
): PageFacade | null {
if (typeof selector === 'function') {
return this.getPages().find(selector) || null
}
const entity = this._getDesignEntity()
const pageEntity = entity.findPage(selector)
return pageEntity ? this.getPageById(pageEntity.id) : null
}
/**
* Looks up all artboard objects matching the provided criteria.
*
* @category Page Lookup
* @param selector A page selector. All specified fields must be matched by the results.
* @returns A page list.
*
* @example
* ```typescript
* const mobilePages = design.findPages({ name: /mobile/i })
* const mobilePages = design.findPages((page) => /mobile/i.test(page.name))
* const pages123 = design.findPages({ id: ['<ID1>', '<ID2>', '<ID3>'] })
* ```
*/
findPages(
selector: PageSelector | ((page: PageFacade) => boolean)
): Array<PageFacade> {
if (typeof selector === 'function') {
return this.getPages().filter((page) => selector(page))
}
const entity = this._getDesignEntity()
const pageEntities = entity.findPages(selector)
return pageEntities
.map((pageEntity) => {
return this.getPageById(pageEntity.id)
})
.filter(Boolean) as Array<PageFacade>
}
/**
* Returns a collection of all layers from all pages and artboards (optionally down to a specific nesting level).
*
* The produced collection can be queried further for narrowing down the search.
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param options Object
* @param options.depth The maximum nesting level of layers within pages and artboards to include in the collection. By default, all levels are included. `0` also means "no limit"; `1` means only root layers in artboards should be included.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer collection with the flattened layers.
*
* @example All layers from all artboards
* ```typescript
* const layers = await design.getFlattenedLayers()
* ```
*
* @example Root layers from all artboards
* ```typescript
* const rootLayers = await design.getFlattenedLayers({ depth: 1 })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layers = await design.getFlattenedLayers({ cancelToken: token })
* ```
*/
async getFlattenedLayers(
options: { depth?: number; cancelToken?: CancelToken | null } = {}
): Promise<LayerCollectionFacade> {
await this.load({ cancelToken: options.cancelToken || null })
const entity = this._getDesignEntity()
const layerCollection = entity.getFlattenedLayers({
depth: options.depth || 0,
})
return new LayerCollectionFacade(layerCollection, {
designFacade: this,
})
}
/**
* Returns the first layer object which has the specified ID.
*
* Layer IDs are unique within individual artboards but different artboards can potentially have layer ID clashes. This is the reason the method is not prefixed with "get".
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param layerId A layer ID.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer object.
*
* @example
* ```typescript
* const layer = await design.findLayerById('<ID>')
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await design.findLayerById('<ID>', { cancelToken: token })
* ```
*/
async findLayerById(
layerId: LayerId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerFacade | null> {
await this.load(options)
const entity = this._getDesignEntity()
const layerEntity = entity.findLayerById(layerId)
const artboardId = layerEntity ? layerEntity.artboardId : null
if (!layerEntity || !artboardId) {
return null
}
return this.getArtboardLayerFacade(artboardId, layerEntity.id)
}
/**
* Returns a collection of all layer objects which have the specified ID.
*
* Layer IDs are unique within individual artboards but different artboards can potentially have layer ID clashes.
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param layerId A layer ID.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer collection with layer matches.
*
* @example
* ```typescript
* const layers = await design.findLayersById('<ID>')
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layers = await design.findLayersById('<ID>', { cancelToken: token })
* ```
*/
async findLayersById(
layerId: LayerId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerCollectionFacade> {
await this.load(options)
const entity = this._getDesignEntity()
const layerCollection = entity.findLayersById(layerId)
return new LayerCollectionFacade(layerCollection, {
designFacade: this,
})
}
/**
* Returns the first layer object from any page or artboard (optionally down to a specific nesting level) matching the specified criteria.
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param selector A design-wide layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A matched layer object.
*
* @example Layer by name from any artboard
* ```typescript
* const layer = await design.findLayer({ name: 'Share icon' })
* ```
*
* @example Layer by function selector from any artboard
* ```typescript
* const shareIconLayer = await design.findLayer((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Layer by name from a certain artboard subset
* ```typescript
* const layer = await design.findLayer({
* name: 'Share icon',
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await design.findLayer(
* { name: 'Share icon' },
* { cancelToken: token }
* )
* ```
*/
async findLayer(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number; cancelToken?: CancelToken | null } = {}
): Promise<LayerFacade | null> {
await this.load({ cancelToken: options.cancelToken || null })
const entitySelector = createLayerEntitySelector(this, selector)
const entity = this._getDesignEntity()
const layerEntity = entity.findLayer(entitySelector, {
depth: options.depth || 0,
})
const artboardId = layerEntity ? layerEntity.artboardId : null
if (!layerEntity || !artboardId) {
return null
}
return this.getArtboardLayerFacade(artboardId, layerEntity.id)
}
/**
* Returns a collection of all layer objects from all pages and artboards (optionally down to a specific nesting level) matching the specified criteria.
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Layer Lookup
* @param selector A design-wide layer selector. All specified fields must be matched by the result.
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer collection with layer matches.
*
* @example Layers by name from all artboards
* ```typescript
* const layers = await design.findLayers({ name: 'Share icon' })
* ```
*
* @example Layers by function selector from all artboards
* ```typescript
* const shareIconLayers = await design.findLayers((layer) => {
* return layer.name === 'Share icon'
* })
* ```
*
* @example Invisible layers from all a certain artboard subset
* ```typescript
* const layers = await design.findLayers({
* visible: false,
* artboardId: [ '<ID1>', '<ID2>' ],
* })
* ```
*
* @example With timeout
* ```typescript
* const { cancel, token } = createCancelToken()
* setTimeout(cancel, 5000) // Throw an OperationCancelled error in 5 seconds.
* const layer = await design.findLayers(
* { type: 'shapeLayer' },
* { cancelToken: token }
* )
* ```
*/
async findLayers(
selector: DesignLayerSelector | ((layer: LayerFacade) => boolean),
options: { depth?: number; cancelToken?: CancelToken | null } = {}
): Promise<LayerCollectionFacade> {
await this.load({ cancelToken: options.cancelToken || null })
const entitySelector = createLayerEntitySelector(this, selector)
const entity = this._getDesignEntity()
const layerCollection = entity.findLayers(entitySelector, {
depth: options.depth || 0,
})
return new LayerCollectionFacade(layerCollection, {
designFacade: this,
})
}
/**
* Returns a list of bitmap assets used by layers in all pages and artboards (optionally down to a specific nesting level).
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Asset
* @param options Options
* @param options.depth The maximum nesting level within page and artboard layers to search for bitmap asset usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.includePrerendered Whether to also include "pre-rendered" bitmap assets. These assets can be produced by the rendering engine (if configured; future functionality) but are available as assets for either performance reasons or due to the some required data (such as font files) potentially not being available. By default, pre-rendered assets are included.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A list of bitmap assets.
*
* @example All bitmap assets from all artboards
* ```typescript
* const bitmapAssetDescs = await design.getBitmapAssets()
* ```
*
* @example Bitmap assets excluding pre-rendered bitmaps from all artboards
* ```typescript
* const bitmapAssetDescs = await design.getBitmapAssets({
* includePrerendered: false,
* })
* ```
*/
async getBitmapAssets(
options: {
depth?: number
includePrerendered?: boolean
cancelToken?: CancelToken | null
} = {}
): Promise<
Array<
BitmapAssetDescriptor & {
artboardLayerIds: Record<ArtboardId, Array<LayerId>>
}
>
> {
await this.load({ cancelToken: options.cancelToken || null })
const entity = this._getDesignEntity()
return entity.getBitmapAssets({
depth: options.depth || 0,
includePrerendered: options.includePrerendered !== false,
})
}
/**
* Returns a list of fonts used by layers in all pages and artboards (optionally down to a specific nesting level).
*
* This method internally triggers loading of all pages and artboards. Uncached items are downloaded when the API is configured (and cached when the local cache is configured).
*
* @category Asset
* @param options.depth The maximum nesting level within page and artboard layers to search for font usage. By default, all levels are searched. `0` also means "no limit"; `1` means only root layers in artboards should be searched.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @param options Options
* @returns A list of fonts.
*
* @example All fonts from all artboards
* ```typescript
* const fontDescs = await design.getFonts()
* ```
*/
async getFonts(
options: { depth?: number; cancelToken?: CancelToken | null } = {}
): Promise<
Array<
FontDescriptor & { artboardLayerIds: Record<ArtboardId, Array<LayerId>> }
>
> {
await this.load({ cancelToken: options.cancelToken || null })
const entity = this._getDesignEntity()
return entity.getFonts({ depth: options.depth || 0 })
}
/** @internal */
setFontSource(fontSource: FontSource | null): void {
this._fontSource = fontSource
}
/**
* Sets the directory where fonts should be looked up when rendering the design.
*
* Fonts are matched based on their postscript names, not the file basenames.
*
* This configuration overrides the global font directory configuration (set up via {@link Sdk.setGlobalFontDirectory}) – i.e. fonts from the globally configured directory are not used for the design.
*
* This configuration is copied to any other versions of the design later obtained through this design object as the default font configuration.
*
* @category Configuration
* @param fontDirectoryPath An absolute path to a directory or a path relative to the process working directory (`process.cwd()` in node.js). When `null` is provided, the configuration is cleared for the design.
*
* @example
* ```typescript
* design.setFontDirectory('./custom-fonts')
* design.setFontDirectory('/var/custom-fonts')
* ```
*/
setFontDirectory(fontDirectoryPath: string): void {
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error(
'Cannot set the font directory when the rendering engine is not configured'
)
}
renderingDesign.setFontDirectory(fontDirectoryPath)
const fontSource = this._fontSource
if (fontSource) {
fontSource.setFontDirectory(fontDirectoryPath)
}
}
/**
* Sets the fonts which should be used as a fallback in case the actual fonts needed for rendering text layers are not available.
*
* The first font from this list which is available in the system is used for all text layers with missing actual fonts. If none of the fonts are available, the text layers are not rendered.
*
* This configuration overrides/extends the global configuration set via {@link Sdk.setGlobalFallbackFonts}. Fonts specified here are preferred over the global config.
*
* This configuration is copied to any other versions of the design later obtained through this design object as the default font configuration.
*
* @category Configuration
* @param fallbackFonts An ordered list of font postscript names or font file paths.
*
* @example
* ```typescript
* design.setFallbackFonts([ 'Calibri', './custom-fonts/Carolina.otf', 'Arial' ])
* ```
*/
setFallbackFonts(fallbackFonts: Array<string>): void {
const fontSource = this._fontSource
if (fontSource) {
fontSource.setFallbackFonts(fallbackFonts)
}
}
/**
* Renders the specified artboard as an PNG image file.
*
* All visible layers from the artboard are included.
*
* Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param artboardId The ID of the artboard to render.
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.bounds The area (in the coordinate system of the artboard) to include. This can be used to either crop or expand (add empty space to) the default artboard area.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x, whole artboard area)
* ```typescript
* await design.renderArtboardToFile('<ARTBOARD_ID>', './rendered/artboard.png')
* ```
*
* @example With custom scale and crop
* ```typescript
* await design.renderArtboardToFile('<ARTBOARD_ID>', './rendered/artboard.png', {
* scale: 4,
* // The result is going to have the dimensions of 400x200 due to the 4x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* })
* ```
*/
async renderArtboardToFile(
artboardId: ArtboardId,
filePath: string,
options: {
scale?: number
bounds?: Bounds
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: true,
cancelToken: options.cancelToken || null,
})
await renderingDesign.renderArtboardToFile(artboardId, filePath, options)
}
/**
* Renders all artboards from the specified page as a single PNG image file.
*
* All visible layers from the artboards are included.
*
* Uncached items (artboard contents and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param pageId The ID of the page to render.
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.bounds The area (in the coordinate system of the page) to include. This can be used to either crop or expand (add empty space to) the default page area.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x, whole page area)
* ```typescript
* await design.renderPageToFile('<PAGE_ID>', './rendered/page.png')
* ```
*
* @example With custom scale and crop
* ```typescript
* await design.renderPageToFile('<PAGE_ID>', './rendered/page.png', {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* })
* ```
*/
async renderPageToFile(
pageId: PageId,
filePath: string,
options: {
scale?: number
bounds?: Bounds
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
await this._loadRenderingDesignPage(pageId, { loadAssets: true })
await renderingDesign.renderPageToFile(pageId, filePath, options)
}
/**
* Renders the specified layer from the specified artboard as an PNG image file.
*
* In case of group layers, all visible nested layers are also included.
*
* Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param artboardId The ID of the artboard from which to render the layer.
* @param layerId The ID of the artboard layer to render.
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.blendingMode The blending mode to use for rendering the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeComponentBackground Whether to render the component background from the main/master component. By default, the configuration from the main/master component is used. Note that this configuration has no effect when the artboard background is not included via explicit `includeComponentBackground=true` nor the main/master component configuration as there is nothing with which to blend the layer.
* @param options.includeEffects Whether to apply layer effects of the layer. Rendering of effects of nested layers is not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.bounds The area (in the coordinate system of the artboard) to include. This can be used to either crop or expand (add empty space to) the default layer area.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example
* ```typescript With default options (1x, whole layer area)
* await design.renderArtboardLayerToFile(
* '<ARTBOARD_ID>',
* '<LAYER_ID>',
* './rendered/layer.png'
* )
* ```
*
* @example With custom scale and crop and using the component background color
* ```typescript
* await design.renderArtboardLayerToFile(
* '<ARTBOARD_ID>',
* '<LAYER_ID>',
* './rendered/layer.png',
* {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* includeComponentBackground: true,
* }
* )
* ```
*/
async renderArtboardLayerToFile(
artboardId: ArtboardId,
layerId: LayerId,
filePath: string,
options: {
includeEffects?: boolean
clip?: boolean
includeComponentBackground?: boolean
blendingMode?: BlendingMode
opacity?: number
bounds?: Bounds
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const { bounds, scale, cancelToken = null, ...layerAttributes } = options
await this.renderArtboardLayersToFile(artboardId, [layerId], filePath, {
...(bounds ? { bounds } : {}),
scale: scale || 1,
layerAttributes: { [layerId]: layerAttributes },
cancelToken,
})
}
/**
* Renders the specified layers from the specified artboard as a single composed PNG image file.
*
* In case of group layers, all visible nested layers are also included.
*
* Uncached items (artboard content and bitmap assets of rendered layers) are downloaded and cached.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Rendering
* @param artboardId The ID of the artboard from which to render the layers.
* @param layerIds The IDs of the artboard layers to render.
* @param filePath The target location of the produced PNG image file.
* @param options Render options
* @param options.bounds The area (in the coordinate system of the artboard) to include. This can be used to either crop or expand (add empty space to) the default layer area.
* @param options.scale The scale (zoom) factor to use for rendering instead of the default 1x factor.
* @param options.layerAttributes Layer-specific options to use for the rendering instead of the default values.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x, whole combined layer area)
* ```typescript
* await design.renderArtboardLayersToFile(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>'],
* './rendered/layers.png'
* )
* ```
*
* @example With custom scale and crop and using the custom layer configuration
* ```typescript
* await design.renderArtboardLayersToFile(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>'],
* './rendered/layers.png',
* {
* scale: 2,
* // The result is going to have the dimensions of 400x200 due to the 2x scale.
* bounds: { left: 100, top: 0, width: 100, height: 50 },
* layerAttributes: {
* '<LAYER1>': { blendingMode: 'SOFT_LIGHT', includeComponentBackground: true },
* '<LAYER2>': { opacity: 0.6 },
* }
* }
* )
* ```
*/
async renderArtboardLayersToFile(
artboardId: ArtboardId,
layerIds: Array<LayerId>,
filePath: string,
options: {
layerAttributes?: Record<string, LayerAttributesConfig>
scale?: number
bounds?: Bounds
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
const { cancelToken = null, ...layerOptions } = options
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: false,
cancelToken,
})
const resolvedLayerSubtrees = await Promise.all(
layerIds.map((layerId) => {
return this._resolveVisibleArtboardLayerSubtree(artboardId, layerId, {
cancelToken,
})
})
)
const resolvedLayerIds = resolvedLayerSubtrees.flat(1)
if (resolvedLayerIds.length === 0) {
throw new Error('No such layer')
}
const bitmapAssetDescs = (
await Promise.all(
layerIds.map(async (layerId) => {
const layer = await artboard.getLayerById(layerId, { cancelToken })
return layer ? layer.getBitmapAssets() : []
})
)
).flat(1)
const fonts = (
await Promise.all(
layerIds.map(async (layerId) => {
const layer = await artboard.getLayerById(layerId, { cancelToken })
return layer ? layer.getFonts() : []
})
)
).flat(1)
await Promise.all([
this.downloadBitmapAssets(bitmapAssetDescs, { cancelToken }),
this._loadFontsToRendering(fonts, { cancelToken }),
])
await renderingDesign.markArtboardAsReady(artboardId)
cancelToken?.throwIfCancelled()
await renderingDesign.renderArtboardLayersToFile(
artboardId,
resolvedLayerIds,
filePath,
layerOptions
)
}
/**
* Returns an SVG document string of the specified layer from the specified artboard.
*
* In case of group layers, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG Export
* @param artboardId The ID of the artboard from which to export the layer.
* @param layerId The IDs of the artboard layer to export.
* @param options Export options
* @param options.blendingMode The blending mode to use for the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeEffects Whether to apply layer effects of the layer. Effects of nested layers are not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.scale The scale (zoom) factor to use instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns An SVG document string.
*
* @example With default options (1x)
* ```typescript
* const svg = await design.exportArtboardLayerToSvgCode(
* '<ARTBOARD_ID>',
* '<LAYER_ID>'
* )
* ```
*
* @example With custom scale and opacity
* ```typescript
* const svg = await design.exportArtboardLayerToSvgCode(
* '<ARTBOARD_ID>',
* '<LAYER_ID>',
* {
* opacity: 0.6,
* scale: 2,
* }
* )
* ```
*/
async exportArtboardLayerToSvgCode(
artboardId: ArtboardId,
layerId: LayerId,
options: {
includeEffects?: boolean
clip?: boolean
blendingMode?: BlendingMode
opacity?: number
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<string> {
const { scale = 1, cancelToken = null, ...layerAttributes } = options
return this.exportArtboardLayersToSvgCode(artboardId, [layerId], {
scale,
cancelToken,
layerAttributes: { [layerId]: layerAttributes },
})
}
/**
* Exports the specified layer from the specified artboard as an SVG file.
*
* In case of group layers, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG Export
* @param artboardId The ID of the artboard from which to export the export.
* @param layerId The IDs of the artboard layer to export.
* @param filePath The target location of the produced SVG file.
* @param options Export options.
* @param options.blendingMode The blending mode to use for the layer instead of its default blending mode.
* @param options.clip Whether to apply clipping by a mask layer if any such mask is set for the layer (see {@link LayerFacade.isMasked}). Clipping is disabled by default. Setting this flag for layers which do not have a mask layer set has no effect on the results.
* @param options.includeEffects Whether to apply layer effects of the layer. Effects of nested layers are not affected. By defaults, effects of the layer are applied.
* @param options.opacity The opacity to use for the layer instead of its default opacity.
* @param options.scale The scale (zoom) factor to use instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x)
* ```typescript
* await design.exportArtboardLayerToSvgFile(
* '<ARTBOARD_ID>',
* '<LAYER_ID>',
* './layer.svg'
* )
* ```
*
* @example With custom scale and opacity
* ```typescript
* await design.exportArtboardLayerToSvgFile(
* '<ARTBOARD_ID>',
* '<LAYER_ID>',
* './layer.svg',
* {
* opacity: 0.6,
* scale: 2,
* }
* )
* ```
*/
async exportArtboardLayerToSvgFile(
artboardId: ArtboardId,
layerId: LayerId,
filePath: string,
options: {
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const svg = await this.exportArtboardLayerToSvgCode(
artboardId,
layerId,
options
)
await this._sdk.saveTextFile(filePath, svg, {
cancelToken: options.cancelToken,
})
}
/**
* Returns an SVG document string of the specified layers from the specified artboard.
*
* In case of group layers, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG Export
* @param artboardId The ID of the artboard from which to export the layers.
* @param layerIds The IDs of the artboard layers to export.
* @param options Export options.
* @param options.layerAttributes Layer-specific options to use for instead of the default values.
* @param options.scale The scale (zoom) factor to use instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns An SVG document string.
*
* @example With default options (1x)
* ```typescript
* const svg = await design.exportArtboardLayersToSvgCode(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>']
* )
* ```
*
* @example With custom scale
* ```typescript
* const svg = await design.exportArtboardLayersToSvgCode(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>'],
* {
* scale: 2,
* layerAttributes: {
* '<LAYER1>': { blendingMode: 'SOFT_LIGHT' },
* '<LAYER2>': { opacity: 0.6 },
* }
* }
* )
* ```
*/
async exportArtboardLayersToSvgCode(
artboardId: ArtboardId,
layerIds: Array<LayerId>,
options: {
layerAttributes?: Record<LayerId, LayerOctopusAttributesConfig>
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<string> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const { layerAttributes = {}, scale = 1, cancelToken = null } = options
await artboard.load({ cancelToken })
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
const data = await layerIds.reduce(
async (prevResultPromise, layerId) => {
const [prevResult, layer] = await Promise.all([
prevResultPromise,
artboard.getLayerById(layerId, { cancelToken }),
])
if (!layer) {
return prevResult
}
const parentLayers = layer.getParentLayers().getLayers()
return {
bitmapAssetDescs: prevResult.bitmapAssetDescs.concat(
layer.getBitmapAssets()
),
fonts: prevResult.fonts.concat(layer.getFonts()),
parentLayers: parentLayers.reduce((layers, parentLayer) => {
return {
...layers,
[parentLayer.id]: parentLayer.getOctopusForAttributes(
layerAttributes[parentLayer.id] || {}
),
}
}, prevResult.parentLayers),
parentLayerIds: {
...prevResult.parentLayerIds,
[layerId]: layer.getParentLayerIds(),
},
layerOctopusDataList: prevResult.layerOctopusDataList.concat([
layer.getOctopusForAttributes(layerAttributes[layer.id] || {}),
]),
}
},
Promise.resolve({
bitmapAssetDescs: [] as Array<BitmapAssetDescriptor>,
fonts: [] as Array<FontDescriptor>,
parentLayers: {} as Record<LayerId, LayerOctopusData>,
parentLayerIds: {} as Record<LayerId, Array<LayerId>>,
layerOctopusDataList: [] as Array<LayerOctopusData>,
})
)
const [bitmapAssetFilenames] = await Promise.all([
this.downloadBitmapAssets(data.bitmapAssetDescs, { cancelToken }),
this._loadFontsToRendering(data.fonts, { cancelToken }),
])
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: false,
cancelToken,
})
const viewBoxBounds = await renderingDesign.getArtboardLayerCompositionBounds(
artboardId,
layerIds,
{ scale, layerAttributes }
)
return this._sdk.exportLayersToSvgCode(data.layerOctopusDataList, {
scale,
parentLayerIds: data.parentLayerIds,
parentLayers: data.parentLayers,
viewBoxBounds,
bitmapAssetFilenames,
cancelToken,
})
}
/**
* Export the specified layers from the specified artboard as an SVG file.
*
* In case of group layers, all visible nested layers are also included.
*
* Bitmap assets are serialized as base64 data URIs.
*
* Uncached items (artboard content and bitmap assets of exported layers) are downloaded and cached.
*
* The SVG exporter has to be configured when using this methods. The local cache has to also be configured when working with layers with bitmap assets.
*
* @category SVG Export
* @param artboardId The ID of the artboard from which to export the layers.
* @param layerIds The IDs of the artboard layers to export.
* @param filePath The target location of the produced SVG file.
* @param options Export options
* @param options.layerAttributes Layer-specific options to use for instead of the default values.
* @param options.scale The scale (zoom) factor to use instead of the default 1x factor.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
*
* @example With default options (1x)
* ```typescript
* await design.exportArtboardLayersToSvgFile(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>'],
* './layers.svg'
* )
* ```
*
* @example With custom scale
* ```typescript
* await design.exportArtboardLayersToSvgFile(
* '<ARTBOARD_ID>',
* ['<LAYER1>', '<LAYER2>'],
* './layers.svg',
* {
* scale: 2,
* layerAttributes: {
* '<LAYER1>': { blendingMode: 'SOFT_LIGHT' },
* '<LAYER2>': { opacity: 0.6 },
* }
* }
* )
* ```
*/
async exportArtboardLayersToSvgFile(
artboardId: ArtboardId,
layerIds: Array<LayerId>,
filePath: string,
options: {
scale?: number
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const svg = await this.exportArtboardLayersToSvgCode(
artboardId,
layerIds,
options
)
await this._sdk.saveTextFile(filePath, svg, {
cancelToken: options.cancelToken,
})
}
/**
* Returns the bounds of the specified artboard.
*
* The API has to be configured when using this method to get bounds of an uncached artboard.
*
* @category Data
* @param options Options
* @param artboardId The ID of the artboard to inspect.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns The artboard bounds.
*
* @example
* ```typescript
* const artboardBounds = await design.getArtboardBounds('<ARTBOARD_ID>')
* ```
*/
async getArtboardBounds(
artboardId: ArtboardId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<Bounds> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
return artboard.getBounds(options)
}
/**
* Returns various bounds of the specified layer.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Data
* @param artboardId The ID of the artboard from which to inspect the layer.
* @param layerId The ID of the layer to inspect.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns Various layer bounds.
*
* @example
* ```typescript
* const layerBounds = await design.getArtboardLayerBounds('<ARTBOARD_ID>', '<LAYER_ID>')
* const boundsWithEffects = layerBounds.fullBounds
* ```
*/
async getArtboardLayerBounds(
artboardId: ArtboardId,
layerId: LayerId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerBounds> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
const layer = await artboard.getLayerById(layerId, options)
if (!layer) {
throw new Error('No such layer')
}
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: false,
...options,
})
const fonts = layer.getFonts()
await this._loadFontsToRendering(fonts, options)
return renderingDesign.getArtboardLayerBounds(artboardId, layerId)
}
/**
* Returns the attributes of the spececified layer.
*
* @category Data
* @param artboardId The ID of the artboard from which to inspect the layer.
* @param layerId The ID of the layer to inspect.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns Layer attributes.
*
* @example
* ```typescript
* const attrs = await design.getArtboardLayerAttributes('<ARTBOARD_ID>', '<LAYER_ID>')
* const { blendingMode, opacity, visible } = attrs
* ```
*/
async getArtboardLayerAttributes(
artboardId: ArtboardId,
layerId: LayerId,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerAttributes> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const layer = await artboard.getLayerById(layerId, options)
if (!layer) {
throw new Error('No such layer')
}
return layer.getAttributes()
}
/**
* Returns the top-most layer located at the specified coordinates within the specified artboard.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Layer Lookup
* @param artboardId The ID of the artboard from which to render the layer.
* @param x The X coordinate in the coordinate system of the artboard where to look for a layer.
* @param y The Y coordinate in the coordinate system of the artboard where to look for a layer.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer object.
*
* @example
* ```typescript
* const layerId = await design.getArtboardLayerAtPosition('<ARTBOARD_ID>', 100, 200)
* ```
*/
async getArtboardLayerAtPosition(
artboardId: ArtboardId,
x: number,
y: number,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<LayerFacade | null> {
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: true,
...options,
})
const layerId = await renderingDesign.getArtboardLayerAtPosition(
artboardId,
x,
y
)
return layerId ? this.getArtboardLayerFacade(artboardId, layerId) : null
}
/**
* Returns all layers located within the specified area of the the specified artboard.
*
* The rendering engine and the local cache have to be configured when using this method.
*
* @category Layer Lookup
* @param artboardId The ID of the artboard from which to render the layer.
* @param bounds The area in the corrdinate system of the artboard where to look for layers.
* @param options Options
* @param options.partialOverlap Whether to also return layers which are only partially contained within the specified area.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. newly cached artboards are not uncached). A cancellation token can be created via {@link createCancelToken}.
* @returns A layer list.
*
* @example Layers fully contained in the area
* ```typescript
* const layerIds = await design.getArtboardLayersInArea(
* '<ARTBOARD_ID>',
* { left: 80, top: 150, width: 40, height: 30 }
* )
* ```
*
* @example Layers fully or partially contained in the area
* ```typescript
* const layerIds = await design.getArtboardLayersInArea(
* '<ARTBOARD_ID>',
* { left: 80, top: 150, width: 40, height: 30 },
* { partialOverlap: true }
* )
* ```
*/
async getArtboardLayersInArea(
artboardId: ArtboardId,
bounds: Bounds,
options: {
partialOverlap?: boolean
cancelToken?: CancelToken | null
} = {}
): Promise<Array<LayerFacade>> {
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
const { cancelToken = null, ...layerOptions } = options
await this._loadRenderingDesignArtboard(artboardId, {
loadAssets: true,
cancelToken,
})
const layerIds = await renderingDesign.getArtboardLayersInArea(
artboardId,
bounds,
layerOptions
)
return layerIds.flatMap((layerId) => {
const layerFacade = this.getArtboardLayerFacade(artboardId, layerId)
return layerFacade ? [layerFacade] : []
})
}
/** @internal */
getArtboardLayerFacade(
artboardId: ArtboardId,
layerId: LayerId
): LayerFacade | null {
const artboardFacade = this.getArtboardById(artboardId)
return artboardFacade ? artboardFacade.getLayerFacadeById(layerId) : null
}
/** @internal */
async load(options: { cancelToken?: CancelToken | null }): Promise<void> {
const artboards = this.getArtboards()
await Promise.all(
artboards.map((artboard) => {
return artboard.load(options)
})
)
}
/** @internal */
async loadArtboard(
artboardId: ArtboardId,
options: {
cancelToken?: CancelToken | null
}
): Promise<ArtboardFacade> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const prevArtboardLoadingPromise = this._loadingArtboardPromises.get(
artboardId
)
if (prevArtboardLoadingPromise) {
await prevArtboardLoadingPromise
} else if (!artboard.isLoaded()) {
// NOTE: Maybe use the Octopus Reader file entity instead for clearer source of truth.
const artboardEntity = artboard.getArtboardEntity()
const artboardLoadingPromise = this._loadArtboardContent(
artboardId,
options
).then((content) => {
artboardEntity.setOctopus(content)
})
this._loadingArtboardPromises.set(artboardId, artboardLoadingPromise)
await artboardLoadingPromise
}
return artboard
}
/**
* Releases all loaded data of the design from memory. The design object is no longer usable after this.
*
* If it is only desired to clean loaded data from memory while keeping the object usable, call {@link DesignFacade.unload} instead.
*
* @category Status
*/
async destroy(): Promise<void> {
this._designEntity = null
this._getDesignEntity.clear()
const localDesign = this._localDesign
if (localDesign) {
localDesign.unload()
}
const renderingDesign = this._renderingDesign
if (renderingDesign) {
await renderingDesign.destroy()
}
}
/**
* Releases all loaded data of the design from memory. The design object can be used for loading the data again later.
*
* @category Status
*/
async unload(): Promise<void> {
const designEntity = this._getDesignEntity()
designEntity.unloadArtboards()
const localDesign = this._localDesign
if (localDesign) {
localDesign.unload()
}
const renderingDesign = this._renderingDesign
if (renderingDesign) {
await renderingDesign.unloadArtboards()
}
}
/**
* Releases data related to the specified artboard from memory.
*
* @param artboardId The ID of the artboard to unload.
* @category Status
*/
async unloadArtboard(artboardId: ArtboardId): Promise<void> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
if (!artboard.isLoaded()) {
this._console.warn(
'Trying to unload an artboard which has not been loaded.'
)
return
}
const artboardEntity = artboard.getArtboardEntity()
artboardEntity.unload()
const renderingDesign = this._renderingDesign
if (renderingDesign) {
await renderingDesign.unloadArtboard(artboardId)
}
}
private async _loadArtboardContent(
artboardId: ArtboardId,
options: {
cancelToken?: CancelToken | null
}
): Promise<OctopusDocument> {
const localDesign = this._localDesign
const apiDesign = this._apiDesign
if (localDesign) {
if (!(await localDesign.hasArtboardContent(artboardId))) {
if (!apiDesign) {
throw new Error(
'The artboard is not locally available and the API is not configured'
)
}
const contentStream = await apiDesign.getArtboardContentJsonStream(
artboardId,
options
)
await localDesign.saveArtboardContentJsonStream(
artboardId,
contentStream,
options
)
}
return localDesign.getArtboardContent(artboardId, options)
}
if (!apiDesign) {
throw new Error('The artboard cannot be loaded')
}
return apiDesign.getArtboardContent(artboardId, options)
}
/**
* Downloads the specified bitmap assets to the local cache.
*
* Assets which have already been downloaded are skipped.
*
* The API and the local cache have to be configured when using this method.
*
* @category Asset
* @param bitmapAssetDescs A list of bitmap assets to download. When not provided, all bitmap assets of the design are downloaded.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the asset is not deleted from the disk). A cancellation token can be created via {@link createCancelToken}.
* @returns The locations of the bitmap assets within the file system. Keys of the produced object are the `name` values from the provided bitmap asset descriptors (or all bitmap asset names by default).
*
* @example Download all assets
* ```typescript
* const bitmapAssetFilenames = await design.downloadBitmapAssets()
* ```
*
* @example Download specific assets
* ```typescript
* const bitmapAssetDescs = await design.getBitmapAssets({ depth: 1 })
* const bitmapAssetFilenames = await design.downloadBitmapAssets(bitmapAssetDescs)
* ```
*/
async downloadBitmapAssets(
bitmapAssetDescs?: Array<BitmapAssetDescriptor>,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<Record<string, string>> {
bitmapAssetDescs = bitmapAssetDescs || (await this.getBitmapAssets())
const filenames = await sequence(
bitmapAssetDescs,
async (bitmapAssetDesc) => {
return this.downloadBitmapAsset(bitmapAssetDesc, options)
}
)
const bitmapAssetFilenames = {} as {
[K in BitmapAssetDescriptor['name']]: string
}
bitmapAssetDescs.forEach((bitmapAssetDesc, index) => {
const filename = filenames[index] as string
bitmapAssetFilenames[bitmapAssetDesc['name']] = filename
})
return bitmapAssetFilenames
}
/**
* Downloads the specified bitmap asset to the local cache.
*
* The API and the local cache have to be configured when using this method.
*
* @category Asset
* @param bitmapAssetDesc The bitmap asset to download.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. assets are not deleted from the disk). A cancellation token can be created via {@link createCancelToken}.
* @returns The location of the bitmap asset within the file system.
*
* @example
* ```typescript
* const bitmapAssetDescs = await design.getBitmapAssets({ depth: 1 })
* await Promise.all(bitmapAssetDescs.map(async (bitmapAssetDesc) => {
* return design.downloadBitmapAsset(bitmapAssetDesc)
* }))
* ```
*/
async downloadBitmapAsset(
bitmapAssetDesc: BitmapAssetDescriptor,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<string> {
const apiDesign = this._apiDesign
if (!apiDesign) {
throw new Error(
'The API is not configured, cannot download bitmap assets'
)
}
const localDesign = this._localDesign
if (!localDesign) {
throw new Error('The design is not configured to be a local file')
}
const { available, filename } = await localDesign.resolveBitmapAsset(
bitmapAssetDesc,
options
)
if (available) {
return filename
}
const bitmapAssetStream = await apiDesign.getBitmapAssetStream(
bitmapAssetDesc.name,
options
)
return localDesign.saveBitmapAssetStream(
bitmapAssetDesc,
bitmapAssetStream,
options
)
}
/**
* Returns the file system location of the specified bitmap asset if it is downloaded.
*
* The local cache has to be configured when using this method.
*
* @category Asset
* @param bitmapAssetDesc A list of bitmap assets to download.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected. A cancellation token can be created via {@link createCancelToken}.
* @returns The location of the bitmap asset. `null` is returned when the asset is not downloaded.
*
* @example
* ```typescript
* const bitmapAssetDescs = await design.getBitmapAssets({ depth: 1 })
*
* const downlodedBitmapAssetFilenames = []
* await Promise.all(bitmapAssetDescs.map(async (bitmapAssetDesc) => {
* const filename = design.getBitmapAssetFilename(bitmapAssetDesc)
* if (filename) {
* downlodedBitmapAssetFilenames.push(filename)
* }
* }))
* ```
*/
async getBitmapAssetFilename(
bitmapAssetDesc: BitmapAssetDescriptor,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<string | null> {
const localDesign = this._localDesign
if (!localDesign) {
throw new Error('The design is not configured to be a local file')
}
const { available, filename } = await localDesign.resolveBitmapAsset(
bitmapAssetDesc,
options
)
return available ? filename : null
}
/**
* Downloads all uncached pages, artboards and bitmap assets to the local `.octopus` file or the local cache.
*
* In case a new file path is provided for a design loaded from an existing `.octopus` file, all of its contents are copied to the new location and this method essentially serves the purpose of a "save as" action.
*
* The produced `.octopus` file preserves a reference to a server-side design.
*
* The design object switches to using the new location as the local `.octopus` file and considers the file a local cache.
*
* @internal
* @category Serialization
* @param options.filePath An absolute path of the target `.octopus` file or a path relative to the current working directory. When omitted, the open `.octopus` file location is used instead. The API has to be configured in case there are uncached items.
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. the created files are not deleted). A cancellation token can be created via {@link createCancelToken}.
*/
async saveOctopusFile(
options: { filePath?: string | null; cancelToken?: CancelToken | null } = {}
): Promise<void> {
const cancelToken = options.cancelToken || null
const localDesign = await this._getLocalDesign({
filePath: options.filePath || null,
cancelToken,
})
const apiDesign = this._apiDesign
const manifest = this.getManifest()
await localDesign.saveManifest(manifest, { cancelToken })
if (apiDesign) {
await localDesign.saveApiDesignInfo(
{
apiRoot: apiDesign.getApiRoot(),
designId: apiDesign.id,
},
{ cancelToken }
)
}
await Promise.all(
this.getArtboards().map(async (artboard) => {
const artboardOctopus = await artboard.getContent({ cancelToken })
if (!artboardOctopus) {
throw new Error('Artboard octopus not available')
}
await localDesign.saveArtboardContent(artboard.id, artboardOctopus, {
cancelToken,
})
})
)
await this.setLocalDesign(localDesign, { cancelToken })
const bitmapAssetDescs = await this.getBitmapAssets({ cancelToken })
await this.downloadBitmapAssets(bitmapAssetDescs, { cancelToken })
}
/**
* Downloads the design file of the specified format produced by a server-side design file export.
*
* In case no such export has been done for the design yet, a new export is initiated and the resulting design file is downloaded.
*
* @category Serialization
* @param filePath An absolute path to which to save the design file or a path relative to the current working directory.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected and side effects are not reverted (e.g. a partially downloaded file is not deleted). A cancellation token can be created via {@link createCancelToken}.
*
* @example Export a Figma design as a Sketch design file (the only supported conversion)
* ```typescript
* await design.exportDesignFile('./exports/design.sketch')
* ```
*/
async exportDesignFile(
filePath: string,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<void> {
const format = getDesignFormatByFileName(filePath)
if (!format) {
throw new Error('Unknown target design file format')
}
if (format !== 'sketch') {
throw new Error('Unsupported target design file format')
}
const designExport = await this.getExportToFormat(format, options)
await this._sdk.saveDesignFileStream(
filePath,
await designExport.getResultStream(options),
options
)
}
private async _getLocalDesign(params: {
filePath: string | null
cancelToken?: CancelToken | null
}): Promise<LocalDesign> {
const cancelToken = params.cancelToken || null
const localDesign = this._localDesign
if (!params.filePath) {
if (!localDesign) {
throw new Error('The design is not configured to be a local file')
}
return localDesign
}
if (localDesign) {
await localDesign.saveAs(params.filePath, { cancelToken })
return localDesign
}
const targetDesignFacade = await this._sdk.openOctopusFile(
params.filePath,
{ cancelToken }
)
const targetLocalDesign = targetDesignFacade.getLocalDesign()
if (!targetLocalDesign) {
throw new Error('Target location is not available')
}
return targetLocalDesign
}
/** @internal */
addDesignExport(designExport: DesignExportFacade): void {
const format = designExport.resultFormat
this._designExports.set(format, designExport)
}
/**
* Returns info about a design file of the specified format produced by a server-side design file format export.
*
* In case no such export has been done for the design yet, a new export is initiated and the resulting design file info is then returned.
*
* @category Serialization
* @param format The format to which the design should be exported.
* @param options Options
* @param options.cancelToken A cancellation token which aborts the asynchronous operation. When the token is cancelled, the promise is rejected. A cancellation token can be created via {@link createCancelToken}.
* @returns A design export object.
*
* @example
* ```typescript
* // Initiate/fetch an export of a Figma design to the Sketch format (the only supported conversion)
* const export = await design.getExportToFormat('sketch')
*
* // Optional step to get lower-level info
* const url = await export.getResultUrl()
* console.log('Downloading export:', url)
*
* // Download the exported Sketch design file
* await export.exportDesignFile('./exports/design.sketch')
* ```
*/
async getExportToFormat(
format: DesignExportTargetFormatEnum,
options: {
cancelToken?: CancelToken | null
} = {}
): Promise<DesignExportFacade> {
const prevExport = this._designExports.get(format)
if (prevExport) {
return prevExport
}
const apiDesign = this._apiDesign
if (!apiDesign) {
throw new Error('The API is not configured, cannot export the design')
}
const designExport = await apiDesign.exportDesign({
format,
cancelToken: options.cancelToken || null,
})
const designExportFacade = new DesignExportFacade(designExport, {
sdk: this._sdk,
})
this._designExports.set(format, designExportFacade)
return designExportFacade
}
private async _loadRenderingDesignPage(
pageId: string,
params: {
loadAssets: boolean
cancelToken?: CancelToken | null
}
) {
const pageArtboards = this.getPageArtboards(pageId)
await sequence(pageArtboards, (artboard) => {
return this._loadRenderingDesignArtboard(artboard.id, params)
})
}
private async _loadRenderingDesignArtboard(
artboardId: string,
params: {
loadAssets: boolean
cancelToken?: CancelToken | null
}
) {
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
if (renderingDesign.isArtboardReady(artboardId)) {
return
}
const localDesign = this._localDesign
if (!localDesign) {
throw new Error('Local cache is not configured')
}
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
const cancelToken = params.cancelToken || null
await artboard.load({ cancelToken })
const octopusFilename = await localDesign.getArtboardContentFilename(
artboardId,
{ cancelToken }
)
if (!octopusFilename) {
throw new Error('The artboard octopus location is not available')
}
const desc = await renderingDesign.loadArtboard(artboardId, {
octopusFilename,
symbolId: artboard.componentId,
pageId: artboard.pageId,
})
cancelToken?.throwIfCancelled()
// NOTE: This logic is more a future-proofing of the logic rather than a required step
// as the SDK works with "expanded" octopus documents only and there should thus not be
// any pending symbols.
await sequence(desc.pendingSymbolIds, async (componentId: string) => {
const componentArtboard = this.getArtboardByComponentId(componentId)
if (!componentArtboard) {
throw new Error('A dependency component artboard is not available')
}
return this._loadRenderingDesignArtboard(componentArtboard.id, params)
})
if (params.loadAssets) {
const bitmapAssetDescs = await artboard.getBitmapAssets()
cancelToken?.throwIfCancelled()
const fonts = await artboard.getFonts()
cancelToken?.throwIfCancelled()
await Promise.all([
this.downloadBitmapAssets(bitmapAssetDescs, { cancelToken }),
this._loadFontsToRendering(fonts, { cancelToken }),
])
}
await renderingDesign.markArtboardAsReady(artboardId)
cancelToken?.throwIfCancelled()
if (!renderingDesign.isArtboardReady(artboardId)) {
throw new Error('The artboard failed to be loaded to a ready state')
}
}
private async _loadFontsToRendering(
fonts: Array<{ fontPostScriptName: string }>,
options: {
cancelToken?: CancelToken | null
}
) {
const fontSource = this._fontSource
if (!fontSource) {
return
}
const renderingDesign = this._renderingDesign
if (!renderingDesign) {
throw new Error('The rendering engine is not configured')
}
await sequence(fonts, async ({ fontPostScriptName }) => {
const fontMatch = await fontSource.resolveFontPath(
fontPostScriptName,
options
)
if (fontMatch) {
await renderingDesign.loadFont(
fontPostScriptName,
fontMatch.fontFilename,
{ facePostscriptName: fontMatch.fontPostscriptName }
)
options.cancelToken?.throwIfCancelled()
} else {
this._console.warn(`Font not available: ${fontPostScriptName}`)
}
})
}
private _resolveVisibleArtboardLayerSubtree(
artboardId: ArtboardId,
layerId: LayerId,
options: {
cancelToken?: CancelToken | null
}
): Promise<Array<LayerId>> {
const artboard = this.getArtboardById(artboardId)
if (!artboard) {
throw new Error('No such artboard')
}
return artboard.resolveVisibleLayerSubtree(layerId, options)
}
} | the_stack |
import {SnapshotEdgeType, SnapshotNodeType, SnapshotSizeSummary, ILeakRoot, IPath, GrowthStatus, Log, OperationType} from '../common/interfaces';
import {default as HeapSnapshotParser, DataTypes} from './heap_snapshot_parser';
import {OneBitArray, TwoBitArray} from '../common/util';
import LeakRoot from './leak_root';
/**
* Represents a link in a heap path. Specified as a simple class to make it quick to construct and JSONable.
* TODO: Better terminology?
*/
class PathSegment implements IPathSegment {
constructor(public readonly type: PathSegmentType,
public readonly indexOrName: string | number) {}
}
/**
* Converts an edge into a heap path segment.
* @param edge
*/
function edgeToIPathSegment(edge: Edge): IPathSegment {
const pst = edge.pathSegmentType;
const name = pst === PathSegmentType.CLOSURE ? "__scope__" : edge.indexOrName;
return new PathSegment(edge.pathSegmentType, name);
}
/**
* Converts a sequence of edges from the heap graph into an IPath object.
* @param edges
*/
function edgePathToPath(edges: Edge[]): IPath {
return edges.filter(isNotHidden).map(edgeToIPathSegment);
}
/**
* Returns true if the given edge type is visible from JavaScript.
* @param edge
*/
function isNotHidden(edge: Edge): boolean {
// window.self is a special property in Chrome's heap snapshots that
// contains a variety of native objects, including the DOM. Failing
// to ignore it prevents BLeak from finding DOM leaks.
/*if (edge.indexOrName === "self" && edge.to.name === "Window" && edge.to.type === SnapshotNodeType.Native) {
return false;
}*/
if (edge.snapshotType === SnapshotEdgeType.Element && edge.to.type === SnapshotNodeType.Native) {
return false;
}
switch(edge.snapshotType) {
case SnapshotEdgeType.Internal:
// Keep around closure edges so we can convert them to __scope__.
return edge.indexOrName === "context";
case SnapshotEdgeType.Hidden:
case SnapshotEdgeType.Shortcut:
return false;
default:
return true;
}
}
/**
* Extracts a tree of growing heap paths from a series of leak roots and
* paths to said roots.
*
* Called before sending the leak roots to the BLeak agent for instrumentation.
*/
export function toPathTree(leakroots: ILeakRoot[]): IPathTrees {
const tree: IPathTrees = [];
function addPath(p: IPath, id: number, index = 0, children = tree): void {
if (p.length === 0) {
return;
}
const pathSegment = p[index];
const indexOrName = pathSegment.indexOrName;
const matches = children.filter((c) => c.indexOrName === indexOrName);
let recur: IPathTree;
if (matches.length > 0) {
recur = matches[0];
} else {
// Add to children list.
recur = <IPathTreeNotGrowing> Object.assign({
isGrowing: false,
children: []
}, pathSegment);
children.push(recur);
}
const next = index + 1;
if (next === p.length) {
(recur as IPathTreeGrowing).isGrowing = true;
(recur as IPathTreeGrowing).id = id;
} else {
addPath(p, id, next, recur.children);
}
}
leakroots.forEach((lr) => {
lr.paths.forEach((p) => {
if (p.length === 0) {
// It's a root path! Instrument $$$GLOBAL$$$.
addPath([{
type: PathSegmentType.PROPERTY,
indexOrName: "$$$GLOBAL$$$"
}], lr.id);
} else {
addPath(p, lr.id);
}
});
});
return tree;
}
// Edge brand
type EdgeIndex = number & { ___EdgeIndex: true };
// Node brand
type NodeIndex = number & { ___NodeIndex: true };
function shouldTraverse(edge: Edge, wantDom: boolean): boolean {
// HACK: Ignore <symbol> properties. There may be multiple properties
// with the name <symbol> in a heap snapshot. There does not appear to
// be an easy way to disambiguate them.
if (edge.indexOrName === "<symbol>") {
return false;
}
if (edge.snapshotType === SnapshotEdgeType.Internal) {
// Whitelist of internal edges we know how to follow.
switch (edge.indexOrName) {
case "elements":
case "table":
case "properties":
case "context":
return true;
default:
return wantDom && edge.to.name.startsWith("Document DOM");
}
} else if (edge.to.type === SnapshotNodeType.Synthetic) {
return edge.to.name === "(Document DOM trees)";
}
return true;
}
/**
* Returns a hash representing a particular edge as a child of the given parent.
* @param parent
* @param edge
*/
function hash(parent: Node, edge: Edge): string | number {
if (parent.type === SnapshotNodeType.Synthetic) {
return edge.to.name;
} else {
return edge.indexOrName;
}
}
/**
* PropagateGrowth (Figure 4 in the paper).
* Migrates a node's growth between heap snapshots. BLeak considers a path in the heap to be growing
* if the node at the path exhibits sustained growth (in terms of number of outgoing edges) between heap
* snapshots.
* @param oldG The old heap graph.
* @param oldGrowth Growth bits for the nodes in the old heap graph.
* @param newG The new heap graph.
* @param newGrowth Growth bits for the nodes in the new heap graph.
*/
function propagateGrowth(oldG: HeapGraph, oldGrowth: TwoBitArray, newG: HeapGraph, newGrowth: TwoBitArray): void {
const numNewNodes = newG.nodeCount;
let index = 0;
// We visit each new node at most once, forming an upper bound on the queue length.
// Pre-allocate for better performance.
let queue = new Uint32Array(numNewNodes << 1);
// Stores the length of queue.
let queueLength = 0;
// Only store visit bits for the new graph.
const visitBits = new OneBitArray(numNewNodes);
// Enqueues the given node pairing (represented by their indices in their respective graphs)
// into the queue. oldNodeIndex and newNodeIndex represent a node at the same edge shared between
// the graphs.
function enqueue(oldNodeIndex: NodeIndex, newNodeIndex: NodeIndex): void {
queue[queueLength++] = oldNodeIndex;
queue[queueLength++] = newNodeIndex;
}
// Returns a single item from the queue. (Called twice to remove a pair.)
function dequeue(): NodeIndex {
return queue[index++] as NodeIndex;
}
// 0 indicates the root node. Start at the root.
const oldNode = new Node(0 as NodeIndex, oldG);
const newNode = new Node(0 as NodeIndex, newG);
const oldEdgeTmp = new Edge(0 as EdgeIndex, oldG);
{
// Visit global roots by *node name*, not *edge name* as edges are arbitrarily numbered from the root node.
// These global roots correspond to different JavaScript contexts (e.g. IFrames).
const newUserRoots = newG.getGlobalRootIndices();
const oldUserRoots = oldG.getGlobalRootIndices();
const m = new Map<string, {o: number[], n: number[]}>();
for (let i = 0; i < newUserRoots.length; i++) {
newNode.nodeIndex = <any> newUserRoots[i];
const name = newNode.name;
let a = m.get(name);
if (!a) {
a = {o: [], n: []};
m.set(name, a);
}
a.n.push(newUserRoots[i]);
}
for (let i = 0; i < oldUserRoots.length; i++) {
oldNode.nodeIndex = <any> oldUserRoots[i];
const name = oldNode.name;
let a = m.get(name);
if (a) {
a.o.push(oldUserRoots[i]);
}
}
m.forEach((v) => {
let num = Math.min(v.o.length, v.n.length);
for (let i = 0; i < num; i++) {
enqueue(<any> v.o[i], <any> v.n[i]);
visitBits.set(v.n[i], true);
}
});
}
// The main loop, which is the essence of PropagateGrowth.
while (index < queueLength) {
const oldIndex = dequeue();
const newIndex = dequeue();
oldNode.nodeIndex = oldIndex;
newNode.nodeIndex = newIndex;
const oldNodeGrowthStatus: GrowthStatus = oldGrowth.get(oldIndex);
// Nodes are either 'New', 'Growing', or 'Not Growing'.
// Nodes begin as 'New', and transition to 'Growing' or 'Not Growing' after a snapshot.
// So if a node is neither new nor consistently growing, we don't care about it.
if ((oldNodeGrowthStatus === GrowthStatus.NEW || oldNodeGrowthStatus === GrowthStatus.GROWING) && oldNode.numProperties() < newNode.numProperties()) {
newGrowth.set(newIndex, GrowthStatus.GROWING);
}
// Visit shared children.
const oldEdges = new Map<string | number, EdgeIndex>();
if (oldNode.hasChildren) {
for (const it = oldNode.children; it.hasNext(); it.next()) {
const oldChildEdge = it.item();
oldEdges.set(hash(oldNode, oldChildEdge), oldChildEdge.edgeIndex);
}
}
if (newNode.hasChildren) {
for (const it = newNode.children; it.hasNext(); it.next()) {
const newChildEdge = it.item();
const oldEdge = oldEdges.get(hash(newNode, newChildEdge));
oldEdgeTmp.edgeIndex = oldEdge;
if (oldEdge !== undefined && !visitBits.get(newChildEdge.toIndex) &&
shouldTraverse(oldEdgeTmp, false) && shouldTraverse(newChildEdge, false)) {
visitBits.set(newChildEdge.toIndex, true);
enqueue(oldEdgeTmp.toIndex, newChildEdge.toIndex);
}
}
}
}
}
/**
* Tracks growth in the heap.
*/
export class HeapGrowthTracker {
private _stringMap: StringMap = new StringMap();
private _heap: HeapGraph = null;
private _growthStatus: TwoBitArray = null;
// DEBUG INFO; this information is shown in a heap explorer tool.
public _leakRefs: Uint16Array = null;
public _nonLeakVisits: OneBitArray = null;
public async addSnapshot(parser: HeapSnapshotParser, log: Log): Promise<void> {
const heap = await HeapGraph.Construct(parser, log, this._stringMap);
const growthStatus = new TwoBitArray(heap.nodeCount);
if (this._heap !== null) {
log.timeEvent(OperationType.PROPAGATE_GROWTH, () => {
// Initialize all new nodes to 'NOT_GROWING'.
// We only want to consider stable heap paths present from the first snapshot.
growthStatus.fill(GrowthStatus.NOT_GROWING);
// Merge graphs.
propagateGrowth(this._heap, this._growthStatus, heap, growthStatus);
});
}
// Keep new graph.
this._heap = heap;
this._growthStatus = growthStatus;
}
public getGraph(): HeapGraph {
return this._heap;
}
/**
* Implements FindLeakPaths (Figure 5 in the paper) and CalculateLeakShare (Figure 6 in the paper),
* as well as calculations for Retained Size and Transitive Closure Size (which we compare against in the paper).
*
* Returns paths through the heap to leaking nodes, along with multiple different types of scores to help
* developers prioritize them, grouped by the leak root responsible.
*/
public findLeakPaths(log: Log): LeakRoot[] {
// A map from growing nodes to heap paths that reference them.
const growthPaths = new Map<NodeIndex, Edge[][]>();
// Adds a given path to growthPaths.
function addPath(e: Edge[]): void {
const to = e[e.length - 1].toIndex;
let paths = growthPaths.get(to);
if (paths === undefined) {
paths = [];
growthPaths.set(to, paths);
}
paths.push(e);
}
// Filter out DOM nodes and hidden edges that represent internal V8 / Chrome state.
function filterNoDom(n: Node, e: Edge) {
return isNotHidden(e) && nonWeakFilter(n, e) && shouldTraverse(e, false);
}
// Filter out hidden edges that represent internal V8 / Chrome state, but keep DOM nodes.
function filterIncludeDom(n: Node, e: Edge) {
return nonWeakFilter(n, e) && shouldTraverse(e, true);
}
log.timeEvent(OperationType.FIND_LEAK_PATHS, () => {
// Get the growing paths. Ignore paths through the DOM, as we mirror those in JavaScript.
// (See Section 5.3.2 in the paper, "Exposing Hidden State")
this._heap.visitGlobalEdges((e, getPath) => {
if (this._growthStatus.get(e.toIndex) === GrowthStatus.GROWING) {
addPath(getPath());
}
}, filterNoDom);
});
// Now, calculate growth metrics!
return log.timeEvent(OperationType.CALCULATE_METRICS, () => {
// Mark items that are reachable by non-leaks.
const nonleakVisitBits = new OneBitArray(this._heap.nodeCount);
this._heap.visitUserRoots((n) => {
nonleakVisitBits.set(n.nodeIndex, true);
}, (n, e) => {
// Filter out edges to growing objects.
// Traverse the DOM this time.
return filterIncludeDom(n, e) && !growthPaths.has(e.toIndex);
});
// Filter out items that are reachable from non-leaks.
function nonLeakFilter(n: Node, e: Edge): boolean {
return filterIncludeDom(n, e) && !nonleakVisitBits.get(e.toIndex);
}
// Increment visit counter for each heap item reachable from a leak.
// Used by LeakShare.
const leakReferences = new Uint16Array(this._heap.nodeCount);
growthPaths.forEach((paths, growthNodeIndex) => {
bfsVisitor(this._heap, [growthNodeIndex], (n) => {
leakReferences[n.nodeIndex]++;
}, nonLeakFilter);
});
// Calculate final growth metrics (LeakShare, Retained Size, Transitive Closure Size)
// for each LeakPath, and construct LeakRoot objects representing each LeakRoot.
let rv = new Array<LeakRoot>();
growthPaths.forEach((paths, growthNodeIndex) => {
let retainedSize = 0;
let leakShare = 0;
let transitiveClosureSize = 0;
let ownedObjects = 0;
bfsVisitor(this._heap, [growthNodeIndex], (n) => {
const refCount = leakReferences[n.nodeIndex];
if (refCount === 1) {
// A refCount of 1 means the heap item is uniquely referenced by this leak,
// so it contributes to retainedSize.
retainedSize += n.size;
ownedObjects++;
}
leakShare += n.size / refCount;
}, nonLeakFilter);
// Transitive closure size, for comparison to related work.
bfsVisitor(this._heap, [growthNodeIndex], (n) => {
transitiveClosureSize += n.size;
}, filterIncludeDom);
rv.push(new LeakRoot(growthNodeIndex, paths.map(edgePathToPath), {
retainedSize,
leakShare,
transitiveClosureSize,
ownedObjects
}));
});
// DEBUG
this._leakRefs = leakReferences;
this._nonLeakVisits = nonleakVisitBits;
return rv;
});
}
public isGrowing(nodeIndex: number): boolean {
return this._growthStatus.get(nodeIndex) === GrowthStatus.GROWING;
}
}
/**
* Map from ID => string.
*/
class StringMap {
private _map = new Map<string, number>();
private _strings = new Array<string>();
public get(s: string): number {
const map = this._map;
let id = map.get(s);
if (id === undefined) {
id = this._strings.push(s) - 1;
map.set(s, id);
}
return id;
}
public fromId(i: number): string {
return this._strings[i];
}
}
/**
* Edge mirror
*/
export class Edge {
public edgeIndex: EdgeIndex;
private _heap: HeapGraph;
constructor(i: EdgeIndex, heap: HeapGraph) {
this.edgeIndex = i;
this._heap = heap;
}
public get to(): Node {
return new Node(this._heap.edgeToNodes[this.edgeIndex], this._heap);
}
public get toIndex(): NodeIndex {
return this._heap.edgeToNodes[this.edgeIndex];
}
public get snapshotType(): SnapshotEdgeType {
return this._heap.edgeTypes[this.edgeIndex];
}
/**
* Returns the index (number) or name (string) that this edge
* corresponds to. (Index types occur in Arrays.)
*/
public get indexOrName(): string | number {
const nameOrIndex = this._heap.edgeNamesOrIndexes[this.edgeIndex];
if (this._isIndex()) {
return nameOrIndex;
} else {
return this._heap.stringMap.fromId(nameOrIndex);
}
}
/**
* Returns 'true' if the edge corresponds to a type where nameOrIndex is an index,
* and false otherwise.
*/
private _isIndex(): boolean {
switch(this.snapshotType) {
case SnapshotEdgeType.Element: // Array element.
case SnapshotEdgeType.Hidden: // Hidden from developer, but influences in-memory size. Apparently has an index, not a name. Ignore for now.
return true;
case SnapshotEdgeType.ContextVariable: // Closure variable.
case SnapshotEdgeType.Internal: // Internal data structures that are not actionable to developers. Influence retained size. Ignore for now.
case SnapshotEdgeType.Shortcut: // Shortcut: Should be ignored; an internal detail.
case SnapshotEdgeType.Weak: // Weak reference: Doesn't hold onto memory.
case SnapshotEdgeType.Property: // Property on an object.
return false;
default:
throw new Error(`Unrecognized edge type: ${this.snapshotType}`);
}
}
/**
* Determines what type of edge this is in a heap path.
* Recognizes some special BLeak-inserted heap edges that correspond
* to hidden browser state.
*/
public get pathSegmentType(): PathSegmentType {
switch(this.snapshotType) {
case SnapshotEdgeType.Element:
return PathSegmentType.ELEMENT;
case SnapshotEdgeType.ContextVariable:
return PathSegmentType.CLOSURE_VARIABLE;
case SnapshotEdgeType.Internal:
if (this.indexOrName === 'context') {
return PathSegmentType.CLOSURE;
}
break;
case SnapshotEdgeType.Property: {
// We assume that no one uses our chosen special property names.
// If the program happens to have a memory leak stemming from a non-BLeak-created
// property with one of these names, then BLeak might not find it.
const name = this.indexOrName;
switch (name) {
case '$$$DOM$$$':
return PathSegmentType.DOM_TREE;
case '$$listeners':
return PathSegmentType.EVENT_LISTENER_LIST;
default:
return PathSegmentType.PROPERTY;
}
}
}
console.debug(`Unrecognized edge type: ${this.snapshotType}`)
return PathSegmentType.UNKNOWN;
}
}
class EdgeIterator {
private _edge: Edge;
private _edgeEnd: number;
constructor(heap: HeapGraph, edgeStart: EdgeIndex, edgeEnd: EdgeIndex) {
this._edge = new Edge(edgeStart, heap);
this._edgeEnd = edgeEnd;
}
public hasNext(): boolean {
return this._edge.edgeIndex < this._edgeEnd;
}
public next(): void {
this._edge.edgeIndex++;
}
public item(): Edge {
return this._edge;
}
}
/**
* Node mirror.
*/
class Node {
public nodeIndex: NodeIndex
private _heap: HeapGraph;
constructor(i: NodeIndex, heap: HeapGraph) {
this.nodeIndex = i;
this._heap = heap;
}
public get type(): SnapshotNodeType {
return this._heap.nodeTypes[this.nodeIndex];
}
public get size(): number {
return this._heap.nodeSizes[this.nodeIndex];
}
public get hasChildren(): boolean {
return this.childrenLength !== 0;
}
public get name(): string {
return this._heap.stringMap.fromId(this._heap.nodeNames[this.nodeIndex]);
}
public get childrenLength(): number {
const fei = this._heap.firstEdgeIndexes;
return fei[this.nodeIndex + 1] - fei[this.nodeIndex];
}
public get children(): EdgeIterator {
const fei = this._heap.firstEdgeIndexes;
return new EdgeIterator(this._heap, fei[this.nodeIndex], fei[this.nodeIndex + 1]);
}
public getChild(i: number): Edge {
const fei = this._heap.firstEdgeIndexes;
const index = fei[this.nodeIndex] + i as EdgeIndex;
if (index >= fei[this.nodeIndex + 1]) {
throw new Error(`Invalid child.`);
}
return new Edge(index, this._heap);
}
/**
* Measures the number of properties on the node.
* May require traversing hidden children.
* This is the growth metric we use.
*/
public numProperties(): number {
let count = 0;
if (this.hasChildren) {
for (const it = this.children; it.hasNext(); it.next()) {
const child = it.item();
switch(child.snapshotType) {
case SnapshotEdgeType.Internal:
switch(child.indexOrName) {
case "elements": {
// Contains numerical properties, including those of
// arrays and objects.
const elements = child.to;
// Only count if no children.
if (!elements.hasChildren) {
count += Math.floor(elements.size / 8);
}
break;
}
case "table": {
// Contains Map and Set object entries.
const table = child.to;
if (table.hasChildren) {
count += table.childrenLength;
}
break;
}
case "properties": {
// Contains expando properties on DOM nodes,
// properties storing numbers on objects,
// etc.
const props = child.to;
if (props.hasChildren) {
count += props.childrenLength;
}
break;
}
}
break;
case SnapshotEdgeType.Hidden:
case SnapshotEdgeType.Shortcut:
case SnapshotEdgeType.Weak:
break;
default:
count++;
break;
}
}
}
return count;
}
}
/**
* Represents a heap snapshot / heap graph.
*/
export class HeapGraph {
public static async Construct(parser: HeapSnapshotParser, log: Log, stringMap: StringMap = new StringMap()): Promise<HeapGraph> {
return log.timeEvent(OperationType.HEAP_SNAPSHOT_PARSE, async () => {
const firstChunk = await parser.read();
if (firstChunk.type !== DataTypes.SNAPSHOT) {
throw new Error(`First chunk does not contain snapshot property.`);
}
const snapshotInfo = firstChunk.data;
const meta = snapshotInfo.meta;
const nodeFields = meta.node_fields;
const nodeLength = nodeFields.length;
const rootNodeIndex = (snapshotInfo.root_index ? snapshotInfo.root_index / nodeLength : 0) as NodeIndex;
const nodeCount = snapshotInfo.node_count;
const edgeCount = snapshotInfo.edge_count;
const nodeTypes = new Uint8Array(nodeCount);
const nodeNames = new Uint32Array(nodeCount);
const nodeSizes = new Uint32Array(nodeCount);
const firstEdgeIndexes = new Uint32Array(nodeCount + 1);
const edgeTypes = new Uint8Array(edgeCount);
const edgeNamesOrIndexes = new Uint32Array(edgeCount);
const edgeToNodes = new Uint32Array(edgeCount);
{
const nodeTypeOffset = nodeFields.indexOf("type");
const nodeNameOffset = nodeFields.indexOf("name");
const nodeSelfSizeOffset = nodeFields.indexOf("self_size");
const nodeEdgeCountOffset = nodeFields.indexOf("edge_count");
const edgeFields = meta.edge_fields;
const edgeLength = edgeFields.length;
const edgeTypeOffset = edgeFields.indexOf("type");
const edgeNameOrIndexOffset = edgeFields.indexOf("name_or_index");
const edgeToNodeOffset = edgeFields.indexOf("to_node");
let strings: Array<string> = [];
let nodePtr = 0;
let edgePtr = 0;
let nextEdge = 0;
while (true) {
const chunk = await parser.read();
if (chunk === null) {
break;
}
switch (chunk.type) {
case DataTypes.NODES: {
const data = chunk.data;
const dataLen = data.length;
const dataNodeCount = dataLen / nodeLength;
if (dataLen % nodeLength !== 0) {
throw new Error(`Expected chunk to contain whole nodes. Instead, contained ${dataNodeCount} nodes.`);
}
// Copy data into our typed arrays.
for (let i = 0; i < dataNodeCount; i++) {
const dataBase = i * nodeLength;
const arrayBase = nodePtr + i;
nodeTypes[arrayBase] = data[dataBase + nodeTypeOffset];
nodeNames[arrayBase] = data[dataBase + nodeNameOffset];
nodeSizes[arrayBase] = data[dataBase + nodeSelfSizeOffset];
firstEdgeIndexes[arrayBase] = nextEdge;
nextEdge += data[dataBase + nodeEdgeCountOffset];
}
nodePtr += dataNodeCount;
break;
}
case DataTypes.EDGES: {
const data = chunk.data;
const dataLen = data.length;
const dataEdgeCount = dataLen / edgeLength;
if (dataLen % edgeLength !== 0) {
throw new Error(`Expected chunk to contain whole nodes. Instead, contained ${dataEdgeCount} nodes.`);
}
// Copy data into our typed arrays.
for (let i = 0; i < dataEdgeCount; i++) {
const dataBase = i * edgeLength;
const arrayBase = edgePtr + i;
edgeTypes[arrayBase] = data[dataBase + edgeTypeOffset];
edgeNamesOrIndexes[arrayBase] = data[dataBase + edgeNameOrIndexOffset];
edgeToNodes[arrayBase] = data[dataBase + edgeToNodeOffset] / nodeLength;
}
edgePtr += dataEdgeCount;
break;
}
case DataTypes.STRINGS: {
strings = strings.concat(chunk.data);
break;
}
default:
throw new Error(`Unexpected snapshot chunk: ${chunk.type}.`);
}
}
// Process edgeNameOrIndex now.
for (let i = 0; i < edgeCount; i++) {
const edgeType = edgeTypes[i];
switch(edgeType) {
case SnapshotEdgeType.Element: // Array element.
case SnapshotEdgeType.Hidden: // Hidden from developer, but influences in-memory size. Apparently has an index, not a name. Ignore for now.
break;
case SnapshotEdgeType.ContextVariable: // Function context. I think it has a name, like "context".
case SnapshotEdgeType.Internal: // Internal data structures that are not actionable to developers. Influence retained size. Ignore for now.
case SnapshotEdgeType.Shortcut: // Shortcut: Should be ignored; an internal detail.
case SnapshotEdgeType.Weak: // Weak reference: Doesn't hold onto memory.
case SnapshotEdgeType.Property: // Property on an object.
edgeNamesOrIndexes[i] = stringMap.get(strings[edgeNamesOrIndexes[i]]);
break;
default:
throw new Error(`Unrecognized edge type: ${edgeType}`);
}
}
firstEdgeIndexes[nodeCount] = edgeCount;
// Process nodeNames now.
for (let i = 0; i < nodeCount; i++) {
nodeNames[i] = stringMap.get(strings[nodeNames[i]]);
}
}
return new HeapGraph(stringMap, nodeTypes, nodeNames, nodeSizes,
firstEdgeIndexes, edgeTypes, edgeNamesOrIndexes, edgeToNodes, rootNodeIndex);
});
}
public readonly stringMap: StringMap;
// Map from node index => node type
public readonly nodeTypes: Uint8Array;
// Map from node index => node name.
public readonly nodeNames: Uint32Array;
// Map from node index => node size.
public readonly nodeSizes: Uint32Array;
// Map from Node index => the index of its first edge / the last index of ID - 1
public readonly firstEdgeIndexes: {[n: number]: EdgeIndex} & Uint32Array;
// Map from edge index => edge type.
public readonly edgeTypes: Uint8Array;
// Map from edge index => edge name.
public readonly edgeNamesOrIndexes: Uint32Array;
// Map from edge index => destination node.
public readonly edgeToNodes: {[n: number]: NodeIndex} & Uint32Array; // Uint32Array
// Index of the graph's root node.
public readonly rootNodeIndex: NodeIndex;
// Lazily initialized retained size array.
public readonly retainedSize: Uint32Array = null;
private constructor(stringMap: StringMap, nodeTypes: Uint8Array, nodeNames: Uint32Array,
nodeSizes: Uint32Array, firstEdgeIndexes: Uint32Array, edgeTypes: Uint8Array,
edgeNamesOrIndexes: Uint32Array, edgeToNodes: Uint32Array, rootNodeIndex: NodeIndex) {
this.stringMap = stringMap;
this.nodeTypes = nodeTypes;
this.nodeNames = nodeNames;
this.nodeSizes = nodeSizes;
this.firstEdgeIndexes = firstEdgeIndexes as any;
this.edgeTypes = edgeTypes;
this.edgeNamesOrIndexes = edgeNamesOrIndexes;
this.edgeToNodes = edgeToNodes as any;
this.rootNodeIndex = rootNodeIndex;
}
public get nodeCount(): number {
return this.nodeTypes.length;
}
public get edgeCount(): number {
return this.edgeTypes.length;
}
public getGlobalRootIndices(): number[] {
const rv = new Array<number>();
const root = this.getRoot();
for (const it = root.children; it.hasNext(); it.next()) {
const subroot = it.item().to;
if (subroot.type !== SnapshotNodeType.Synthetic) {
rv.push(subroot.nodeIndex);
}
}
return rv;
}
public getUserRootIndices(): number[] {
const rv = new Array<number>();
const root = this.getRoot();
for (const it = root.children; it.hasNext(); it.next()) {
const subroot = it.item().to;
if (subroot.type !== SnapshotNodeType.Synthetic || subroot.name === "(Document DOM trees)") {
rv.push(subroot.nodeIndex);
}
}
return rv;
}
public getRoot(): Node {
return new Node(this.rootNodeIndex, this);
}
public calculateSize(): SnapshotSizeSummary {
const rv: SnapshotSizeSummary = {
numNodes: this.nodeCount,
numEdges: this.edgeCount,
totalSize: 0,
hiddenSize: 0,
arraySize: 0,
stringSize: 0,
objectSize: 0,
codeSize: 0,
closureSize: 0,
regexpSize: 0,
heapNumberSize: 0,
nativeSize: 0,
syntheticSize: 0,
consStringSize: 0,
slicedStringSize: 0,
symbolSize: 0,
unknownSize: 0
};
this.visitUserRoots((n) => {
const nodeType = n.type;
const nodeSelfSize = n.size;
rv.totalSize += n.size;
switch (nodeType) {
case SnapshotNodeType.Array:
rv.arraySize += nodeSelfSize;
break;
case SnapshotNodeType.Closure:
rv.closureSize += nodeSelfSize;
break;
case SnapshotNodeType.Code:
rv.codeSize += nodeSelfSize;
break;
case SnapshotNodeType.ConsString:
rv.consStringSize += nodeSelfSize;
break;
case SnapshotNodeType.HeapNumber:
rv.heapNumberSize += nodeSelfSize;
break;
case SnapshotNodeType.Hidden:
rv.hiddenSize += nodeSelfSize;
break;
case SnapshotNodeType.Native:
rv.nativeSize += nodeSelfSize;
break;
case SnapshotNodeType.Object:
rv.objectSize += nodeSelfSize;
break;
case SnapshotNodeType.RegExp:
rv.regexpSize += nodeSelfSize;
break;
case SnapshotNodeType.SlicedString:
rv.slicedStringSize += nodeSelfSize;
break;
case SnapshotNodeType.String:
rv.stringSize += nodeSelfSize;
break;
case SnapshotNodeType.Symbol:
rv.symbolSize += nodeSelfSize;
break;
case SnapshotNodeType.Synthetic:
rv.syntheticSize += nodeSelfSize;
break;
case SnapshotNodeType.Unresolved:
default:
rv.unknownSize += nodeSelfSize;
break;
}
});
return rv;
}
public visitRoot(visitor: (n: Node) => void, filter: (n: Node, e: Edge) => boolean = nonWeakFilter): void {
bfsVisitor(this, [this.rootNodeIndex], visitor, filter);
}
public visitUserRoots(visitor: (n: Node) => void, filter: (n: Node, e: Edge) => boolean = nonWeakFilter) {
bfsVisitor(this, this.getUserRootIndices(), visitor, filter);
}
public visitGlobalRoots(visitor: (n: Node) => void, filter: (n: Node, e: Edge) => boolean = nonWeakFilter) {
bfsVisitor(this, this.getGlobalRootIndices(), visitor, filter);
}
public visitGlobalEdges(visitor: (e: Edge, getPath: () => Edge[]) => void, filter: (n: Node, e: Edge) => boolean = nonWeakFilter): void {
let initial = new Array<number>();
const root = this.getRoot();
for (const it = root.children; it.hasNext(); it.next()) {
const edge = it.item();
const subroot = edge.to;
if (subroot.type !== SnapshotNodeType.Synthetic) {
initial.push(edge.edgeIndex);
}
}
bfsEdgeVisitor(this, initial, visitor, filter);
}
}
function nonWeakFilter(n: Node, e: Edge): boolean {
return e.snapshotType !== SnapshotEdgeType.Weak;
}
function nopFilter(n: Node, e: Edge): boolean {
return true;
}
/**
* Visit edges / paths in the graph in a breadth-first-search.
* @param g The heap graph to visit.
* @param initial Initial edge indices to visit.
* @param visitor Visitor function. Called on every unique edge visited.
* @param filter Filter function. Called on every edge. If false, visitor does not visit edge.
*/
function bfsEdgeVisitor(g: HeapGraph, initial: number[], visitor: (e: Edge, getPath: () => Edge[]) => void, filter: (n: Node, e: Edge) => boolean = nopFilter): void {
const visitBits = new OneBitArray(g.edgeCount);
// Every edge is a pair: [previousEdge, edgeIndex].
// Can follow linked list to reconstruct path.
// Index 0 is "root".
const edgesToVisit = new Uint32Array((g.edgeCount + 1) << 1);
// Leave first entry blank as a catch-all root.
let edgesToVisitLength = 2;
let index = 2;
function enqueue(prevIndex: number, edgeIndex: number): void {
edgesToVisit[edgesToVisitLength++] = prevIndex;
edgesToVisit[edgesToVisitLength++] = edgeIndex;
}
function dequeue(): EdgeIndex {
// Ignore the prev edge link.
index++;
return edgesToVisit[index++] as EdgeIndex;
}
initial.forEach((i) => {
enqueue(0, i);
visitBits.set(i, true);
});
function indexToEdge(index: number): Edge {
return new Edge(index as EdgeIndex, g);
}
let currentEntryIndex = index;
function getPath(): Edge[] {
let pIndex = currentEntryIndex;
let path = new Array<number>();
while (pIndex !== 0) {
path.push(edgesToVisit[pIndex + 1]);
pIndex = edgesToVisit[pIndex];
}
return path.reverse().map(indexToEdge);
}
const node = new Node(0 as NodeIndex, g);
const edge = new Edge(0 as EdgeIndex, g);
while (index < edgesToVisitLength) {
currentEntryIndex = index;
edge.edgeIndex = dequeue();
visitor(edge, getPath);
node.nodeIndex = edge.toIndex;
for (const it = node.children; it.hasNext(); it.next()) {
const child = it.item();
if (!visitBits.get(child.edgeIndex) && filter(node, child)) {
visitBits.set(child.edgeIndex, true);
enqueue(currentEntryIndex, child.edgeIndex);
}
}
}
}
/**
* Visit the graph in a breadth-first-search.
* @param g The heap graph to visit.
* @param initial Initial node(s) to visit.
* @param visitor Visitor function. Called on every unique node visited.
* @param filter Filter function. Called on every edge. If false, visitor does not visit edge.
*/
function bfsVisitor(g: HeapGraph, initial: number[], visitor: (n: Node) => void, filter: (n: Node, e: Edge) => boolean = nopFilter): void {
const visitBits = new OneBitArray(g.nodeCount);
const nodesToVisit: {[n: number]: NodeIndex} & Uint32Array = <any> new Uint32Array(g.nodeCount);
let nodesToVisitLength = 0;
function enqueue(nodeIndex: NodeIndex): void {
nodesToVisit[nodesToVisitLength++] = nodeIndex;
}
let index = 0;
initial.map(enqueue);
initial.forEach((i) => visitBits.set(i, true));
const node = new Node(0 as NodeIndex, g);
const edge = new Edge(0 as EdgeIndex, g);
while (index < nodesToVisitLength) {
const nodeIndex = nodesToVisit[index++];
node.nodeIndex = nodeIndex;
visitor(node);
const firstEdgeIndex = g.firstEdgeIndexes[nodeIndex];
const edgesEnd = g.firstEdgeIndexes[nodeIndex + 1];
for (let edgeIndex = firstEdgeIndex; edgeIndex < edgesEnd; edgeIndex++) {
const childNodeIndex = g.edgeToNodes[edgeIndex];
edge.edgeIndex = edgeIndex;
if (!visitBits.get(childNodeIndex) && filter(node, edge)) {
visitBits.set(childNodeIndex, true);
enqueue(childNodeIndex);
}
}
}
} | the_stack |
"use strict";
import { assert } from "chai";
import { Strings } from "../../../src/helpers/strings";
import { FindConflicts } from "../../../src/tfvc/commands/findconflicts";
import { TfvcError } from "../../../src/tfvc/tfvcerror";
import { IExecutionResult, IConflict } from "../../../src/tfvc/interfaces";
import { ConflictType } from "../../../src/tfvc/scm/status";
import { TeamServerContext } from "../../../src/contexts/servercontext";
import { CredentialInfo } from "../../../src/info/credentialinfo";
import { RepositoryInfo } from "../../../src/info/repositoryinfo";
describe("Tfvc-FindConflictsCommand", function() {
const serverUrl: string = "http://server:8080/tfs";
const repoUrl: string = "http://server:8080/tfs/collection1/_git/repo1";
const collectionUrl: string = "http://server:8080/tfs/collection1";
const user: string = "user1";
const pass: string = "pass1";
let context: TeamServerContext;
beforeEach(function() {
context = new TeamServerContext(repoUrl);
context.CredentialInfo = new CredentialInfo(user, pass);
context.RepoInfo = new RepositoryInfo({
serverUrl: serverUrl,
collection: {
name: "collection1",
id: ""
},
repository: {
remoteUrl: repoUrl,
id: "",
name: "",
project: {
name: "project1"
}
}
});
});
it("should verify constructor", function() {
const localPath: string = "/usr/alias/repo1";
new FindConflicts(undefined, localPath);
});
it("should verify constructor with context", function() {
const localPath: string = "/usr/alias/repo1";
new FindConflicts(context, localPath);
});
it("should verify constructor - undefined args", function() {
assert.throws(() => new FindConflicts(undefined, undefined), TfvcError, /Argument is required/);
});
it("should verify GetOptions", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
assert.deepEqual(cmd.GetOptions(), {});
});
it("should verify GetExeOptions", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
assert.deepEqual(cmd.GetExeOptions(), {});
});
it("should verify arguments", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "resolve -noprompt " + localPath + " -recursive -preview");
});
it("should verify Exe arguments", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "resolve -noprompt " + localPath + " -recursive -preview");
});
it("should verify arguments with context", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(context, localPath);
assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "resolve -noprompt -collection:" + collectionUrl + " ******** " + localPath + " -recursive -preview");
});
it("should verify Exe arguments with context", function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(context, localPath);
assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "resolve -noprompt ******** " + localPath + " -recursive -preview");
});
it("should verify parse output - no output", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: undefined,
stderr: undefined
};
const results: IConflict[] = await cmd.ParseOutput(executionResult);
assert.equal(results.length, 0);
});
it("should verify parse output - one of each type", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "",
stderr: "contentChange.txt: The item content has changed\n" +
"addConflict.txt: Another item with the same name exists on the server\n" +
"nameChange.txt: The item name has changed\n" +
"nameAndContentChange.txt: The item name and content have changed\n" +
"anotherNameAndContentChange.txt: You have a conflicting pending change\n" +
"contentChange2.txt: The item content has changed\n" +
"deleted.txt: The item has already been deleted\n" +
"branchEdit.txt: The source and target both have changes\n" +
"branchDelete.txt: The item has been deleted in the target branch"
};
const results: IConflict[] = await cmd.ParseOutput(executionResult);
assert.equal(results.length, 9);
assert.equal(results[0].localPath, "contentChange.txt");
assert.equal(results[0].type, ConflictType.CONTENT);
assert.equal(results[1].localPath, "addConflict.txt");
assert.equal(results[1].type, ConflictType.CONTENT);
assert.equal(results[2].localPath, "nameChange.txt");
assert.equal(results[2].type, ConflictType.RENAME);
assert.equal(results[3].localPath, "nameAndContentChange.txt");
assert.equal(results[3].type, ConflictType.NAME_AND_CONTENT);
assert.equal(results[4].localPath, "anotherNameAndContentChange.txt");
assert.equal(results[4].type, ConflictType.NAME_AND_CONTENT);
assert.equal(results[5].localPath, "contentChange2.txt");
assert.equal(results[5].type, ConflictType.CONTENT);
assert.equal(results[6].localPath, "deleted.txt");
assert.equal(results[6].type, ConflictType.DELETE);
assert.equal(results[7].localPath, "branchEdit.txt");
assert.equal(results[7].type, ConflictType.MERGE);
assert.equal(results[8].localPath, "branchDelete.txt");
assert.equal(results[8].type, ConflictType.DELETE_TARGET);
});
//With _JAVA_OPTIONS set and there are conflicts, _JAVA_OPTIONS will appear in stderr along with the results also in stderr (and stdout will be empty)
it("should verify parse output - one of each type - _JAVA_OPTIONS", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "",
stderr: "contentChange.txt: The item content has changed\n" +
"addConflict.txt: Another item with the same name exists on the server\n" +
"nameChange.txt: The item name has changed\n" +
"nameAndContentChange.txt: The item name and content have changed\n" +
"anotherNameAndContentChange.txt: You have a conflicting pending change\n" +
"contentChange2.txt: The item content has changed\n" +
"deleted.txt: The item has already been deleted\n" +
"branchEdit.txt: The source and target both have changes\n" +
"branchDelete.txt: The item has been deleted in the target branch\n" +
"Picked up _JAVA_OPTIONS: -Xmx1024M"
};
const results: IConflict[] = await cmd.ParseOutput(executionResult);
assert.equal(results.length, 9);
assert.equal(results[0].localPath, "contentChange.txt");
assert.equal(results[0].type, ConflictType.CONTENT);
assert.equal(results[1].localPath, "addConflict.txt");
assert.equal(results[1].type, ConflictType.CONTENT);
assert.equal(results[2].localPath, "nameChange.txt");
assert.equal(results[2].type, ConflictType.RENAME);
assert.equal(results[3].localPath, "nameAndContentChange.txt");
assert.equal(results[3].type, ConflictType.NAME_AND_CONTENT);
assert.equal(results[4].localPath, "anotherNameAndContentChange.txt");
assert.equal(results[4].type, ConflictType.NAME_AND_CONTENT);
assert.equal(results[5].localPath, "contentChange2.txt");
assert.equal(results[5].type, ConflictType.CONTENT);
assert.equal(results[6].localPath, "deleted.txt");
assert.equal(results[6].type, ConflictType.DELETE);
assert.equal(results[7].localPath, "branchEdit.txt");
assert.equal(results[7].type, ConflictType.MERGE);
assert.equal(results[8].localPath, "branchDelete.txt");
assert.equal(results[8].type, ConflictType.DELETE_TARGET);
});
//With _JAVA_OPTIONS set and there are no conflicts, _JAVA_OPTIONS is in stderr but the result we want to process is moved to stdout
it("should verify parse output - no conflicts - _JAVA_OPTIONS", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: "There are no conflicts to resolve.\n",
stderr: "Picked up _JAVA_OPTIONS: -Xmx1024M\n"
};
const results: IConflict[] = await cmd.ParseOutput(executionResult);
assert.equal(results.length, 0);
});
it("should verify parse output - errors - exit code 100", async function() {
const localPath: string = "/usr/alias/repo 1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 100,
stdout: "Something bad this way comes.",
stderr: undefined
};
try {
await cmd.ParseOutput(executionResult);
} catch (err) {
assert.equal(err.exitCode, 100);
assert.isTrue(err.message.startsWith(Strings.TfExecFailedError));
}
});
it("should verify parse Exe output - no output", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 0,
stdout: undefined,
stderr: undefined
};
const results: IConflict[] = await cmd.ParseExeOutput(executionResult);
assert.equal(results.length, 0);
});
it("should verify parse Exe output - one of each type", async function() {
const localPath: string = "/usr/alias/repo1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 1,
stdout: "",
stderr: "folder1\\anothernewfile2.txt: A newer version exists on the server.\n" +
"folder1\\anothernewfile4.txt: The item has been deleted from the server.\n"
};
const results: IConflict[] = await cmd.ParseExeOutput(executionResult);
assert.equal(results.length, 2);
assert.equal(results[0].localPath, "folder1\\anothernewfile2.txt");
assert.equal(results[0].type, ConflictType.NAME_AND_CONTENT);
assert.equal(results[1].localPath, "folder1\\anothernewfile4.txt");
assert.equal(results[1].type, ConflictType.DELETE);
});
it("should verify parse Exe output - errors - exit code 100", async function() {
const localPath: string = "/usr/alias/repo 1";
const cmd: FindConflicts = new FindConflicts(undefined, localPath);
const executionResult: IExecutionResult = {
exitCode: 100,
stdout: "Something bad this way comes.",
stderr: undefined
};
try {
await cmd.ParseExeOutput(executionResult);
} catch (err) {
assert.equal(err.exitCode, 100);
assert.isTrue(err.message.startsWith(Strings.TfExecFailedError));
}
});
}); | the_stack |
import { ADD_ITEM, REMOVE_ITEM, SET } from "#SRC/js/constants/TransactionTypes";
import Transaction from "#SRC/js/structs/Transaction";
import { deepCopy } from "#SRC/js/utils/Util";
import {
MultiContainerReducerContext,
MultiContainerSecretContext,
MultiContainerServiceJSON,
ServiceSecret,
SingleContainerReducerContext,
SingleContainerSecretExposure,
SingleContainerSecretContext,
SingleContainerServiceJSON,
MultiContainerVolume,
MultiContainerSecretExposure,
} from "./types";
function defaultSecretVolumeKey(secretKey: string, index: number) {
return `${secretKey}volume${index}`;
}
function emptySingleContainerSecret(): SingleContainerSecretContext {
return { key: null, value: null, exposures: [] };
}
function emptyMultiContainerSecret(): MultiContainerSecretContext {
return { key: null, value: null, exposures: [] };
}
// tslint:disable-next-line
function processSecretTransaction(
secrets: SingleContainerSecretContext[],
{ type, path, value }: Transaction
): SingleContainerSecretContext[] {
const base: string = path[0] as string;
if (base !== "secrets") {
return secrets;
}
let newSecrets: SingleContainerSecretContext[] = deepCopy(secrets);
const index: number | undefined =
path.length > 1 ? (path[1] as number) : undefined;
const field: string | undefined =
path.length > 2 ? (path[2] as string) : undefined;
const secondaryIndex: number | undefined =
path.length > 3 ? (path[3] as number) : undefined;
switch (type) {
case ADD_ITEM:
if (index == null) {
const item: SingleContainerSecretContext = value
? (value as SingleContainerSecretContext)
: emptySingleContainerSecret();
newSecrets.push(item);
} else if (field === "exposures") {
if (
typeof value === "object" &&
value != null &&
"type" in value &&
"value" in value
) {
newSecrets[index].exposures.push(
value as SingleContainerSecretExposure
);
} else if (typeof value === "string") {
newSecrets[index].exposures.push({ type: "envVar", value });
} else {
newSecrets[index].exposures.push({ type: "envVar", value: "" });
}
}
break;
case REMOVE_ITEM:
if (!field) {
newSecrets = newSecrets.filter((_, index) => {
return index !== value;
});
} else if (index !== undefined && field === "exposures") {
newSecrets[index].exposures = newSecrets[index].exposures.filter(
(_, index) => index !== value
);
}
break;
case SET:
if (index !== undefined) {
if (field === "key" || field === "value") {
newSecrets[index][field] = value as string;
} else if (field === "exposures" && secondaryIndex != null) {
// initialize empty exposure values up to the index we're setting
if (secondaryIndex >= newSecrets[index].exposures.length) {
for (
let i = newSecrets[index].exposures.length;
i <= secondaryIndex;
i++
) {
newSecrets[index].exposures[i] = { type: "", value: "" };
}
}
const exposureField: string | null =
path.length > 4 ? (path[4] as string) : null;
if (exposureField == null) {
newSecrets[index].exposures[
secondaryIndex
] = value as SingleContainerSecretExposure;
} else if (exposureField === "value") {
newSecrets[index].exposures[secondaryIndex].value = value as string;
} else if (exposureField === "type") {
const currentType =
newSecrets[index].exposures[secondaryIndex].type;
const newType = value as string;
if (currentType !== newType) {
newSecrets[index].exposures[secondaryIndex].type = newType;
newSecrets[index].exposures[secondaryIndex].value = "";
}
}
}
}
break;
}
return newSecrets;
}
// tslint:disable-next-line
function processPodSecretTransaction(
secrets: MultiContainerSecretContext[],
{ type, path, value }: Transaction
): MultiContainerSecretContext[] {
const base: string = path[0] as string;
if (base !== "secrets") {
return secrets;
}
let newSecrets: MultiContainerSecretContext[] = deepCopy(secrets);
const index: number | undefined =
path.length > 1 ? (path[1] as number) : undefined;
const field: string | undefined =
path.length > 2 ? (path[2] as string) : undefined;
const secondaryIndex: number | undefined =
path.length > 3 ? (path[3] as number) : undefined;
switch (type) {
case ADD_ITEM:
if (index == null) {
const item: MultiContainerSecretContext = value
? (value as MultiContainerSecretContext)
: emptyMultiContainerSecret();
newSecrets.push(item);
} else if (field === "exposures") {
if (
typeof value === "object" &&
value != null &&
"type" in value &&
"value" in value
) {
newSecrets[index].exposures.push(
value as MultiContainerSecretExposure
);
} else if (typeof value === "string") {
newSecrets[index].exposures.push({ type: "envVar", value });
} else {
newSecrets[index].exposures.push({ type: "envVar", value: "" });
}
}
break;
case REMOVE_ITEM:
if (!field) {
newSecrets = newSecrets.filter((_, index) => index !== value);
} else if (index != null && field === "exposures") {
newSecrets[index].exposures = newSecrets[index].exposures.filter(
(_, index) => index !== value
);
}
break;
case SET:
if (index != null) {
if (field === "key" || field === "value") {
newSecrets[index][field] = value as string;
} else if (field === "exposures" && secondaryIndex != null) {
// initialize empty exposure values up to the index we're setting
if (secondaryIndex >= newSecrets[index].exposures.length) {
for (
let i = newSecrets[index].exposures.length;
i <= secondaryIndex;
i++
) {
newSecrets[index].exposures[i] = { type: "", value: "" };
}
}
const exposureField: string | null =
path.length > 4 ? (path[4] as string) : null;
if (exposureField == null) {
newSecrets[index].exposures[
secondaryIndex
] = value as MultiContainerSecretExposure;
} else if (exposureField === "value") {
newSecrets[index].exposures[secondaryIndex].value = value as string;
} else if (exposureField === "type") {
const newType = value as string;
newSecrets[index].exposures[secondaryIndex].type = newType;
newSecrets[index].exposures[secondaryIndex].value = "";
if (
newType === "envVar" &&
newSecrets[index].exposures[secondaryIndex].mounts
) {
delete newSecrets[index].exposures[secondaryIndex].mounts;
}
if (
newType === "file" &&
!newSecrets[index].exposures[secondaryIndex].mounts
) {
newSecrets[index].exposures[secondaryIndex].mounts = [];
}
} else if (exposureField === "mounts") {
const mountsIndex: number | null =
path.length > 5 ? (path[5] as number) : null;
if (mountsIndex != null) {
const exposure = newSecrets[index].exposures[secondaryIndex];
// initialize the mounts array if it doesn't exist on the exposure
if (!exposure.mounts) {
exposure.mounts = [];
}
// initialize empty mount values up to the index we're setting
if (mountsIndex >= exposure.mounts.length) {
for (let i = exposure.mounts.length; i <= mountsIndex; i++) {
exposure.mounts[i] = "";
}
}
exposure.mounts[mountsIndex] = value as string;
}
}
}
}
break;
}
return newSecrets;
}
/**
* JSONSingleContainerReducer - generates JSON fragment of a `secrets` field of a definition
*
* Secret declaration is split between `env`, `secrets` & `container.volumes` fields
* Secrets.JSONReducer can return only `secrets` part
* `env` part of a secret will be generated by
* EnvironmentVariables.JSONReducer
* `container.volumes` part of a secret will be generated by
* Volumes.JSONSingleContainerReducer
*
* @param {Object} state current state of `secrets` field
* @param {Object} transaction
* @param {String} transaction.type
* @param {String[]} transaction.path
* @param {*} transaction.value
* @return {Object} new state for the `secrets` field
*/
function JSONSingleContainerReducer(
this: SingleContainerReducerContext,
state: object,
{ type, path, value }: Transaction
): Record<string, ServiceSecret> | object {
if (path == null) {
return state;
}
if (this.secrets == null) {
this.secrets = [];
}
const base: string = path[0] as string;
if (base === "secrets") {
this.secrets = processSecretTransaction(this.secrets, {
type,
path,
value,
});
}
const result: Record<string, ServiceSecret> = {};
return this.secrets.reduce((memo, item, index) => {
const key = item.key || `secret${index}`;
if (key != null && item.value != null) {
memo[key] = { source: item.value };
}
return memo;
}, result);
}
function JSONSingleContainerParser(
state: SingleContainerServiceJSON
): Transaction[] {
if (state.secrets == null) {
return [];
}
const secretsState = state.secrets;
const env = state.env || state.environment;
const volumes =
state.container &&
state.container.volumes &&
Array.isArray(state.container.volumes)
? state.container.volumes.filter((vol) => vol.secret)
: [];
const result: Transaction[] = [];
// Secrets are two folds and one can not exist without another:
// 1. Special format Env variable
// 2. Secret declaration
return Object.keys(secretsState).reduce((memo, key, index) => {
const emptySecret = emptySingleContainerSecret();
const source = secretsState[key].source;
memo.push(new Transaction(["secrets"], emptySecret, ADD_ITEM));
memo.push(new Transaction(["secrets", index, "key"], key, SET));
memo.push(new Transaction(["secrets", index, "value"], source, SET));
if (env) {
// Search for the secrets name in env variables
const environmentVars = Object.keys(env).filter((name) => {
const envVar = env[name];
return typeof envVar === "object" && envVar.secret === key;
});
environmentVars.forEach((name) => {
memo.push(
new Transaction(
["secrets", index, "exposures"],
{ type: "envVar", value: name },
ADD_ITEM
)
);
});
}
if (volumes.length > 0) {
const files = volumes
.filter((vol) => vol.secret === key)
.map((vol) => vol.containerPath);
files.forEach((path) => {
memo.push(
new Transaction(
["secrets", index, "exposures"],
{ type: "file", value: path },
ADD_ITEM
)
);
});
}
return memo;
}, result);
}
function FormSingleContainerReducer(
state: SingleContainerSecretContext[] = [],
{ type, path, value }: Transaction
): SingleContainerSecretContext[] {
if (path == null) {
return state;
}
return processSecretTransaction(state, {
type,
path,
value,
});
}
/**
* JSONMultiContainerReducer - generates JSON fragment of a `secrets` field of a definition
*
* Secret declaration is split between `env` and `secrets` fields
* Secrets.JSONReducer can return only `secrets` part
* `env` part of a secret will be generated by
* EnvironmentVariables.JSONReducer
*
* @param {Object} state current state of `secrets` field
* @param {Object} transaction
* @param {String} transaction.type
* @param {String[]} transaction.path
* @param {*} transaction.value
* @return {Object} new state for the `secrets` field
*/
function JSONMultiContainerReducer(
this: MultiContainerReducerContext,
state: object,
{ type, path, value }: Transaction
): Record<string, ServiceSecret> | object {
if (path == null) {
return state;
}
if (this.secrets == null) {
this.secrets = [];
}
const base: string = path[0] as string;
if (base === "secrets") {
this.secrets = processPodSecretTransaction(this.secrets, {
type,
path,
value,
});
}
const result: Record<string, ServiceSecret> = {};
return this.secrets.reduce((memo, item, index) => {
const key = item.key || `secret${index}`;
if (key != null && item.value != null) {
memo[key] = { source: item.value };
}
return memo;
}, result);
}
function JSONMultiContainerParser(
state: MultiContainerServiceJSON
): Transaction[] {
if (state.secrets == null) {
return [];
}
const env = state.env || state.environment;
const volumes =
(state.volumes && state.volumes.filter((vol) => vol.secret && vol.name)) ||
[];
const volumeMap: Record<string, MultiContainerVolume> = {};
volumes.forEach((vol) => {
if (!vol.name) {
return;
}
volumeMap[vol.name] = vol;
});
let containerVolumeMounts: Array<{
index: number;
mountPath: string;
volumeName: string;
}> = [];
let numContainers = 0;
if (state.containers && state.containers.length > 0) {
numContainers = state.containers.length;
containerVolumeMounts = state.containers.reduce(
(mounts, container, containerIndex) => {
if (!container.volumeMounts) {
return mounts;
}
container.volumeMounts.forEach((mount) => {
if (mount.name && mount.name in volumeMap) {
mounts.push({
index: containerIndex,
mountPath: mount.mountPath || "",
volumeName: mount.name || "",
});
}
});
return mounts;
},
containerVolumeMounts
);
}
let result: Transaction[] = [];
result = Object.keys(state.secrets).reduce((memo, key, index) => {
const emptySecret = emptyMultiContainerSecret();
// @ts-ignore
const source = state.secrets[key].source;
memo.push(new Transaction(["secrets"], emptySecret, ADD_ITEM));
memo.push(new Transaction(["secrets", index, "key"], key, SET));
memo.push(new Transaction(["secrets", index, "value"], source, SET));
if (env) {
// Search for the secrets name in env variables
const environmentVars = Object.keys(env).filter((name) => {
const envVar = env[name];
return typeof envVar === "object" && envVar.secret === key;
});
environmentVars.forEach((name) => {
memo.push(
new Transaction(
["secrets", index, "exposures"],
{ type: "envVar", value: name },
ADD_ITEM
)
);
});
}
if (volumes) {
const secretVolumes = volumes.filter((vol) => vol.secret === key);
secretVolumes.forEach((volume) => {
const volumeExposure: MultiContainerSecretExposure = {
type: "file",
value: volume.name || defaultSecretVolumeKey(key, index),
mounts: [],
};
for (let i = 0; i < numContainers; i++) {
// @ts-ignore
volumeExposure.mounts.push("");
}
containerVolumeMounts.forEach((mount) => {
if (mount.volumeName === volumeExposure.value) {
// @ts-ignore
volumeExposure.mounts[mount.index] = mount.mountPath;
}
});
memo.push(
new Transaction(
["secrets", index, "exposures"],
volumeExposure,
ADD_ITEM
)
);
});
}
return memo;
}, result);
return result;
}
function FormMultiContainerReducer(
state: MultiContainerSecretContext[] = [],
{ type, path, value }: Transaction
): MultiContainerSecretContext[] {
if (path == null) {
return state;
}
const base: string = path[0] as string;
if (base === "secrets") {
return processPodSecretTransaction(state, {
type,
path,
value,
});
}
return state;
}
function removeSecretVolumes(
parserState: MultiContainerServiceJSON
): MultiContainerServiceJSON {
if (
!parserState.volumes ||
!parserState.volumes.find((volume) => volume.secret != null)
) {
return parserState;
}
// make a copy of the state so we can sanitize it
const sanitizedState = deepCopy(parserState) as MultiContainerServiceJSON;
// @ts-ignore
const secretVolumeNames: string[] = sanitizedState.volumes
.filter((volume) => volume.secret && volume.name)
.map((volume) => volume.name);
// Remove secret volumes from state
// @ts-ignore
sanitizedState.volumes = sanitizedState.volumes.filter(
(volume) => !volume.secret
);
// Remove volumeMounts for secret volumes
if (sanitizedState.containers) {
sanitizedState.containers = sanitizedState.containers.map((container) => {
if (!container.volumeMounts) {
return container;
}
container.volumeMounts = container.volumeMounts.filter(
(mount) => !secretVolumeNames.includes(mount.name)
);
return container;
});
}
return sanitizedState;
}
export {
processSecretTransaction,
processPodSecretTransaction,
emptySingleContainerSecret,
emptyMultiContainerSecret,
defaultSecretVolumeKey,
removeSecretVolumes,
JSONSingleContainerReducer,
JSONSingleContainerParser,
FormSingleContainerReducer,
JSONMultiContainerReducer,
JSONMultiContainerParser,
FormMultiContainerReducer,
}; | the_stack |
import gql from 'graphql-tag';
import { DocumentNode, GraphQLError, getIntrospectionQuery } from 'graphql';
import { Observable } from '../../utilities';
import { ApolloLink } from '../../link/core';
import { Operation } from '../../link/core';
import { ApolloClient } from '../../core';
import { ApolloCache, InMemoryCache } from '../../cache';
import { itAsync, withErrorSpy } from '../../testing';
describe('General functionality', () => {
it('should not impact normal non-@client use', () => {
const query = gql`
{
field
}
`;
const link = new ApolloLink(() => Observable.of({ data: { field: 1 } }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
resolvers: {
Query: {
count: () => 0,
},
},
});
return client.query({ query }).then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
});
});
it('should not interfere with server introspection queries', () => {
const query = gql`
${getIntrospectionQuery()}
`;
const error = new GraphQLError('no introspection result found');
const link = new ApolloLink(() => Observable.of({ errors: [error] }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
resolvers: {
Query: {
count: () => 0,
},
},
});
return client
.query({ query })
.then(() => {
throw new global.Error('should not call');
})
.catch((error: GraphQLError) =>
expect(error.message).toMatch(/no introspection/),
);
});
it('should support returning default values from resolvers', () => {
const query = gql`
{
field @client
}
`;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers: {
Query: {
field: () => 1,
},
},
});
return client.query({ query }).then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
});
});
it('should cache data for future lookups', () => {
const query = gql`
{
field @client
}
`;
let count = 0;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers: {
Query: {
field: () => {
count += 1;
return 1;
},
},
},
});
return client
.query({ query })
.then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
expect(count).toBe(1);
})
.then(() =>
client.query({ query }).then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
expect(count).toBe(1);
}),
);
});
it('should honour `fetchPolicy` settings', () => {
const query = gql`
{
field @client
}
`;
let count = 0;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers: {
Query: {
field: () => {
count += 1;
return 1;
},
},
},
});
return client
.query({ query })
.then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
expect(count).toBe(1);
})
.then(() =>
client
.query({ query, fetchPolicy: 'network-only' })
.then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
expect(count).toBe(2);
}),
);
});
it('should work with a custom fragment matcher', () => {
const query = gql`
{
foo {
... on Bar {
bar @client
}
... on Baz {
baz @client
}
}
}
`;
const link = new ApolloLink(() =>
Observable.of({
data: { foo: [{ __typename: 'Bar' }, { __typename: 'Baz' }] },
}),
);
const resolvers = {
Bar: {
bar: () => 'Bar',
},
Baz: {
baz: () => 'Baz',
},
};
const fragmentMatcher = (
{ __typename }: { __typename: string },
typeCondition: string,
) => __typename === typeCondition;
const client = new ApolloClient({
cache: new InMemoryCache({
possibleTypes: {
Foo: ['Bar', 'Baz'],
},
}),
link,
resolvers,
fragmentMatcher,
});
return client.query({ query }).then(({ data }) => {
expect(data).toMatchObject({ foo: [{ bar: 'Bar' }, { baz: 'Baz' }] });
});
});
});
describe('Cache manipulation', () => {
it(
'should be able to query @client fields and the cache without defining ' +
'local resolvers',
() => {
const query = gql`
{
field @client
}
`;
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: ApolloLink.empty(),
resolvers: {},
});
cache.writeQuery({ query, data: { field: 'yo' } });
client
.query({ query })
.then(({ data }) => expect({ ...data }).toMatchObject({ field: 'yo' }));
},
);
it('should be able to write to the cache using a local mutation', () => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start {
start @client
}
`;
const resolvers = {
Mutation: {
start: (_1: any, _2: any, { cache }: { cache: InMemoryCache }) => {
cache.writeQuery({ query, data: { field: 1 } });
return { start: true };
},
},
};
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers,
});
return client
.mutate({ mutation })
.then(() => client.query({ query }))
.then(({ data }) => {
expect({ ...data }).toMatchObject({ field: 1 });
});
});
itAsync(
'should be able to write to the cache with a local mutation and have ' +
'things rerender automatically',
(resolve, reject) => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start {
start @client
}
`;
const resolvers = {
Query: {
field: () => 0,
},
Mutation: {
start: (_1: any, _2: any, { cache }: { cache: InMemoryCache }) => {
cache.writeQuery({ query, data: { field: 1 } });
return { start: true };
},
},
};
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers,
});
let count = 0;
client.watchQuery({ query }).subscribe({
next: ({ data }) => {
count++;
if (count === 1) {
expect({ ...data }).toMatchObject({ field: 0 });
client.mutate({ mutation });
}
if (count === 2) {
expect({ ...data }).toMatchObject({ field: 1 });
resolve();
}
},
});
},
);
it('should support writing to the cache with a local mutation using variables', () => {
const query = gql`
{
field @client
}
`;
const mutation = gql`
mutation start($id: ID!) {
start(field: $id) @client {
field
}
}
`;
const resolvers = {
Mutation: {
start: (
_1: any,
variables: { field: string },
{ cache }: { cache: ApolloCache<any> },
) => {
cache.writeQuery({ query, data: { field: variables.field } });
return {
__typename: 'Field',
field: variables.field,
};
},
},
};
const client = new ApolloClient({
cache: new InMemoryCache(),
link: ApolloLink.empty(),
resolvers,
});
return client
.mutate({ mutation, variables: { id: '1234' } })
.then(({ data }) => {
expect({ ...data }).toEqual({
start: { field: '1234', __typename: 'Field' },
});
})
.then(() => client.query({ query }))
.then(({ data }) => {
expect({ ...data }).toMatchObject({ field: '1234' });
});
});
itAsync("should read @client fields from cache on refetch (#4741)", (resolve, reject) => {
const query = gql`
query FetchInitialData {
serverData {
id
title
}
selectedItemId @client
}
`;
const mutation = gql`
mutation Select {
select(itemId: $id) @client
}
`;
const serverData = {
__typename: "ServerData",
id: 123,
title: "Oyez and Onoz",
};
let selectedItemId = -1;
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new ApolloLink(() => Observable.of({ data: { serverData } })),
resolvers: {
Query: {
selectedItemId() {
return selectedItemId;
},
},
Mutation: {
select(_, { itemId }) {
selectedItemId = itemId;
}
}
},
});
client.watchQuery({ query }).subscribe({
next(result) {
expect(result).toEqual({
data: {
serverData,
selectedItemId,
},
loading: false,
networkStatus: 7,
});
if (selectedItemId !== 123) {
client.mutate({
mutation,
variables: {
id: 123,
},
refetchQueries: [
"FetchInitialData",
],
});
} else {
resolve();
}
},
});
});
itAsync("should rerun @client(always: true) fields on entity update", (resolve, reject) => {
const query = gql`
query GetClientData($id: ID) {
clientEntity(id: $id) @client(always: true) {
id
title
titleLength @client(always: true)
}
}
`;
const mutation = gql`
mutation AddOrUpdate {
addOrUpdate(id: $id, title: $title) @client
}
`;
const fragment = gql`
fragment ClientDataFragment on ClientData {
id
title
}
`
const client = new ApolloClient({
cache: new InMemoryCache(),
link: new ApolloLink(() => Observable.of({ data: { } })),
resolvers: {
ClientData: {
titleLength(data) {
return data.title.length
}
},
Query: {
clientEntity(_root, {id}, {cache}) {
return cache.readFragment({
id: cache.identify({id, __typename: "ClientData"}),
fragment,
});
},
},
Mutation: {
addOrUpdate(_root, {id, title}, {cache}) {
return cache.writeFragment({
id: cache.identify({id, __typename: "ClientData"}),
fragment,
data: {id, title, __typename: "ClientData"},
});
},
}
},
});
const entityId = 1;
const shortTitle = "Short";
const longerTitle = "A little longer";
client.mutate({
mutation,
variables: {
id: entityId,
title: shortTitle,
},
});
let mutated = false;
client.watchQuery({ query, variables: {id: entityId}}).subscribe({
next(result) {
if (!mutated) {
expect(result.data.clientEntity).toEqual({
id: entityId,
title: shortTitle,
titleLength: shortTitle.length,
__typename: "ClientData",
});
client.mutate({
mutation,
variables: {
id: entityId,
title: longerTitle,
}
});
mutated = true;
} else if (mutated) {
expect(result.data.clientEntity).toEqual({
id: entityId,
title: longerTitle,
titleLength: longerTitle.length,
__typename: "ClientData",
});
resolve();
}
},
});
});
});
describe('Sample apps', () => {
itAsync('should support a simple counter app using local state', (resolve, reject) => {
const query = gql`
query GetCount {
count @client
lastCount # stored in db on server
}
`;
const increment = gql`
mutation Increment($amount: Int = 1) {
increment(amount: $amount) @client
}
`;
const decrement = gql`
mutation Decrement($amount: Int = 1) {
decrement(amount: $amount) @client
}
`;
const link = new ApolloLink(operation => {
expect(operation.operationName).toBe('GetCount');
return Observable.of({ data: { lastCount: 1 } });
});
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
resolvers: {},
});
const update = (
query: DocumentNode,
updater: (data: { count: number }, variables: { amount: number }) => any,
) => {
return (
_result: {},
variables: { amount: number },
{ cache }: { cache: ApolloCache<any> },
): null => {
const read = client.readQuery<{ count: number }>({ query, variables });
if (read) {
const data = updater(read, variables);
cache.writeQuery({ query, variables, data });
} else {
throw new Error('readQuery returned a falsy value');
}
return null;
};
};
const resolvers = {
Query: {
count: () => 0,
},
Mutation: {
increment: update(query, ({ count, ...rest }, { amount }) => ({
...rest,
count: count + amount,
})),
decrement: update(query, ({ count, ...rest }, { amount }) => ({
...rest,
count: count - amount,
})),
},
};
client.addResolvers(resolvers);
let count = 0;
client.watchQuery({ query }).subscribe({
next: ({ data }) => {
count++;
if (count === 1) {
try {
expect({ ...data }).toMatchObject({ count: 0, lastCount: 1 });
} catch (e) {
reject(e);
}
client.mutate({ mutation: increment, variables: { amount: 2 } });
}
if (count === 2) {
try {
expect({ ...data }).toMatchObject({ count: 2, lastCount: 1 });
} catch (e) {
reject(e);
}
client.mutate({ mutation: decrement, variables: { amount: 1 } });
}
if (count === 3) {
try {
expect({ ...data }).toMatchObject({ count: 1, lastCount: 1 });
} catch (e) {
reject(e);
}
resolve();
}
},
error: e => reject(e),
complete: reject,
});
});
itAsync('should support a simple todo app using local state', (resolve, reject) => {
const query = gql`
query GetTasks {
todos @client {
message
title
}
}
`;
const mutation = gql`
mutation AddTodo($message: String, $title: String) {
addTodo(message: $message, title: $title) @client
}
`;
const client = new ApolloClient({
link: ApolloLink.empty(),
cache: new InMemoryCache(),
resolvers: {},
});
interface Todo {
title: string;
message: string;
__typename: string;
}
const update = (
query: DocumentNode,
updater: (todos: any, variables: Todo) => any,
) => {
return (
_result: {},
variables: Todo,
{ cache }: { cache: ApolloCache<any> },
): null => {
const data = updater(client.readQuery({ query, variables }), variables);
cache.writeQuery({ query, variables, data });
return null;
};
};
const resolvers = {
Query: {
todos: () => [],
},
Mutation: {
addTodo: update(query, ({ todos }, { title, message }: Todo) => ({
todos: todos.concat([{ message, title, __typename: 'Todo' }]),
})),
},
};
client.addResolvers(resolvers);
let count = 0;
client.watchQuery({ query }).subscribe({
next: ({ data }: any) => {
count++;
if (count === 1) {
expect({ ...data }).toMatchObject({ todos: [] });
client.mutate({
mutation,
variables: {
title: 'Apollo Client 2.0',
message: 'ship it',
},
});
} else if (count === 2) {
expect(data.todos.map((x: Todo) => ({ ...x }))).toMatchObject([
{
title: 'Apollo Client 2.0',
message: 'ship it',
__typename: 'Todo',
},
]);
resolve();
}
},
});
});
});
describe('Combining client and server state/operations', () => {
itAsync('should merge remote and local state', (resolve, reject) => {
const query = gql`
query list {
list(name: "my list") {
items {
id
name
isDone
isSelected @client
}
}
}
`;
const data = {
list: {
__typename: 'List',
items: [
{ __typename: 'ListItem', id: 1, name: 'first', isDone: true },
{ __typename: 'ListItem', id: 2, name: 'second', isDone: false },
],
},
};
const link = new ApolloLink(() => Observable.of({ data }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
resolvers: {
Mutation: {
toggleItem: async (_, { id }, { cache }) => {
id = `ListItem:${id}`;
const fragment = gql`
fragment item on ListItem {
__typename
isSelected
}
`;
const previous = cache.readFragment({ fragment, id });
const data = {
...previous,
isSelected: !previous.isSelected,
};
await cache.writeFragment({
id,
fragment,
data,
});
return data;
},
},
ListItem: {
isSelected(source) {
expect(source.name).toBeDefined();
// List items default to an unselected state
return false;
},
},
},
});
const observer = client.watchQuery({ query });
let count = 0;
observer.subscribe({
next: response => {
if (count === 0) {
const initial = { ...data };
initial.list.items = initial.list.items.map(x => ({
...x,
isSelected: false,
}));
expect(response.data).toMatchObject(initial);
}
if (count === 1) {
expect((response.data as any).list.items[0].isSelected).toBe(true);
expect((response.data as any).list.items[1].isSelected).toBe(false);
resolve();
}
count++;
},
error: reject,
});
const variables = { id: 1 };
const mutation = gql`
mutation SelectItem($id: Int!) {
toggleItem(id: $id) @client
}
`;
// After initial result, toggle the state of one of the items
setTimeout(() => {
client.mutate({ mutation, variables });
}, 10);
});
itAsync('should correctly propagate an error from a client resolver', async (resolve, reject) => {
const data = {
list: {
__typename: 'List',
items: [
{ __typename: 'ListItem', id: 1, name: 'first', isDone: true },
{ __typename: 'ListItem', id: 2, name: 'second', isDone: false },
],
},
};
const link = new ApolloLink(() => Observable.of({ data }));
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
resolvers: {
Query: {
hasBeenIllegallyTouched: (_, _v, _c) => {
throw new Error('Illegal Query Operation Occurred');
},
},
Mutation: {
touchIllegally: (_, _v, _c) => {
throw new Error('Illegal Mutation Operation Occurred');
},
},
},
});
const variables = { id: 1 };
const query = gql`
query hasBeenIllegallyTouched($id: Int!) {
hasBeenIllegallyTouched(id: $id) @client
}
`;
const mutation = gql`
mutation SelectItem($id: Int!) {
touchIllegally(id: $id) @client
}
`;
try {
await client.query({ query, variables });
reject('Should have thrown!');
} catch (e) {
// Test Passed!
expect(() => {
throw e;
}).toThrowErrorMatchingSnapshot();
}
try {
await client.mutate({ mutation, variables });
reject('Should have thrown!');
} catch (e) {
// Test Passed!
expect(() => {
throw e;
}).toThrowErrorMatchingSnapshot();
}
resolve();
});
withErrorSpy(itAsync, 'should handle a simple query with both server and client fields', (resolve, reject) => {
const query = gql`
query GetCount {
count @client
lastCount
}
`;
const cache = new InMemoryCache();
const link = new ApolloLink(operation => {
expect(operation.operationName).toBe('GetCount');
return Observable.of({ data: { lastCount: 1 } });
});
const client = new ApolloClient({
cache,
link,
resolvers: {},
});
cache.writeQuery({
query,
data: {
count: 0,
},
});
client.watchQuery({ query }).subscribe({
next: ({ data }) => {
expect({ ...data }).toMatchObject({ count: 0, lastCount: 1 });
resolve();
},
});
});
withErrorSpy(itAsync, 'should support nested querying of both server and client fields', (resolve, reject) => {
const query = gql`
query GetUser {
user {
firstName @client
lastName
}
}
`;
const cache = new InMemoryCache();
const link = new ApolloLink(operation => {
expect(operation.operationName).toBe('GetUser');
return Observable.of({
data: {
user: {
__typename: 'User',
// We need an id (or a keyFields policy) because, if the User
// object is not identifiable, the call to cache.writeQuery
// below will simply replace the existing data rather than
// merging the new data with the existing data.
id: 123,
lastName: 'Doe',
},
},
});
});
const client = new ApolloClient({
cache,
link,
resolvers: {},
});
cache.writeQuery({
query,
data: {
user: {
__typename: 'User',
id: 123,
firstName: 'John',
},
},
});
client.watchQuery({ query }).subscribe({
next({ data }: any) {
const { user } = data;
try {
expect(user).toMatchObject({
firstName: 'John',
lastName: 'Doe',
__typename: 'User',
});
} catch (e) {
reject(e);
}
resolve();
},
});
});
itAsync('should combine both server and client mutations', (resolve, reject) => {
const query = gql`
query SampleQuery {
count @client
user {
firstName
}
}
`;
const mutation = gql`
mutation SampleMutation {
incrementCount @client
updateUser(firstName: "Harry") {
firstName
}
}
`;
const counterQuery = gql`
{
count @client
}
`;
const userQuery = gql`
{
user {
firstName
}
}
`;
let watchCount = 0;
const link = new ApolloLink((operation: Operation): Observable<{}> => {
if (operation.operationName === 'SampleQuery') {
return Observable.of({
data: { user: { __typename: 'User', firstName: 'John' } },
});
}
if (operation.operationName === 'SampleMutation') {
return Observable.of({
data: { updateUser: { __typename: 'User', firstName: 'Harry' } },
});
}
return Observable.of({
errors: [new Error(`Unknown operation ${operation.operationName}`)],
})
});
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link,
resolvers: {
Mutation: {
incrementCount: (_, __, { cache }) => {
const { count } = cache.readQuery({ query: counterQuery });
const data = { count: count + 1 };
cache.writeQuery({
query: counterQuery,
data,
});
return null;
},
},
},
});
cache.writeQuery({
query: counterQuery,
data: {
count: 0,
},
});
client.watchQuery({ query }).subscribe({
next: ({ data }: any) => {
if (watchCount === 0) {
expect(data.count).toEqual(0);
expect({ ...data.user }).toMatchObject({
__typename: 'User',
firstName: 'John',
});
watchCount += 1;
client.mutate({
mutation,
update(proxy, { data: { updateUser } }: { data: any }) {
proxy.writeQuery({
query: userQuery,
data: {
user: { ...updateUser },
},
});
},
});
} else {
expect(data.count).toEqual(1);
expect({ ...data.user }).toMatchObject({
__typename: 'User',
firstName: 'Harry',
});
resolve();
}
},
});
});
}); | the_stack |
import {
scaleLinear as d3ScaleLinear, scaleBand as d3ScaleBand,
} from 'd3-scale';
import {
ARGUMENT_DOMAIN, VALUE_DOMAIN,
} from '../constants';
import {
ScaleObject, FactoryFn, DomainInfo, NumberArray, DomainBounds, DomainItems,
} from '../types';
/** @internal */
export const scaleLinear: FactoryFn = d3ScaleLinear as any;
export const scaleBand: FactoryFn = () => (
d3ScaleBand().paddingInner(0.3).paddingOuter(0.15) as any
);
/** @internal */
export const isHorizontal = (name: string, rotated: boolean) => (
name === ARGUMENT_DOMAIN === !rotated
);
// tslint:disable-next-line: ban-types
const makeScaleHelper = <T extends Function>(linear: T, band: T) => {
const func: any = (scale: ScaleObject, ...args: any[]) => {
const choosen = 'bandwidth' in scale ? band : linear;
return choosen(scale, ...args);
};
return func as T;
};
const getLinearScaleWidth = (_: ScaleObject) => 0;
const getBandScaleWidth = (scale: ScaleObject) => scale.bandwidth!();
/** @internal */
export const getWidth = makeScaleHelper(getLinearScaleWidth, getBandScaleWidth);
/** @internal */
export const getValueDomainName = (name?: string) => name || VALUE_DOMAIN;
const floatsEqual = (a: number, b: number) => Math.abs(a - b) < Number.EPSILON;
/** @internal */
export const rangesEqual = (r1: Readonly<NumberArray>, r2: Readonly<NumberArray>) =>
floatsEqual(r1[0], r2[0]) && floatsEqual(r1[1], r2[1]);
const wrapLinearScale = (scale: ScaleObject) => scale;
const wrapBandScale = (scale: ScaleObject): ScaleObject => {
const ret: any = (value: any) => scale(value) + scale.bandwidth!() / 2;
Object.assign(ret, scale);
return ret;
};
const wrapScale = makeScaleHelper(wrapLinearScale, wrapBandScale);
/** @internal */
export const makeScale = ({ factory, domain }: DomainInfo, range: NumberArray) => {
const scale = (factory || scaleLinear)().domain(domain).range(range);
return wrapScale(scale);
};
// It is implicitly supposed that Chart can accept any d3 scale. It is wrong.
// The followings notes show that. d3 scales are not seamlessly interchangeable themselves
// (i.e. band scale has no "invert", continuous scale has no "bandwidth").
// We have to use "adapters" to mitigate the differences.
// Hence Chart can actually accept any object that matches "adapter" interface.
// TODO: We should update reference accordingly. There might be breaking changes though.
const scaleLinearBounds = (scale: ScaleObject, bounds: DomainBounds): NumberArray => (
bounds.map(scale) as NumberArray
);
// There is an issue - when range is "inverted" values are scaled incorrectly.
// scaleBand().domain(['a', 'b', 'c']).range([0, 60])('b') === 20
// scaleBand().domain(['a', 'b', 'c']).range([60, 0])('b') === 20 (should be 40)
const scaleBandBounds = (scale: ScaleObject, bounds: DomainBounds): NumberArray => {
const cleanScale = scale.copy().paddingInner!(0).paddingOuter!(0);
const fullRange = scale.range();
const sign = Math.sign(fullRange[1] - fullRange[0]);
return sign >= 0
? [cleanScale(bounds[0]), cleanScale(bounds[1]) + cleanScale.bandwidth!()]
: [cleanScale(bounds[0]) + cleanScale.bandwidth!(), cleanScale(bounds[1])];
};
const moveLinearScaleBounds = (
scale: ScaleObject, bounds: DomainBounds, delta: number,
): DomainBounds => {
const fullRange = scale.range();
const sign = Math.sign(fullRange[1] - fullRange[0]);
const range = scaleLinearBounds(scale, bounds);
let r0 = range[0] + delta;
let r1 = range[1] + delta;
// Check if new range is outside of the left border.
if (Math.sign(r0 - fullRange[0]) !== sign) {
r0 = fullRange[0];
r1 = r0 + range[1] - range[0];
}
// Check if new range is outside of the right border.
if (Math.sign(fullRange[1] - r1) !== sign) {
r1 = fullRange[1];
r0 = r1 - range[1] + range[0];
}
const newBounds: DomainBounds = [scale.invert!(r0), scale.invert!(r1)];
return rangesEqual(bounds, newBounds) ? bounds : newBounds;
};
// This is pointer "delta" processing specific for "band" scale.
// If pointer delta is significantly smaller than band size (0.3) then movement should be skipped
// and current delta should be added to a next one (from a new "move" event).
// Now there is no code that accumulates deltas.
// In order to allow band scrolling at least somehow the following is applied - if pointer delta
// is at least greater than 30 pixel then minimal movement is performed.
// TODO: Make proper delta accumulation!
const adjustBandScaleMoveStep = (delta: number, step: number) => {
const ratio = Math.abs(delta / step);
const sign = Math.sign(delta / step);
if (ratio >= 0.5) {
return sign * Math.round(ratio);
}
if (ratio >= 0.3) {
return sign;
}
if (Math.abs(delta) > 30) {
return sign;
}
return 0;
};
// Band case is processed separately to preserve categories count in the bounds range.
// If common inversion mechanism is used start and end bounds cannot be inverted independently
// because of rounding issues which may add or remove categories to the new bounds.
const moveBandScaleBounds = (
scale: ScaleObject, bounds: DomainBounds, delta: number,
): DomainBounds => {
const domain = scale.domain();
const fullRange = scale.range();
const step = (fullRange[1] - fullRange[0]) / domain.length;
const rangeStep = adjustBandScaleMoveStep(delta, step);
if (rangeStep === 0) {
return bounds;
}
const range = scaleBounds(scale, bounds);
const range0 = Math.round((range[0] - fullRange[0]) / step);
const range1 = range0 + Math.round((range[1] - range[0]) / step) - 1;
let new0 = range0 + rangeStep;
let new1 = range1 + rangeStep;
if (new0 < 0) {
new0 = 0;
new1 = new0 + range1 - range0;
}
if (new1 > domain.length - 1) {
new1 = domain.length - 1;
new0 = new1 - range1 + range0;
}
if (new0 === range0 || new1 === range1) {
return bounds;
}
return [domain[new0], domain[new1]];
};
// Defines how much linear scale can be zoomed it.
// I.e. if original scale domain has size of 1, then fully zoomed scale domain has size
// of 1 / LINEAR_SCALE_ZOOMING_THRESHOLD.
const LINEAR_SCALE_ZOOMING_THRESHOLD = 1000;
const growLinearScaleBounds = (
scale: ScaleObject, bounds: DomainBounds, delta: number, anchor: number,
): DomainBounds => {
const fullRange = scale.range();
const minRangeThreshold = (fullRange[1] - fullRange[0]) / LINEAR_SCALE_ZOOMING_THRESHOLD;
const sign = Math.sign(fullRange[1] - fullRange[0]);
const range = scaleBounds(scale, bounds);
// If zooming in and initial range is already too small then do nothing.
if (delta > 0 && Math.abs(range[1] - range[0]) <= Math.abs(minRangeThreshold)) {
return bounds;
}
// If zooming out and initial range is already too large then do nothing.
if (delta < 0 && Math.abs(range[1] - range[0]) >= Math.abs(fullRange[1] - fullRange[0])) {
return bounds;
}
const t = Math.abs((anchor - range[0]) / (range[1] - range[0]));
let r0 = range[0] + sign * delta * 2 * t;
let r1 = range[1] - sign * delta * 2 * (1 - t);
// If new range is outside of the left border then clamp it.
if (Math.sign(r0 - fullRange[0]) !== sign) {
r0 = fullRange[0];
}
// If new range is outside of the right border then clamp it.
if (Math.sign(fullRange[1] - r1) !== sign) {
r1 = fullRange[1];
}
// If new range is too small then make it no less than minimal available.
if (Math.sign(r1 - r0) !== sign || Math.abs(r1 - r0) < Math.abs(minRangeThreshold)) {
if (Math.abs(r0 - range[0]) < Math.abs(minRangeThreshold / 2)) {
// Dock it to the start.
r0 = range[0];
r1 = r0 + minRangeThreshold;
} else if (Math.abs(r1 - range[1]) < Math.abs(minRangeThreshold / 2)) {
// Dock it to the end.
r1 = range[1];
r0 = r1 - minRangeThreshold;
} else {
// Dock it to the anchor.
r0 = anchor - minRangeThreshold / 2;
r1 = anchor + minRangeThreshold / 2;
}
}
const newBounds: DomainBounds = [scale.invert!(r0), scale.invert!(r1)];
return rangesEqual(bounds, newBounds) ? bounds : newBounds;
};
const growBandScaleBounds = (
scale: ScaleObject, bounds: DomainBounds, delta: number, anchor: number,
): DomainBounds => {
const domain = scale.domain();
const fullRange = scale.range();
const step = (fullRange[1] - fullRange[0]) / domain.length;
const range = scaleBounds(scale, bounds);
const range0 = Math.round((range[0] - fullRange[0]) / step);
const range1 = range0 + Math.round((range[1] - range[0]) / step) - 1;
// Let it be always 1 for now.
const rangeStep = Math.sign(delta);
if (
(rangeStep === 0) ||
(rangeStep > 0 && range0 === range1) ||
(rangeStep < 0 && range0 === 0 && range1 === domain.length - 1)
) {
return bounds;
}
const t = Math.abs((anchor - range[0]) / (range[1] - range[0]));
let new0 = range0 + Math.round(rangeStep * 2 * t);
let new1 = range1 - Math.round(rangeStep * 2 * (1 - t));
if (new0 < 0) {
new0 = 0;
}
if (new1 > domain.length - 1) {
new1 = domain.length - 1;
}
if (new0 > new1) {
if (t <= 0.5) {
new1 = new0;
} else {
new0 = new1;
}
}
if (new0 === range0 && new1 === range1) {
return bounds;
}
return [domain[new0], domain[new1]];
};
const invertLinearScaleBounds = (scale: ScaleObject, range: NumberArray): DomainBounds => {
const fullRange = scale.range();
const match = Math.sign(fullRange[1] - fullRange[0]) === Math.sign(range[1] - range[0]);
return [
scale.invert!(range[match ? 0 : 1]),
scale.invert!(range[match ? 1 : 0]),
];
};
const matchPointToBand = (domain: DomainItems, range: NumberArray, p: number) => {
const i = Math.floor(domain.length * (p - range[0]) / (range[1] - range[0]));
return domain[Math.min(i, domain.length - 1)];
};
const invertBandScaleBounds = (scale: ScaleObject, range: NumberArray): DomainBounds => {
const domain = scale.domain();
const fullRange = scale.range();
return [
matchPointToBand(domain, fullRange, range[0]),
matchPointToBand(domain, fullRange, range[1]),
];
};
// Though these functions are used only in *Viewport* plugin (and so should be placed right there),
// they reside here so that internal scale specifics (*getWidth*)
// are encapsulated in this utility file.
/** @internal */
export const scaleBounds = makeScaleHelper(scaleLinearBounds, scaleBandBounds);
/** @internal */
export const moveBounds = makeScaleHelper(moveLinearScaleBounds, moveBandScaleBounds);
// "scaleBounds" would be a better name but "scale" is already occupied.
/** @internal */
export const growBounds = makeScaleHelper(growLinearScaleBounds, growBandScaleBounds);
/** @internal */
export const invertBoundsRange = makeScaleHelper(invertLinearScaleBounds, invertBandScaleBounds); | the_stack |
import { ArnFormat, Duration, Resource, Stack, Token, TokenComparison, Aspects, Annotations } from '@aws-cdk/core';
import { Construct, IConstruct, DependencyGroup, Node } from 'constructs';
import { Grant } from './grant';
import { CfnRole } from './iam.generated';
import { IIdentity } from './identity-base';
import { IManagedPolicy, ManagedPolicy } from './managed-policy';
import { Policy } from './policy';
import { PolicyDocument } from './policy-document';
import { PolicyStatement } from './policy-statement';
import { AddToPrincipalPolicyResult, ArnPrincipal, IPrincipal, PrincipalPolicyFragment, IComparablePrincipal } from './principals';
import { defaultAddPrincipalToAssumeRole } from './private/assume-role-policy';
import { ImmutableRole } from './private/immutable-role';
import { MutatingPolicyDocumentAdapter } from './private/policydoc-adapter';
import { AttachedPolicies, UniqueStringSet } from './util';
const MAX_INLINE_SIZE = 10000;
const MAX_MANAGEDPOL_SIZE = 6000;
/**
* Properties for defining an IAM Role
*/
export interface RoleProps {
/**
* The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`)
* which can assume this role.
*
* You can later modify the assume role policy document by accessing it via
* the `assumeRolePolicy` property.
*/
readonly assumedBy: IPrincipal;
/**
* ID that the role assumer needs to provide when assuming this role
*
* If the configured and provided external IDs do not match, the
* AssumeRole operation will fail.
*
* @deprecated see {@link externalIds}
*
* @default No external ID required
*/
readonly externalId?: string;
/**
* List of IDs that the role assumer needs to provide one of when assuming this role
*
* If the configured and provided external IDs do not match, the
* AssumeRole operation will fail.
*
* @default No external ID required
*/
readonly externalIds?: string[];
/**
* A list of managed policies associated with this role.
*
* You can add managed policies later using
* `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
*
* @default - No managed policies.
*/
readonly managedPolicies?: IManagedPolicy[];
/**
* A list of named policies to inline into this role. These policies will be
* created with the role, whereas those added by ``addToPolicy`` are added
* using a separate CloudFormation resource (allowing a way around circular
* dependencies that could otherwise be introduced).
*
* @default - No policy is inlined in the Role resource.
*/
readonly inlinePolicies?: { [name: string]: PolicyDocument };
/**
* The path associated with this role. For information about IAM paths, see
* Friendly Names and Paths in IAM User Guide.
*
* @default /
*/
readonly path?: string;
/**
* AWS supports permissions boundaries for IAM entities (users or roles).
* A permissions boundary is an advanced feature for using a managed policy
* to set the maximum permissions that an identity-based policy can grant to
* an IAM entity. An entity's permissions boundary allows it to perform only
* the actions that are allowed by both its identity-based policies and its
* permissions boundaries.
*
* @link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-permissionsboundary
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html
*
* @default - No permissions boundary.
*/
readonly permissionsBoundary?: IManagedPolicy;
/**
* A name for the IAM role. For valid values, see the RoleName parameter for
* the CreateRole action in the IAM API Reference.
*
* IMPORTANT: If you specify a name, you cannot perform updates that require
* replacement of this resource. You can perform updates that require no or
* some interruption. If you must replace the resource, specify a new name.
*
* If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
* acknowledge your template's capabilities. For more information, see
* Acknowledging IAM Resources in AWS CloudFormation Templates.
*
* @default - AWS CloudFormation generates a unique physical ID and uses that ID
* for the role name.
*/
readonly roleName?: string;
/**
* The maximum session duration that you want to set for the specified role.
* This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours.
*
* Anyone who assumes the role from the AWS CLI or API can use the
* DurationSeconds API parameter or the duration-seconds CLI parameter to
* request a longer session. The MaxSessionDuration setting determines the
* maximum duration that can be requested using the DurationSeconds
* parameter.
*
* If users don't specify a value for the DurationSeconds parameter, their
* security credentials are valid for one hour by default. This applies when
* you use the AssumeRole* API operations or the assume-role* CLI operations
* but does not apply when you use those operations to create a console URL.
*
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html
*
* @default Duration.hours(1)
*/
readonly maxSessionDuration?: Duration;
/**
* A description of the role. It can be up to 1000 characters long.
*
* @default - No description.
*/
readonly description?: string;
}
/**
* Options allowing customizing the behavior of {@link Role.fromRoleArn}.
*/
export interface FromRoleArnOptions {
/**
* Whether the imported role can be modified by attaching policy resources to it.
*
* @default true
*/
readonly mutable?: boolean;
/**
* For immutable roles: add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
}
/**
* IAM Role
*
* Defines an IAM role. The role is created with an assume policy document associated with
* the specified AWS service principal defined in `serviceAssumeRole`.
*/
export class Role extends Resource implements IRole {
/**
* Import an external role by ARN.
*
* If the imported Role ARN is a Token (such as a
* `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced
* role has a `path` (like `arn:...:role/AdminRoles/Alice`), the
* `roleName` property will not resolve to the correct value. Instead it
* will resolve to the first path component. We unfortunately cannot express
* the correct calculation of the full path name as a CloudFormation
* expression. In this scenario the Role ARN should be supplied without the
* `path` in order to resolve the correct role resource.
*
* @param scope construct scope
* @param id construct id
* @param roleArn the ARN of the role to import
* @param options allow customizing the behavior of the returned role
*/
public static fromRoleArn(scope: Construct, id: string, roleArn: string, options: FromRoleArnOptions = {}): IRole {
const scopeStack = Stack.of(scope);
const parsedArn = scopeStack.splitArn(roleArn, ArnFormat.SLASH_RESOURCE_NAME);
const resourceName = parsedArn.resourceName!;
const roleAccount = parsedArn.account;
// service roles have an ARN like 'arn:aws:iam::<account>:role/service-role/<roleName>'
// or 'arn:aws:iam::<account>:role/service-role/servicename.amazonaws.com/service-role/<roleName>'
// we want to support these as well, so we just use the element after the last slash as role name
const roleName = resourceName.split('/').pop()!;
class Import extends Resource implements IRole, IComparablePrincipal {
public readonly grantPrincipal: IPrincipal = this;
public readonly principalAccount = roleAccount;
public readonly assumeRoleAction: string = 'sts:AssumeRole';
public readonly policyFragment = new ArnPrincipal(roleArn).policyFragment;
public readonly roleArn = roleArn;
public readonly roleName = roleName;
private readonly attachedPolicies = new AttachedPolicies();
private defaultPolicy?: Policy;
constructor(_scope: Construct, _id: string) {
super(_scope, _id, {
account: roleAccount,
});
}
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'Policy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
return { statementAdded: true, policyDependable: this.defaultPolicy };
}
public attachInlinePolicy(policy: Policy): void {
const thisAndPolicyAccountComparison = Token.compareStrings(this.env.account, policy.env.account);
const equalOrAnyUnresolved = thisAndPolicyAccountComparison === TokenComparison.SAME ||
thisAndPolicyAccountComparison === TokenComparison.BOTH_UNRESOLVED ||
thisAndPolicyAccountComparison === TokenComparison.ONE_UNRESOLVED;
if (equalOrAnyUnresolved) {
this.attachedPolicies.attach(policy);
policy.attachToRole(this);
}
}
public addManagedPolicy(_policy: IManagedPolicy): void {
// FIXME: Add warning that we're ignoring this
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantPassRole(identity: IPrincipal): Grant {
return this.grant(identity, 'iam:PassRole');
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantAssumeRole(identity: IPrincipal): Grant {
return this.grant(identity, 'sts:AssumeRole');
}
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
public grant(grantee: IPrincipal, ...actions: string[]): Grant {
return Grant.addToPrincipal({
grantee,
actions,
resourceArns: [this.roleArn],
scope: this,
});
}
public dedupeString(): string | undefined {
return `ImportedRole:${roleArn}`;
}
}
if (options.addGrantsToResources !== undefined && options.mutable !== false) {
throw new Error('\'addGrantsToResources\' can only be passed if \'mutable: false\'');
}
const roleArnAndScopeStackAccountComparison = Token.compareStrings(roleAccount ?? '', scopeStack.account);
const equalOrAnyUnresolved = roleArnAndScopeStackAccountComparison === TokenComparison.SAME ||
roleArnAndScopeStackAccountComparison === TokenComparison.BOTH_UNRESOLVED ||
roleArnAndScopeStackAccountComparison === TokenComparison.ONE_UNRESOLVED;
// if we are returning an immutable role then the 'importedRole' is just a throwaway construct
// so give it a different id
const mutableRoleId = (options.mutable !== false && equalOrAnyUnresolved) ? id : `MutableRole${id}`;
const importedRole = new Import(scope, mutableRoleId);
// we only return an immutable Role if both accounts were explicitly provided, and different
return options.mutable !== false && equalOrAnyUnresolved
? importedRole
: new ImmutableRole(scope, id, importedRole, options.addGrantsToResources ?? false);
}
/**
* Import an external role by name.
*
* The imported role is assumed to exist in the same account as the account
* the scope's containing Stack is being deployed to.
*/
public static fromRoleName(scope: Construct, id: string, roleName: string) {
return Role.fromRoleArn(scope, id, Stack.of(scope).formatArn({
region: '',
service: 'iam',
resource: 'role',
resourceName: roleName,
}));
}
public readonly grantPrincipal: IPrincipal = this;
public readonly principalAccount: string | undefined = this.env.account;
public readonly assumeRoleAction: string = 'sts:AssumeRole';
/**
* The assume role policy document associated with this role.
*/
public readonly assumeRolePolicy?: PolicyDocument;
/**
* Returns the ARN of this role.
*/
public readonly roleArn: string;
/**
* Returns the stable and unique string identifying the role. For example,
* AIDAJQABLZS4A3QDU576Q.
*
* @attribute
*/
public readonly roleId: string;
/**
* Returns the name of the role.
*/
public readonly roleName: string;
/**
* Returns the role.
*/
public readonly policyFragment: PrincipalPolicyFragment;
/**
* Returns the permissions boundary attached to this role
*/
public readonly permissionsBoundary?: IManagedPolicy;
private defaultPolicy?: Policy;
private readonly managedPolicies: IManagedPolicy[] = [];
private readonly attachedPolicies = new AttachedPolicies();
private readonly inlinePolicies: { [name: string]: PolicyDocument };
private readonly dependables = new Map<PolicyStatement, DependencyGroup>();
private immutableRole?: IRole;
private _didSplit = false;
constructor(scope: Construct, id: string, props: RoleProps) {
super(scope, id, {
physicalName: props.roleName,
});
const externalIds = props.externalIds || [];
if (props.externalId) {
externalIds.push(props.externalId);
}
this.assumeRolePolicy = createAssumeRolePolicy(props.assumedBy, externalIds);
this.managedPolicies.push(...props.managedPolicies || []);
this.inlinePolicies = props.inlinePolicies || {};
this.permissionsBoundary = props.permissionsBoundary;
const maxSessionDuration = props.maxSessionDuration && props.maxSessionDuration.toSeconds();
validateMaxSessionDuration(maxSessionDuration);
const description = (props.description && props.description?.length > 0) ? props.description : undefined;
if (description && description.length > 1000) {
throw new Error('Role description must be no longer than 1000 characters.');
}
validateRolePath(props.path);
const role = new CfnRole(this, 'Resource', {
assumeRolePolicyDocument: this.assumeRolePolicy as any,
managedPolicyArns: UniqueStringSet.from(() => this.managedPolicies.map(p => p.managedPolicyArn)),
policies: _flatten(this.inlinePolicies),
path: props.path,
permissionsBoundary: this.permissionsBoundary ? this.permissionsBoundary.managedPolicyArn : undefined,
roleName: this.physicalName,
maxSessionDuration,
description,
});
this.roleId = role.attrRoleId;
this.roleArn = this.getResourceArnAttribute(role.attrArn, {
region: '', // IAM is global in each partition
service: 'iam',
resource: 'role',
// Removes leading slash from path
resourceName: `${props.path ? props.path.substr(props.path.charAt(0) === '/' ? 1 : 0) : ''}${this.physicalName}`,
});
this.roleName = this.getResourceNameAttribute(role.ref);
this.policyFragment = new ArnPrincipal(this.roleArn).policyFragment;
function _flatten(policies?: { [name: string]: PolicyDocument }) {
if (policies == null || Object.keys(policies).length === 0) {
return undefined;
}
const result = new Array<CfnRole.PolicyProperty>();
for (const policyName of Object.keys(policies)) {
const policyDocument = policies[policyName];
result.push({ policyName, policyDocument });
}
return result;
}
Aspects.of(this).add({
visit: (c) => {
if (c === this) {
this.splitLargePolicy();
}
},
});
this.node.addValidation({ validate: () => this.validateRole() });
}
/**
* Adds a permission to the role's default policy document.
* If there is no default policy attached to this role, it will be created.
* @param statement The permission statement to add to the policy document
*/
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'DefaultPolicy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
// We might split this statement off into a different policy, so we'll need to
// late-bind the dependable.
const policyDependable = new DependencyGroup();
this.dependables.set(statement, policyDependable);
return { statementAdded: true, policyDependable };
}
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
/**
* Attaches a managed policy to this role.
* @param policy The the managed policy to attach.
*/
public addManagedPolicy(policy: IManagedPolicy) {
if (this.managedPolicies.find(mp => mp === policy)) { return; }
this.managedPolicies.push(policy);
}
/**
* Attaches a policy to this role.
* @param policy The policy to attach
*/
public attachInlinePolicy(policy: Policy) {
this.attachedPolicies.attach(policy);
policy.attachToRole(this);
}
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
public grant(grantee: IPrincipal, ...actions: string[]) {
return Grant.addToPrincipal({
grantee,
actions,
resourceArns: [this.roleArn],
scope: this,
});
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantPassRole(identity: IPrincipal) {
return this.grant(identity, 'iam:PassRole');
}
/**
* Grant permissions to the given principal to assume this role.
*/
public grantAssumeRole(identity: IPrincipal) {
return this.grant(identity, 'sts:AssumeRole');
}
/**
* Return a copy of this Role object whose Policies will not be updated
*
* Use the object returned by this method if you want this Role to be used by
* a construct without it automatically updating the Role's Policies.
*
* If you do, you are responsible for adding the correct statements to the
* Role's policies yourself.
*/
public withoutPolicyUpdates(options: WithoutPolicyUpdatesOptions = {}): IRole {
if (!this.immutableRole) {
this.immutableRole = new ImmutableRole(Node.of(this).scope as Construct, `ImmutableRole${this.node.id}`, this, options.addGrantsToResources ?? false);
}
return this.immutableRole;
}
private validateRole(): string[] {
const errors = new Array<string>();
errors.push(...this.assumeRolePolicy?.validateForResourcePolicy() ?? []);
for (const policy of Object.values(this.inlinePolicies)) {
errors.push(...policy.validateForIdentityPolicy());
}
return errors;
}
/**
* Split large inline policies into managed policies
*
* This gets around the 10k bytes limit on role policies.
*/
private splitLargePolicy() {
if (!this.defaultPolicy || this._didSplit) {
return;
}
this._didSplit = true;
const self = this;
const originalDoc = this.defaultPolicy.document;
const splitOffDocs = originalDoc._splitDocument(this, MAX_INLINE_SIZE, MAX_MANAGEDPOL_SIZE);
// Includes the "current" document
const mpCount = this.managedPolicies.length + (splitOffDocs.size - 1);
if (mpCount > 20) {
Annotations.of(this).addWarning(`Policy too large: ${mpCount} exceeds the maximum of 20 managed policies attached to a Role`);
} else if (mpCount > 10) {
Annotations.of(this).addWarning(`Policy large: ${mpCount} exceeds 10 managed policies attached to a Role, this requires a quota increase`);
}
// Create the managed policies and fix up the dependencies
markDeclaringConstruct(originalDoc, this.defaultPolicy);
let i = 1;
for (const newDoc of splitOffDocs.keys()) {
if (newDoc === originalDoc) { continue; }
const mp = new ManagedPolicy(this, `OverflowPolicy${i++}`, {
description: `Part of the policies for ${this.node.path}`,
document: newDoc,
roles: [this],
});
markDeclaringConstruct(newDoc, mp);
}
/**
* Update the Dependables for the statements in the given PolicyDocument to point to the actual declaring construct
*/
function markDeclaringConstruct(doc: PolicyDocument, declaringConstruct: IConstruct) {
for (const original of splitOffDocs.get(doc) ?? []) {
self.dependables.get(original)?.add(declaringConstruct);
}
}
}
}
/**
* A Role object
*/
export interface IRole extends IIdentity {
/**
* Returns the ARN of this role.
*
* @attribute
*/
readonly roleArn: string;
/**
* Returns the name of this role.
*
* @attribute
*/
readonly roleName: string;
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
grant(grantee: IPrincipal, ...actions: string[]): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
grantPassRole(grantee: IPrincipal): Grant;
/**
* Grant permissions to the given principal to assume this role.
*/
grantAssumeRole(grantee: IPrincipal): Grant;
}
function createAssumeRolePolicy(principal: IPrincipal, externalIds: string[]) {
const actualDoc = new PolicyDocument();
// If requested, add externalIds to every statement added to this doc
const addDoc = externalIds.length === 0
? actualDoc
: new MutatingPolicyDocumentAdapter(actualDoc, (statement) => {
statement.addCondition('StringEquals', {
'sts:ExternalId': externalIds.length === 1 ? externalIds[0] : externalIds,
});
return statement;
});
defaultAddPrincipalToAssumeRole(principal, addDoc);
return actualDoc;
}
function validateRolePath(path?: string) {
if (path === undefined || Token.isUnresolved(path)) {
return;
}
const validRolePath = /^(\/|\/[\u0021-\u007F]+\/)$/;
if (path.length == 0 || path.length > 512) {
throw new Error(`Role path must be between 1 and 512 characters. The provided role path is ${path.length} characters.`);
} else if (!validRolePath.test(path)) {
throw new Error(
'Role path must be either a slash or valid characters (alphanumerics and symbols) surrounded by slashes. '
+ `Valid characters are unicode characters in [\\u0021-\\u007F]. However, ${path} is provided.`);
}
}
function validateMaxSessionDuration(duration?: number) {
if (duration === undefined) {
return;
}
if (duration < 3600 || duration > 43200) {
throw new Error(`maxSessionDuration is set to ${duration}, but must be >= 3600sec (1hr) and <= 43200sec (12hrs)`);
}
}
/**
* Options for the `withoutPolicyUpdates()` modifier of a Role
*/
export interface WithoutPolicyUpdatesOptions {
/**
* Add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
} | the_stack |
export namespace BugReporting {
/**
* Enables and disables manual invocation and prompt options for bug and feedback.
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Sets the events that invoke the feedback form.
* Default is set by `Instabug.start`.
* @param {invocationEvent} invocationEvents Array of events that invokes the
* feedback form.
*/
function setInvocationEvents(invocationEvents: invocationEvent[]): void;
/**
* Sets the invocation options.
* Default is set by `Instabug.start`.
* @param {options} options Array of options
*/
function setOptions(options: option[]): void;
/**
* Sets a block of code to be executed just before the SDK's UI is presented.
* This block is executed on the UI thread. Could be used for performing any
* UI changes before the SDK's UI is shown.
* @param {function} handler - A callback that gets executed before invoking the SDK
*/
function onInvokeHandler(handler: () => void): void;
/**
* Sets a block of code to be executed right after the SDK's UI is dismissed.
* This block is executed on the UI thread. Could be used for performing any
* UI changes after the SDK's UI is dismissed.
* @param {function} handler - A callback to get executed after
* dismissing the SDK.
*/
function onSDKDismissedHandler(
handler: (dismiss: dismissType, report: reportType) => void
): void;
/**
* Sets a block of code to be executed when a prompt option is selected.
* @param {function} didSelectPromptOptionHandler - A block of code that
* gets executed when a prompt option is selected.
*/
function setDidSelectPromptOptionHandler(
didSelectPromptOptionHandler: () => void
): void;
/**
* Sets the default edge and offset from the top at which the floating button
* will be shown. Different orientations are already handled.
* Default for `floatingButtonEdge` is `rectEdge.maxX`.
* Default for `floatingButtonOffsetFromTop` is 50
* @param {rectEdge} floatingButtonEdge `maxX` to show on the right,
* or `minX` to show on the left.
* @param {number} offsetFromTop floatingButtonOffsetFromTop Top offset for
* floating button.
*/
function setFloatingButtonEdge(
floatingButtonEdge: number,
offsetFromTop: number
): void;
/**
* Sets whether attachments in bug reporting and in-app messaging are enabled or not.
* @param {boolean} screenshot A boolean to enable or disable screenshot attachments.
* @param {boolean} extraScreenshot A boolean to enable or disable extra
* screenshot attachments.
* @param {boolean} galleryImage A boolean to enable or disable gallery image
* attachments. In iOS 10+,NSPhotoLibraryUsageDescription should be set in
* info.plist to enable gallery image attachments.
* @param {boolean} screenRecording A boolean to enable or disable screen recording attachments.
*/
function setEnabledAttachmentTypes(
screenshot: boolean,
extraScreenshot: boolean,
galleryImage: boolean,
screenRecording: boolean
): void;
/**
* Sets the threshold value of the shake gesture for iPhone/iPod Touch
* Default for iPhone is 2.5.
* @param {number} iPhoneShakingThreshold Threshold for iPhone.
*/
function setShakingThresholdForiPhone(iPhoneShakingThreshold: number): void;
/**
* Sets the threshold value of the shake gesture for iPad.
* Default for iPad is 0.6.
* @param {number} iPadShakingThreshold Threshold for iPad.
*/
function setShakingThresholdForiPad(iPadShakingThreshold: number): void;
/**
* Sets the threshold value of the shake gesture for android devices.
* Default for android is an integer value equals 350.
* you could increase the shaking difficulty level by
* increasing the `350` value and vice versa
* @param {number} androidThreshold Threshold for android devices.
*/
function setShakingThresholdForAndroid(androidThreshold: number): void;
/**
* Sets whether the extended bug report mode should be disabled, enabled with
* required fields or enabled with optional fields.
* @param {extendedBugReportMode} extendedBugReportMode An enum to disable
* the extended bug report mode, enable it
* with required or with optional fields.
*/
function setExtendedBugReportMode(
extendedBugReportMode: extendedBugReportMode
): void;
/**
* Sets what type of reports, bug or feedback, should be invoked.
* @param {array} types - Array of reportTypes
*/
function setReportTypes(types: reportType[]): void;
/**
* Invoke bug reporting with report type and options.
* @param {reportType} type
* @param {option} options
*/
function show(type: reportType, options: option[]): void;
/**
* Enable/Disable screen recording
* @param {boolean} autoScreenRecordingEnabled boolean for enable/disable
* screen recording on crash feature
*/
function setAutoScreenRecordingEnabled(autoScreenRecordingEnabled: boolean): void;
/**
* Sets auto screen recording maximum duration
*
* @param autoScreenRecordingMaxDuration maximum duration of the screen recording video
* in seconds
* The maximum duration is 30 seconds
*/
function setAutoScreenRecordingDurationIOS(
autoScreenRecordingMaxDuration: number
): void;
/**
* @summary Enables/disables inspect view hierarchy when reporting a bug/feedback.
* @param {boolean} viewHierarchyEnabled A boolean to set whether view hierarchy are enabled
* or disabled.
*/
function setViewHierarchyEnabled(viewHierarchyEnabled: boolean): void;
/**
* Sets the default position at which the Instabug screen recording button will be shown.
* Different orientations are already handled.
* (Default for `position` is `bottomRight`)
*
* @param position is of type position `topLeft` to show on the top left of screen,
* or `bottomRight` to show on the bottom right of scrren.
*/
function setVideoRecordingFloatingButtonPosition(
position: BugReporting.position
): void;
/**
* The event used to invoke the feedback form
* @readonly
* @enum {number}
*/
enum invocationEvent {
none,
shake,
screenshot,
twoFingersSwipe,
floatingButton
}
/**
* The extended bug report mode
* @readonly
* @enum {number}
*/
enum extendedBugReportMode {
enabledWithRequiredFields,
enabledWithOptionalFields,
disabled
}
/**
* Type of the report either feedback or bug.
* @readonly
* @enum {number}
*/
enum reportType {
bug,
feedback,
question
}
/**
* Options added while invoking bug reporting.
* @readonly
* @enum {number}
*/
enum option {
emailFieldHidden,
emailFieldOptional,
commentFieldRequired,
disablePostSendingDialog
}
/**
* Instabug floating buttons positions.
* @readonly
* @enum {number}
*/
enum position {
bottomRight,
topRight,
bottomLeft,
topLeft
}
}
export namespace CrashReporting {
/**
* Enables and disables everything related to crash reporting including intercepting
* errors in the global error handler. It is enabled by default.
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Send handled JS error object
*
* @param errorObject Error object to be sent to Instabug's servers
*/
function reportJSException(errorObject: object): void;
}
export namespace FeatureRequests {
/**
* Sets whether users are required to enter an email address or not when
* sending reports.
* Defaults to YES.
* @param {boolean} isEmailFieldRequired A boolean to indicate whether email
* field is required or not.
* @param {actionTypes} actionTypes An enum that indicates which action
* types will have the isEmailFieldRequired
*/
function setEmailFieldRequired(
isEmailFieldRequired: boolean,
actionTypes: actionTypes[]
): void;
/**
* Enables and disables everything related to feature requests.
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Shows the UI for feature requests list
*
*/
function show(): void;
/**
* Instabug action types.
* @readonly
* @enum {number}
*/
enum actionTypes {
requestNewFeature,
addCommentToFeature
}
}
export namespace Replies {
/**
* Enables and disables everything related to receiving replies.
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Tells whether the user has chats already or not.
* @param {function} callback - callback that is invoked if chats exist
*/
function hasChats(callback: (previousChats: boolean) => void): void;
/**
* Manual invocation for replies.
*/
function show(): void;
/**
* Sets a block of code that gets executed when a new message is received.
* @param {function} onNewReplyReceivedHandler - A callback that gets
* executed when a new message is received.
*/
function setOnNewReplyReceivedHandler(
onNewReplyReceivedHandler: () => void
): void;
/**
* Returns the number of unread messages the user currently has.
* Use this method to get the number of unread messages the user
* has, then possibly notify them about it with your own UI.
* @param {messageCountCallback} messageCountCallback callback with argument
* Notifications count, or -1 in case the SDK has not been initialized.
*/
function getUnreadRepliesCount(
messageCountCallback: (count: number) => void
): void;
/**
* Enables/disables showing in-app notifications when the user receives a
* new message.
* @param {boolean} inAppNotificationsEnabled A boolean to set whether
* notifications are enabled or disabled.
*/
function setInAppNotificationsEnabled(
inAppNotificationsEnabled: boolean
): void;
/**
* Enables/disables the use of push notifications in the SDK.
* Defaults to YES.
* @param {boolean} isPushNotificationEnabled A boolean to indicate whether push
* notifications are enabled or disabled.
*/
function setPushNotificationsEnabled(
isPushNotificationEnabled: boolean
): void;
/**
* Set whether new in app notification received will play a small sound notification
* or not (Default is {@code false})
* @android
*
* @param shouldPlaySound desired state of conversation sounds
*/
function setInAppNotificationSound(shouldPlaySound: boolean): void;
/**
* Set the GCM registration token to Instabug
*
* @param token the GCM registration token
*/
function setPushNotificationRegistrationTokenAndroid(token: string): void;
/**
* Show in-app Messaging's notifications
*
* @param data the data bundle related to Instabug
*/
function showNotificationAndroid(data: object): void;
/**
* Set the push notification's icon that will be shown with Instabug notifications
*
* @param notificationIcon the notification icon resource ID
*/
function setNotificationIconAndroid(notificationIcon: number): void;
/**
* Set a notification channel id to a notification channel that notifications
* can be posted to.
*
* @param pushNotificationChannelId an id to a notification channel that notifications
*/
function setPushNotificationChannelIdAndroid(pushNotificationChannelId: string): void;
/**
* Set whether new system notification received will play the default sound from
* RingtoneManager or not (Default is {@code false})
*
* @param shouldPlaySound desired state of conversation sounds
*/
function setSystemReplyNotificationSoundEnabledAndroid(shouldPlaySound: boolean): void;
}
export namespace Surveys {
/**
* @summary Sets whether surveys are enabled or not.
* If you disable surveys on the SDK but still have active surveys on your Instabug dashboard,
* those surveys are still going to be sent to the device, but are not going to be
* shown automatically.
* To manually display any available surveys, call `Instabug.showSurveyIfAvailable()`.
* Defaults to `true`.
* @param {boolean} isEnabled A boolean to set whether Instabug Surveys is enabled or disabled.
*/
function setEnabled(isEnabled: boolean): void;
/**
* @summary Shows one of the surveys that were not shown before, that also have conditions
* that match the current device/user.
* Does nothing if there are no available surveys or if a survey has already been shown
* in the current session.
*/
function showSurveyIfAvailable(): void;
/**
* Returns an array containing the available surveys.
* @param {availableSurveysCallback} availableSurveysCallback callback with
* argument available surveys
*
*/
function getAvailableSurveys(
availableSurveysCallback: (surveys: Survey[]) => void
): void;
/**
* Sets whether auto surveys showing are enabled or not.
* @param autoShowingSurveysEnabled A boolean to indicate whether the
* surveys auto showing are enabled or not.
*
*/
function setAutoShowingEnabled(autoShowingSurveysEnabled: boolean): void;
/**
* @summary Sets a block of code to be executed just before the survey's UI is presented.
* This block is executed on the UI thread. Could be used for performing any UI changes before
* the survey's UI is shown.
* @param {function} onShowHandler - A block of code that gets executed before
* presenting the survey's UI.
*/
function setOnShowHandler(onShowHandler: () => void): void;
/**
* @summary Sets a block of code to be executed right after the survey's UI is dismissed.
* This block is executed on the UI thread. Could be used for performing any UI
* changes after the survey's UI is dismissed.
* @param {function} onDismissHandler - A block of code that gets executed after
* the survey's UI is dismissed.
*/
function setOnDismissHandler(onDismissHandler: () => void): void;
/**
* Shows survey with a specific token.
* Does nothing if there are no available surveys with that specific token.
* Answered and cancelled surveys won't show up again.
* @param {string} surveyToken - A String with a survey token.
*
*/
function showSurvey(surveyToken: string): void;
/**
* Returns true if the survey with a specific token was answered before.
* Will return false if the token does not exist or if the survey was not answered before.
* @param {string} surveyToken - A String with a survey token.
* @param {function} surveyTokenCallback callback with argument as the desired value of the whether
* the survey has been responded to or not.
*
*/
function hasRespondedToSurvey(
surveyToken: string,
surveyTokenCallback: (hasResponded: boolean) => void
): void;
/**
* Setting an option for all the surveys to show a welcome screen before
* the user starts taking the survey.
* @param shouldShowWelcomeScreen A boolean for setting whether the
* welcome screen should show.
*
*/
function setShouldShowWelcomeScreen(shouldShowWelcomeScreen: boolean): void;
/**
* iOS Only
* @summary Sets url for the published iOS app on AppStore, You can redirect
* NPS Surveys or AppRating Surveys to AppStore to let users rate your app on AppStore itself.
* @param {String} appStoreURL A String url for the published iOS app on AppStore
*/
function setAppStoreURL(appStoreURL: string): void;
}
export namespace NetworkLogger {
/**
* Sets whether network logs should be sent with bug reports.
* It is enabled by default.
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Obfuscates any response data.
* @param {function} handler
*/
function setNetworkDataObfuscationHandler(handler: (networkData: any) => any): void;
/**
* Omit requests from being logged based on either their request or response details
* @param {string} expression
*/
function setRequestFilterExpression(expression: string): void;
/**
* Returns progress in terms of totalBytesSent and totalBytesExpectedToSend a network request.
* @param {function} handler
*/
function setProgressHandlerForRequest(handler: () => void): void;
/**
* Apollo Link Request Handler to track network log for graphQL using apollo
* @param {any} operation
* @param {any} forward
*/
function apolloLinkRequestHandler(operation: any, forward: any):any;
}
export class Trace {
constructor(id: string, name?: string, attributes?: object);
/**
* Add an attribute with key and value to the Trace to be sent.
* @param {string} key
* @param {string} value
*/
setAttribute(key: string, value: string): void;
/**
* End Execution Trace
*/
end(): void;
}
export namespace APM {
/**
* Enables or disables APM
* @param {boolean} isEnabled
*/
function setEnabled(isEnabled: boolean): void;
/**
* Enables or disables APM App Launch
* @param {boolean} isEnabled
*/
function setAppLaunchEnabled(isEnabled: boolean): void;
/**
* Ends the current session’s App Launch. Calling this API is optional, App Launches will still be captured and ended automatically by the SDK;
* this API just allows you to change when an App Launch actually ends.
*/
function endAppLaunch(): void;
/**
* Enables or disables APM Network Metric
* @param {boolean} isEnabled
*/
function setNetworkEnabledIOS(isEnabled: boolean): void;
/**
* Enables or disables APM UI Responsivenes tracking feature
* @param {boolean} isEnabled
*/
function setAutoUITraceEnabled(isEnabled: boolean): void;
/**
* Starts a custom trace
* Returns a promise, the promise delivers the trace reference if APM is enabled, otherwise it gets rejected
* @param {string} name
*/
function startExecutionTrace(name: string): Promise<Trace>;
/**
* Starts a custom trace
* @param {string} name
*/
function startUITrace(name: string): void;
/**
* Starts a custom trace
* @param {string} name
*/
function endUITrace(): void;
/**
* Sets the printed logs priority. Filter to one of the following levels:
*
* - logLevelNone disables all APM SDK console logs.
*
* - logLevelError prints errors only, we use this level to let you know if something goes wrong.
*
* - logLevelWarning displays warnings that will not necessarily lead to errors but should be addressed nonetheless.
*
* - logLevelInfo (default) logs information that we think is useful without being too verbose.
*
* - logLevelDebug use this in case you are debugging an issue. Not recommended for production use.
*
* - logLevelVerbose use this only if logLevelDebug was not enough and you need more visibility
* on what is going on under the hood.
*
* Similar to the logLevelDebug level, this is not meant to be used on production environments.
*
* Each log level will also include logs from all the levels above it. For instance,
* logLevelInfo will include logLevelInfo logs as well as logLevelWarning
* and logLevelError logs.
* @param {logLevel} logLevel the printed logs priority.
*/
function setLogLevel(logLevel: logLevel): void;
/**
* APM Log Level.
* @readonly
* @enum {number}
*/
enum logLevel {
none,
error,
warning,
info,
debug,
verbose,
}
}
/**
* Starts the SDK.
* This is the main SDK method that does all the magic. This is the only
* method that SHOULD be called.
* Should be called in constructor of the AppRegistry component
* @param {string} token The token that identifies the app, you can find
* it on your dashboard.
* @param {invocationEvent} invocationEvent The event that invokes
* the SDK's UI.
*/
export function start(token: string, invocationEvent: invocationEvent[]): void;
/**
* Attaches user data to each report being sent.
* Each call to this method overrides the user data to be attached.
* Maximum size of the string is 1,000 characters.
* @param {string} userData A string to be attached to each report, with a
* maximum size of 1,000 characters.
*/
export function setUserData(userData: string): void;
/**
* Sets whether the SDK is tracking user steps or not.
* Enabling user steps would give you an insight on the scenario a user has
* performed before encountering a bug or a crash. User steps are attached
* with each report being sent.
* @param {boolean} isEnabled A boolean to set user steps tracking
* to being enabled or disabled.
*/
export function setTrackUserSteps(isEnabled: boolean): void;
/**
* Sets whether IBGLog should also print to Xcode's console log or not.
* @param {boolean} printsToConsole A boolean to set whether printing to
* Xcode's console is enabled or not.
*/
export function setIBGLogPrintsToConsole(printsToConsole: boolean): void;
/**
* The session profiler is enabled by default and it attaches to the bug and
* crash reports the following information during the last 60 seconds before the report is sent.
* @param {boolean} sessionProfilerEnabled - A boolean parameter to enable or disable the feature.
*
*/
export function setSessionProfilerEnabled(
sessionProfilerEnabled: boolean
): void;
/**
* This API sets the verbosity level of logs used to debug The SDK. The defualt value in debug
* mode is sdkDebugLogsLevelVerbose and in production is sdkDebugLogsLevelError.
* @param {sdkDebugLogsLevel} sdkDebugLogsLevel - The verbosity level of logs.
*
*/
export function setSdkDebugLogsLevel(
sdkDebugLogsLevel: sdkDebugLogsLevel
): void;
/**
* Sets the SDK's locale.
* Use to change the SDK's UI to different language.
* Defaults to the device's current locale.
* @param {locale} locale A locale to set the SDK to.
*/
export function setLocale(locale: locale): void;
/**
* Sets the color theme of the SDK's whole UI.
* the SDK's UI to.
* @param colorTheme
*/
export function setColorTheme(colorTheme: colorTheme): void;
/**
* Sets the primary color of the SDK's UI.
* Sets the color of UI elements indicating interactivity or call to action.
* To use, import processColor and pass to it with argument the color hex
* as argument.
* @param {color} color A color to set the UI elements of the SDK to.
*/
export function setPrimaryColor(color: string): void;
/**
* Appends a set of tags to previously added tags of reported feedback,
* bug or crash.
* @param {string[]} tags An array of tags to append to current tags.
*/
export function appendTags(tags: string[]): void;
/**
* Manually removes all tags of reported feedback, bug or crash.
*/
export function resetTags(): void;
/**
* Gets all tags of reported feedback, bug or crash.
* @param {tagsCallback} tagsCallback callback with argument tags of reported feedback, bug or crash.
*/
export function getTags(tagsCallback: () => void): void;
/**
* Overrides any of the strings shown in the SDK with custom ones.
* Allows you to customize any of the strings shown to users in the SDK.
* @param {string} string String value to override the default one.
* @param {strings} key Key of string to override.
*/
export function setString(key: strings, string: string): void;
/**
* Sets the default value of the user's email and hides the email field from the reporting UI
* and set the user's name to be included with all reports.
* It also reset the chats on device to that email and removes user attributes,
* user data and completed surveys.
* @param {string} email Email address to be set as the user's email.
* @param {string} name Name of the user to be set.
*/
export function identifyUser(email: string, name: string): void;
/**
* Sets the default value of the user's email to nil and show email field and remove user name
* from all reports
* It also reset the chats on device and removes user attributes, user data and completed surveys.
*/
export function logOut(): void;
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a session.
* @param {string} name Event name.
*/
export function logUserEvent(name: string): void;
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run.
* If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message the message
*/
export function logVerbose(message: string): void;
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run.
* If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message the message
*/
export function logInfo(message: string): void;
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run.
* If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message the message
*/
export function logDebug(message: string): void;
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run.
* If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message the message
*/
export function logError(message: string): void;
/**
* Appends a log message to Instabug internal log
* <p>
* These logs are then sent along the next uploaded report.
* All log messages are timestamped <br/>
* Logs aren't cleared per single application run.
* If you wish to reset the logs,
* use {@link #clearLogs()} ()}
* </p>
* Note: logs passed to this method are <b>NOT</b> printed to Logcat
*
* @param message the message
*/
export function logWarn(message: string): void;
/**
* Clear all Instabug logs, console logs, network logs and user steps.
*/
export function clearLogs(): void;
/**
* Sets whether user steps tracking is visual, non visual or disabled.
* User Steps tracking is enabled by default if it's available
* in your current plan.
*
* @param {reproStepsMode} reproStepsMode An enum to set user steps tracking
* to be enabled, non visual or disabled.
*/
export function setReproStepsMode(reproStepsMode: reproStepsMode): void;
/**
* Sets user attribute to overwrite it's value or create a new one if it doesn't exist.
*
* @param key the attribute
* @param value the value
*/
export function setUserAttribute(key: string, value: string): void;
/**
* Returns the user attribute associated with a given key.
aKey
* @param {string} key The attribute key as string
* @param {function} userAttributeCallback callback with argument as the desired user attribute value
*/
export function getUserAttribute(
key: string,
userAttributeCallback: () => void
): void;
/**
* Removes user attribute if exists.
*
* @param key the attribute key as string
* @see #setUserAttribute(String, String)
*/
export function removeUserAttribute(key: string): void;
/**
* @summary Returns all user attributes.
* @param {function} userAttributesCallback callback with argument A new dictionary containing
* all the currently set user attributes, or an empty dictionary if no user attributes have been set.
*/
export function getAllUserAttributes(userAttributesCallback: () => void): void;
/**
* Clears all user attributes if exists.
*/
export function clearAllUserAttributes(): void;
/**
* Enable/Disable debug logs from Instabug SDK
* Default state: disabled
*
* @param isDebugEnabled whether debug logs should be printed or not into LogCat
*/
export function setDebugEnabled(isDebugEnabled: boolean): void;
/**
* Enables all Instabug functionality
* It works on android only
*/
export function enable(): void;
/**
* Disables all Instabug functionality
* It works on android only
*/
export function disable(): void;
/**
* @summary Checks whether app is development/Beta testing OR live
* Note: This API is iOS only
* It returns in the callback false if in development or beta testing on Test Flight, and
* true if app is live on the app store.
* @param {function} runningLiveCallBack callback with argument as return value 'isLive'
*/
export function isRunningLive(runningLiveCallBack: (isLive: boolean) => void): void;
/**
* Shows the welcome message in a specific mode.
* @param welcomeMessageMode An enum to set the welcome message mode to
* live, or beta.
*
*/
export function showWelcomeMessage(
welcomeMessageMode: welcomeMessageMode
): void;
/**
* Sets the welcome message mode to live, beta or disabled.
* @param welcomeMessageMode An enum to set the welcome message mode to
* live, beta or disabled.
*
*/
export function setWelcomeMessageMode(
welcomeMessageMode: welcomeMessageMode
): void;
/**
* Add file to be attached to the bug report.
* @param {string} filePath
* @param {string} fileName
*/
export function addFileAttachment(filePath: string, fileName: string): void;
/**
* @deprecated Use {@link Instabug.addPrivateView} instead.
*
* Hides component from screenshots, screen recordings and view hierarchy.
* @param {Object} viewRef the ref of the component to hide
*/
export function setPrivateView(viewRef: object): void;
/**
* Hides component from screenshots, screen recordings and view hierarchy.
* @param {Object} viewRef the ref of the component to hide
*/
export function addPrivateView(viewRef: object): void;
/**
* Removes component from the set of hidden views. The component will show again in
* screenshots, screen recordings and view hierarchy.
* @param {Object} viewRef the ref of the component to remove from hidden views
*/
export function removePrivateView(viewRef: object): void;
/**
* Shows default Instabug prompt.
*/
export function show(): void;
export function onReportSubmitHandler(
preSendingHandler: (presendingHandler: Report) => void
): void;
export function callPrivateApi(apiName: string, param: any): void;
export function onNavigationStateChange(
prevState: any,
currentState: any,
action: any
): void;
export function onStateChange(
state: any
): void;
export function reportScreenChange(
screenName: string
): void;
/**
* Add experiments to next report.
* @param {string[]} experiments An array of experiments to add to the next report.
*/
export function addExperiments(experiments:string[]): void;
/**
* Remove experiments from next report.
* @param {string[]} experiments An array of experiments to remove from the next report.
*/
export function removeExperiments(experiments: string[]): void;
/**
* Clear all experiments
*/
export function clearAllExperiments(): void;
export function componentDidAppearListener(componentObj:
{ componentId: any, componentName: any, passProps: any }
): void;
/**
* The event used to invoke the feedback form
* @readonly
* @enum {number}
*/
export enum invocationEvent {
none,
shake,
screenshot,
twoFingersSwipe,
floatingButton
}
/**
* The user steps option.
* @readonly
* @enum {number}
*/
export enum reproStepsMode {
enabled,
disabled,
enabledWithNoScreenshots
}
/**
* Type of SDK dismiss
* @readonly
* @enum {number}
*/
export enum dismissType {
submit,
cancel,
addAttachment
}
/**
* Verbosity level of the SDK debug logs. This has nothing to do with IBGLog,
* and only affect the logs used to debug the SDK itself.
* @readonly
* @enum {number}
*/
export enum sdkDebugLogsLevel {
sdkDebugLogsLevelVerbose,
sdkDebugLogsLevelDebug,
sdkDebugLogsLevelError,
sdkDebugLogsLevelNone,
}
/**
* The extended bug report mode
* @readonly
* @enum {number}
*/
export enum extendedBugReportMode {
enabledWithRequiredFields,
enabledWithOptionalFields,
disabled
}
/**
* The supported locales
* @readonly
* @enum {number}
*/
export enum locale {
arabic,
azerbaijani,
chineseSimplified,
chineseTraditional,
czech,
danish,
dutch,
english,
french,
german,
italian,
japanese,
polish,
portugueseBrazil,
russian,
spanish,
swedish,
turkish,
korean
}
/**
* The color theme of the different UI elements
* @readonly
* @enum {number}
*/
export enum colorTheme {
light,
dark
}
/**
* Rectangle edges
* @readonly
* @enum {number}
*/
export enum floatingButtonEdge {
left,
right
}
/**
* Instabug floating buttons positions.
* @readonly
* @enum {number}
*/
export enum IBGPosition {
bottomRight,
topRight,
bottomLeft,
topLeft
}
/**
* The welcome message mode.
* @readonly
* @enum {number}
*/
export enum welcomeMessageMode {
live,
beta,
disabled
}
/**
* Instabug action types.
* @readonly
* @enum {number}
*/
export enum actionTypes {
allActions,
reportBug,
requestNewFeature,
addCommentToFeature
}
/**
* Instabug strings
* @readonly
* @enum {number}
*/
export enum strings {
shakeHint,
swipeHint,
edgeSwipeStartHint,
startAlertText,
invalidEmailMessage,
invalidEmailTitle,
invalidCommentMessage,
invalidCommentTitle,
invocationHeader,
reportQuestion,
reportBug,
reportFeedback,
emailFieldHint,
commentFieldHintForBugReport,
commentFieldHintForFeedback,
commentFieldHintForQuestion,
videoPressRecord,
addVideoMessage,
addVoiceMessage,
addImageFromGallery,
addExtraScreenshot,
audioRecordingPermissionDeniedTitle,
audioRecordingPermissionDeniedMessage,
microphonePermissionAlertSettingsButtonText,
recordingMessageToHoldText,
recordingMessageToReleaseText,
conversationsHeaderTitle,
screenshotHeaderTitle,
doneButtonText,
okButtonText,
cancelButtonText,
thankYouText,
audio,
video,
image,
team,
messagesNotification,
messagesNotificationAndOthers,
conversationTextFieldHint,
collectingDataText,
thankYouAlertText,
welcomeMessageBetaWelcomeStepTitle,
welcomeMessageBetaWelcomeStepContent,
welcomeMessageBetaHowToReportStepTitle,
welcomeMessageBetaHowToReportStepContent,
welcomeMessageBetaFinishStepTitle,
welcomeMessageBetaFinishStepContent,
welcomeMessageLiveWelcomeStepTitle,
welcomeMessageLiveWelcomeStepContent,
surveysStoreRatingThanksTitle,
surveysStoreRatingThanksSubtitle,
reportBugDescription,
reportFeedbackDescription,
reportQuestionDescription,
requestFeatureDescription,
discardAlertTitle,
discardAlertMessage,
discardAlertCancel,
discardAlertAction,
addAttachmentButtonTitleStringName,
reportReproStepsDisclaimerBody,
reportReproStepsDisclaimerLink,
reproStepsProgressDialogBody,
reproStepsListHeader,
reproStepsListDescription,
reproStepsListEmptyStateDescription,
reproStepsListItemTitle
}
interface Report {
/**
* Attach debug log to the report to be sent.
* @param {string} log
*/
logDebug(log: string): void;
/**
* Attach verbose log to the report to be sent.
* @param {string} log
*/
logVerbose(log: string): void;
/**
* Attach warn log to the report to be sent.
* @param {string} log
*/
logWarn(log: string): void;
/**
* Attach error log to the report to be sent.
* @param {string} log
*/
logError(log: string): void;
/**
* Attach info log to the report to be sent.
* @param {string} log
*/
logInfo(log: string): void;
/**
* Append a tag to the report to be sent.
* @param {string} tag
*/
appendTag(tag: string): void;
/**
* Append a console log to the report to be sent.
* @param {string} consoleLog
*/
appendConsoleLog(consoleLog: string): void;
/**
* Add a user attribute with key and value to the report to be sent.
* @param {string} key
* @param {string} value
*/
setUserAttribute(key: string, value: string): void;
/**
* Attach a file to the report to be sent.
* @param {string} url
* @param {string} fileName
*/
addFileAttachmentWithUrl(url: string, filename: string): void;
/**
* Attach a file to the report to be sent.
* @param {string} data
* @param {string} fileName
*/
addFileAttachmentWithData(data: string, filename: string): void;
}
interface Survey {
title: string;
} | the_stack |
declare function GetIntrinsic<K extends keyof GetIntrinsic.Intrinsics>(
name: K,
allowMissing?: false,
): GetIntrinsic.Intrinsics[K];
declare function GetIntrinsic<K extends keyof GetIntrinsic.Intrinsics>(
name: K,
allowMissing: true,
): GetIntrinsic.Intrinsics[K] | undefined;
declare function GetIntrinsic<K extends keyof GetIntrinsic.Intrinsics>(
name: K,
allowMissing?: boolean,
): GetIntrinsic.Intrinsics[K] | undefined;
declare function GetIntrinsic(name: string, allowMissing?: boolean): unknown;
export = GetIntrinsic;
type numeric = number | bigint;
interface TypedArray<T extends numeric = numeric> extends Readonly<ArrayBufferView> {
/** The length of the array. */
readonly length: number;
[index: number]: T;
}
interface TypedArrayConstructor {
readonly prototype: TypedArrayPrototype;
new (...args: unknown[]): TypedArrayPrototype;
/**
* Returns a new typed array from a set of elements.
* @param items A set of elements to include in the new typed array object.
*/
of(this: new (length: number) => Int8Array, ...items: number[]): Int8Array;
of(this: new (length: number) => Uint8Array, ...items: number[]): Uint8Array;
of(this: new (length: number) => Uint8ClampedArray, ...items: number[]): Uint8ClampedArray;
of(this: new (length: number) => Int16Array, ...items: number[]): Int16Array;
of(this: new (length: number) => Uint16Array, ...items: number[]): Uint16Array;
of(this: new (length: number) => Int32Array, ...items: number[]): Int32Array;
of(this: new (length: number) => Uint32Array, ...items: number[]): Uint32Array;
// For whatever reason, `array-type` considers `bigint` a non-simple type:
// tslint:disable: array-type
of(this: new (length: number) => BigInt64Array, ...items: bigint[]): BigInt64Array;
of(this: new (length: number) => BigUint64Array, ...items: bigint[]): BigUint64Array;
// tslint:enable: array-type
of(this: new (length: number) => Float32Array, ...items: number[]): Float32Array;
of(this: new (length: number) => Float64Array, ...items: number[]): Float64Array;
/**
* Creates a new typed array from an array-like or iterable object.
* @param source An array-like or iterable object to convert to a typed array.
* @param mapfn A mapping function to call on every element of the source object.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(this: new (length: number) => Int8Array, source: Iterable<number> | ArrayLike<number>): Int8Array;
from<U>(
this: new (length: number) => Int8Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int8Array;
from(this: new (length: number) => Uint8Array, source: Iterable<number> | ArrayLike<number>): Uint8Array;
from<U>(
this: new (length: number) => Uint8Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint8Array;
from(
this: new (length: number) => Uint8ClampedArray,
source: Iterable<number> | ArrayLike<number>,
): Uint8ClampedArray;
from<U>(
this: new (length: number) => Uint8ClampedArray,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint8ClampedArray;
from(this: new (length: number) => Int16Array, source: Iterable<number> | ArrayLike<number>): Int16Array;
from<U>(
this: new (length: number) => Int16Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int16Array;
from(this: new (length: number) => Uint16Array, source: Iterable<number> | ArrayLike<number>): Uint16Array;
from<U>(
this: new (length: number) => Uint16Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint16Array;
from(this: new (length: number) => Int32Array, source: Iterable<number> | ArrayLike<number>): Int32Array;
from<U>(
this: new (length: number) => Int32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Int32Array;
from(this: new (length: number) => Uint32Array, source: Iterable<number> | ArrayLike<number>): Uint32Array;
from<U>(
this: new (length: number) => Uint32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Uint32Array;
from(this: new (length: number) => BigInt64Array, source: Iterable<bigint> | ArrayLike<bigint>): BigInt64Array;
from<U>(
this: new (length: number) => BigInt64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => bigint,
thisArg?: unknown,
): BigInt64Array;
from(this: new (length: number) => BigUint64Array, source: Iterable<bigint> | ArrayLike<bigint>): BigUint64Array;
from<U>(
this: new (length: number) => BigUint64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => bigint,
thisArg?: unknown,
): BigUint64Array;
from(this: new (length: number) => Float32Array, source: Iterable<number> | ArrayLike<number>): Float32Array;
from<U>(
this: new (length: number) => Float32Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Float32Array;
from(this: new (length: number) => Float64Array, source: Iterable<number> | ArrayLike<number>): Float64Array;
from<U>(
this: new (length: number) => Float64Array,
source: Iterable<U> | ArrayLike<U>,
mapfn: (v: U, k: number) => number,
thisArg?: unknown,
): Float64Array;
}
interface TypedArrayPrototype {
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: ArrayBufferLike;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin<THIS extends TypedArray>(this: THIS, target: number, start: number, end?: number): THIS;
/** Yields index, value pairs for every entry in the array. */
entries<T extends numeric>(this: TypedArray<T>): IterableIterator<[number, T]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param callbackfn A function that accepts up to three arguments. The every method calls
* the callbackfn function for each element in the array until the callbackfn returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
every<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): boolean;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill<T extends numeric, THIS extends TypedArray<T>>(this: THIS, value: T, start?: number, end?: number): THIS;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param callbackfn A function that accepts up to three arguments. The filter method calls
* the callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): THIS;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
callbackfn: (value: T, index: number, array: THIS) => void,
thisArg?: unknown,
): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes<T extends numeric>(this: TypedArray<T>, searchElement: T, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf<T extends numeric>(this: TypedArray<T>, searchElement: T, fromIndex?: number): boolean;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(this: TypedArray, separator?: string): string;
/** Yields each index in the array. */
keys(this: TypedArray): IterableIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf<T extends numeric>(this: TypedArray<T>, searchElement: T, fromIndex?: number): boolean;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map<T extends numeric, THIS extends TypedArray>(
this: THIS,
mapper: (value: T, index: number, array: THIS) => T,
thisArg?: unknown,
): THIS;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
reducer: (previousValue: T, currentValue: T, currentIndex: number, array: THIS) => T,
): T;
reduce<T extends numeric, U, THIS extends TypedArray<T>>(
this: THIS,
reducer: (previousValue: U, currentValue: T, currentIndex: number, array: THIS) => U,
initialValue: U,
): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
reducer: (previousValue: T, currentValue: T, currentIndex: number, array: THIS) => T,
): T;
reduceRight<T extends numeric, U, THIS extends TypedArray<T>>(
this: THIS,
reducer: (previousValue: U, currentValue: T, currentIndex: number, array: THIS) => U,
initialValue: U,
): U;
/** Reverses the elements in the array. */
reverse<THIS extends TypedArray>(this: THIS): THIS;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set<T extends numeric>(this: TypedArray<T>, array: ArrayLike<T>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice<THIS extends TypedArray>(this: THIS, start?: number, end?: number): THIS;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param callbackfn A function that accepts up to three arguments. The some method calls the
* callbackfn function for each element in the array until the callbackfn returns true, or until
* the end of the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
some<T extends numeric, THIS extends TypedArray<T>>(
this: THIS,
predicate: (value: T, index: number, array: THIS) => unknown,
thisArg?: unknown,
): boolean;
/**
* Sorts the array.
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
*/
sort<T extends numeric, THIS extends TypedArray<T>>(this: THIS, comparator?: (a: T, b: T) => number): THIS;
/**
* Gets a new subview of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray<THIS extends TypedArray>(this: THIS, begin?: number, end?: number): THIS;
/** Converts the array to a string by using the current locale. */
toLocaleString(this: TypedArray, locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/** Returns a string representation of the array. */
toString(): string;
/** Yields each value in the array. */
values<T extends numeric>(this: TypedArray<T>): IterableIterator<T>;
/** Yields each value in the array. */
[Symbol.iterator]<T extends numeric>(this: TypedArray<T>): IterableIterator<T>;
readonly [Symbol.toStringTag]: string | undefined;
}
// ------------------------ >8 ------------------------
// autogenerated by scripts/collect-intrinsics.ts
// do not edit! 2020-07-08T00:53:03.057Z
// tslint:disable: ban-types
// prettier-ignore
declare namespace GetIntrinsic {
interface Intrinsics {
'%Array%': ArrayConstructor;
'%ArrayBuffer%': ArrayBufferConstructor;
'%ArrayBufferPrototype%': ArrayBuffer;
'%ArrayIteratorPrototype%': IterableIterator<any>;
'%ArrayPrototype%': typeof Array.prototype;
'%ArrayProto_entries%': typeof Array.prototype.entries;
'%ArrayProto_forEach%': typeof Array.prototype.forEach;
'%ArrayProto_keys%': typeof Array.prototype.keys;
'%ArrayProto_values%': typeof Array.prototype.values;
'%AsyncFromSyncIteratorPrototype%': AsyncGenerator<any>;
'%AsyncFunction%': FunctionConstructor;
'%AsyncFunctionPrototype%': typeof Function.prototype;
'%AsyncGenerator%': AsyncGeneratorFunction;
'%AsyncGeneratorFunction%': AsyncGeneratorFunctionConstructor;
'%AsyncGeneratorPrototype%': AsyncGenerator<any>;
'%AsyncIteratorPrototype%': AsyncIterable<any>;
'%Atomics%': Atomics;
'%Boolean%': BooleanConstructor;
'%BooleanPrototype%': typeof Boolean.prototype;
'%DataView%': DataViewConstructor;
'%DataViewPrototype%': DataView;
'%Date%': DateConstructor;
'%DatePrototype%': Date;
'%decodeURI%': typeof decodeURI;
'%decodeURIComponent%': typeof decodeURIComponent;
'%encodeURI%': typeof encodeURI;
'%encodeURIComponent%': typeof encodeURIComponent;
'%Error%': ErrorConstructor;
'%ErrorPrototype%': Error;
'%eval%': typeof eval;
'%EvalError%': EvalErrorConstructor;
'%EvalErrorPrototype%': EvalError;
'%Float32Array%': Float32ArrayConstructor;
'%Float32ArrayPrototype%': Float32Array;
'%Float64Array%': Float64ArrayConstructor;
'%Float64ArrayPrototype%': Float64Array;
'%Function%': FunctionConstructor;
'%FunctionPrototype%': typeof Function.prototype;
'%Generator%': GeneratorFunction;
'%GeneratorFunction%': GeneratorFunctionConstructor;
'%GeneratorPrototype%': Generator<any>;
'%Int8Array%': Int8ArrayConstructor;
'%Int8ArrayPrototype%': Int8Array;
'%Int16Array%': Int16ArrayConstructor;
'%Int16ArrayPrototype%': Int16Array;
'%Int32Array%': Int32ArrayConstructor;
'%Int32ArrayPrototype%': Int32Array;
'%isFinite%': typeof isFinite;
'%isNaN%': typeof isNaN;
'%IteratorPrototype%': Iterable<any>;
'%JSON%': JSON;
'%JSONParse%': typeof JSON.parse;
'%Map%': MapConstructor;
'%MapIteratorPrototype%': IterableIterator<any>;
'%MapPrototype%': typeof Map.prototype;
'%Math%': Math;
'%Number%': NumberConstructor;
'%NumberPrototype%': typeof Number.prototype;
'%Object%': ObjectConstructor;
'%ObjectPrototype%': typeof Object.prototype;
'%ObjProto_toString%': typeof Object.prototype.toString;
'%ObjProto_valueOf%': typeof Object.prototype.valueOf;
'%parseFloat%': typeof parseFloat;
'%parseInt%': typeof parseInt;
'%Promise%': PromiseConstructor;
'%PromisePrototype%': typeof Promise.prototype;
'%PromiseProto_then%': typeof Promise.prototype.then;
'%Promise_all%': typeof Promise.all;
'%Promise_reject%': typeof Promise.reject;
'%Promise_resolve%': typeof Promise.resolve;
'%Proxy%': ProxyConstructor;
'%RangeError%': RangeErrorConstructor;
'%RangeErrorPrototype%': RangeError;
'%ReferenceError%': ReferenceErrorConstructor;
'%ReferenceErrorPrototype%': ReferenceError;
'%Reflect%': typeof Reflect;
'%RegExp%': RegExpConstructor;
'%RegExpPrototype%': RegExp;
'%Set%': SetConstructor;
'%SetIteratorPrototype%': IterableIterator<any>;
'%SetPrototype%': typeof Set.prototype;
'%SharedArrayBuffer%': SharedArrayBufferConstructor;
'%SharedArrayBufferPrototype%': SharedArrayBuffer;
'%String%': StringConstructor;
'%StringIteratorPrototype%': IterableIterator<string>;
'%StringPrototype%': typeof String.prototype;
'%Symbol%': SymbolConstructor;
'%SymbolPrototype%': typeof Symbol.prototype;
'%SyntaxError%': SyntaxErrorConstructor;
'%SyntaxErrorPrototype%': SyntaxError;
'%ThrowTypeError%': () => never;
'%TypedArray%': TypedArrayConstructor;
'%TypedArrayPrototype%': TypedArrayPrototype;
'%TypeError%': TypeErrorConstructor;
'%TypeErrorPrototype%': TypeError;
'%Uint8Array%': Uint8ArrayConstructor;
'%Uint8ArrayPrototype%': Uint8Array;
'%Uint8ClampedArray%': Uint8ClampedArrayConstructor;
'%Uint8ClampedArrayPrototype%': Uint8ClampedArray;
'%Uint16Array%': Uint16ArrayConstructor;
'%Uint16ArrayPrototype%': Uint16Array;
'%Uint32Array%': Uint32ArrayConstructor;
'%Uint32ArrayPrototype%': Uint32Array;
'%URIError%': URIErrorConstructor;
'%URIErrorPrototype%': URIError;
'%WeakMap%': WeakMapConstructor;
'%WeakMapPrototype%': typeof WeakMap.prototype;
'%WeakSet%': WeakSetConstructor;
'%WeakSetPrototype%': typeof WeakSet.prototype;
}
interface Intrinsics {
'%Array.prototype%': typeof Array.prototype;
'%Array.prototype.length%': typeof Array.prototype.length;
'%Array.prototype.concat%': typeof Array.prototype.concat;
'%Array.prototype.copyWithin%': typeof Array.prototype.copyWithin;
'%Array.prototype.fill%': typeof Array.prototype.fill;
'%Array.prototype.find%': typeof Array.prototype.find;
'%Array.prototype.findIndex%': typeof Array.prototype.findIndex;
'%Array.prototype.lastIndexOf%': typeof Array.prototype.lastIndexOf;
'%Array.prototype.pop%': typeof Array.prototype.pop;
'%Array.prototype.push%': typeof Array.prototype.push;
'%Array.prototype.reverse%': typeof Array.prototype.reverse;
'%Array.prototype.shift%': typeof Array.prototype.shift;
'%Array.prototype.unshift%': typeof Array.prototype.unshift;
'%Array.prototype.slice%': typeof Array.prototype.slice;
'%Array.prototype.sort%': typeof Array.prototype.sort;
'%Array.prototype.splice%': typeof Array.prototype.splice;
'%Array.prototype.includes%': typeof Array.prototype.includes;
'%Array.prototype.indexOf%': typeof Array.prototype.indexOf;
'%Array.prototype.join%': typeof Array.prototype.join;
'%Array.prototype.keys%': typeof Array.prototype.keys;
'%Array.prototype.entries%': typeof Array.prototype.entries;
'%Array.prototype.values%': typeof Array.prototype.values;
'%Array.prototype.forEach%': typeof Array.prototype.forEach;
'%Array.prototype.filter%': typeof Array.prototype.filter;
'%Array.prototype.flat%': typeof Array.prototype.flat;
'%Array.prototype.flatMap%': typeof Array.prototype.flatMap;
'%Array.prototype.map%': typeof Array.prototype.map;
'%Array.prototype.every%': typeof Array.prototype.every;
'%Array.prototype.some%': typeof Array.prototype.some;
'%Array.prototype.reduce%': typeof Array.prototype.reduce;
'%Array.prototype.reduceRight%': typeof Array.prototype.reduceRight;
'%Array.prototype.toLocaleString%': typeof Array.prototype.toLocaleString;
'%Array.prototype.toString%': typeof Array.prototype.toString;
'%Array.isArray%': typeof Array.isArray;
'%Array.from%': typeof Array.from;
'%Array.of%': typeof Array.of;
'%ArrayBuffer.prototype%': ArrayBuffer;
'%ArrayBuffer.prototype.byteLength%': (this: ArrayBuffer) => typeof ArrayBuffer.prototype.byteLength;
'%ArrayBuffer.prototype.slice%': typeof ArrayBuffer.prototype.slice;
'%ArrayBuffer.isView%': typeof ArrayBuffer.isView;
'%ArrayBufferPrototype.byteLength%': (this: ArrayBuffer) => typeof ArrayBuffer.prototype.byteLength;
'%ArrayBufferPrototype.slice%': typeof ArrayBuffer.prototype.slice;
'%ArrayIteratorPrototype.next%': IterableIterator<any>['next'];
'%ArrayPrototype.length%': typeof Array.prototype.length;
'%ArrayPrototype.concat%': typeof Array.prototype.concat;
'%ArrayPrototype.copyWithin%': typeof Array.prototype.copyWithin;
'%ArrayPrototype.fill%': typeof Array.prototype.fill;
'%ArrayPrototype.find%': typeof Array.prototype.find;
'%ArrayPrototype.findIndex%': typeof Array.prototype.findIndex;
'%ArrayPrototype.lastIndexOf%': typeof Array.prototype.lastIndexOf;
'%ArrayPrototype.pop%': typeof Array.prototype.pop;
'%ArrayPrototype.push%': typeof Array.prototype.push;
'%ArrayPrototype.reverse%': typeof Array.prototype.reverse;
'%ArrayPrototype.shift%': typeof Array.prototype.shift;
'%ArrayPrototype.unshift%': typeof Array.prototype.unshift;
'%ArrayPrototype.slice%': typeof Array.prototype.slice;
'%ArrayPrototype.sort%': typeof Array.prototype.sort;
'%ArrayPrototype.splice%': typeof Array.prototype.splice;
'%ArrayPrototype.includes%': typeof Array.prototype.includes;
'%ArrayPrototype.indexOf%': typeof Array.prototype.indexOf;
'%ArrayPrototype.join%': typeof Array.prototype.join;
'%ArrayPrototype.keys%': typeof Array.prototype.keys;
'%ArrayPrototype.entries%': typeof Array.prototype.entries;
'%ArrayPrototype.values%': typeof Array.prototype.values;
'%ArrayPrototype.forEach%': typeof Array.prototype.forEach;
'%ArrayPrototype.filter%': typeof Array.prototype.filter;
'%ArrayPrototype.flat%': typeof Array.prototype.flat;
'%ArrayPrototype.flatMap%': typeof Array.prototype.flatMap;
'%ArrayPrototype.map%': typeof Array.prototype.map;
'%ArrayPrototype.every%': typeof Array.prototype.every;
'%ArrayPrototype.some%': typeof Array.prototype.some;
'%ArrayPrototype.reduce%': typeof Array.prototype.reduce;
'%ArrayPrototype.reduceRight%': typeof Array.prototype.reduceRight;
'%ArrayPrototype.toLocaleString%': typeof Array.prototype.toLocaleString;
'%ArrayPrototype.toString%': typeof Array.prototype.toString;
'%AsyncFromSyncIteratorPrototype.next%': AsyncGenerator<any>['next'];
'%AsyncFromSyncIteratorPrototype.return%': AsyncGenerator<any>['return'];
'%AsyncFromSyncIteratorPrototype.throw%': AsyncGenerator<any>['throw'];
'%AsyncFunction.prototype%': typeof Function.prototype;
'%AsyncGenerator.prototype%': AsyncGenerator<any>;
'%AsyncGenerator.prototype.next%': AsyncGenerator<any>['next'];
'%AsyncGenerator.prototype.return%': AsyncGenerator<any>['return'];
'%AsyncGenerator.prototype.throw%': AsyncGenerator<any>['throw'];
'%AsyncGeneratorFunction.prototype%': AsyncGeneratorFunction;
'%AsyncGeneratorFunction.prototype.prototype%': AsyncGenerator<any>;
'%AsyncGeneratorFunction.prototype.prototype.next%': AsyncGenerator<any>['next'];
'%AsyncGeneratorFunction.prototype.prototype.return%': AsyncGenerator<any>['return'];
'%AsyncGeneratorFunction.prototype.prototype.throw%': AsyncGenerator<any>['throw'];
'%AsyncGeneratorPrototype.next%': AsyncGenerator<any>['next'];
'%AsyncGeneratorPrototype.return%': AsyncGenerator<any>['return'];
'%AsyncGeneratorPrototype.throw%': AsyncGenerator<any>['throw'];
'%Atomics.load%': typeof Atomics.load;
'%Atomics.store%': typeof Atomics.store;
'%Atomics.add%': typeof Atomics.add;
'%Atomics.sub%': typeof Atomics.sub;
'%Atomics.and%': typeof Atomics.and;
'%Atomics.or%': typeof Atomics.or;
'%Atomics.xor%': typeof Atomics.xor;
'%Atomics.exchange%': typeof Atomics.exchange;
'%Atomics.compareExchange%': typeof Atomics.compareExchange;
'%Atomics.isLockFree%': typeof Atomics.isLockFree;
'%Atomics.wait%': typeof Atomics.wait;
'%Atomics.notify%': typeof Atomics.notify;
'%Boolean.prototype%': typeof Boolean.prototype;
'%Boolean.prototype.toString%': typeof Boolean.prototype.toString;
'%Boolean.prototype.valueOf%': typeof Boolean.prototype.valueOf;
'%BooleanPrototype.toString%': typeof Boolean.prototype.toString;
'%BooleanPrototype.valueOf%': typeof Boolean.prototype.valueOf;
'%DataView.prototype%': DataView;
'%DataView.prototype.buffer%': (this: DataView) => typeof DataView.prototype.buffer;
'%DataView.prototype.byteLength%': (this: DataView) => typeof DataView.prototype.byteLength;
'%DataView.prototype.byteOffset%': (this: DataView) => typeof DataView.prototype.byteOffset;
'%DataView.prototype.getInt8%': typeof DataView.prototype.getInt8;
'%DataView.prototype.setInt8%': typeof DataView.prototype.setInt8;
'%DataView.prototype.getUint8%': typeof DataView.prototype.getUint8;
'%DataView.prototype.setUint8%': typeof DataView.prototype.setUint8;
'%DataView.prototype.getInt16%': typeof DataView.prototype.getInt16;
'%DataView.prototype.setInt16%': typeof DataView.prototype.setInt16;
'%DataView.prototype.getUint16%': typeof DataView.prototype.getUint16;
'%DataView.prototype.setUint16%': typeof DataView.prototype.setUint16;
'%DataView.prototype.getInt32%': typeof DataView.prototype.getInt32;
'%DataView.prototype.setInt32%': typeof DataView.prototype.setInt32;
'%DataView.prototype.getUint32%': typeof DataView.prototype.getUint32;
'%DataView.prototype.setUint32%': typeof DataView.prototype.setUint32;
'%DataView.prototype.getFloat32%': typeof DataView.prototype.getFloat32;
'%DataView.prototype.setFloat32%': typeof DataView.prototype.setFloat32;
'%DataView.prototype.getFloat64%': typeof DataView.prototype.getFloat64;
'%DataView.prototype.setFloat64%': typeof DataView.prototype.setFloat64;
'%DataView.prototype.getBigInt64%': typeof DataView.prototype.getBigInt64;
'%DataView.prototype.setBigInt64%': typeof DataView.prototype.setBigInt64;
'%DataView.prototype.getBigUint64%': typeof DataView.prototype.getBigUint64;
'%DataView.prototype.setBigUint64%': typeof DataView.prototype.setBigUint64;
'%DataViewPrototype.buffer%': (this: DataView) => typeof DataView.prototype.buffer;
'%DataViewPrototype.byteLength%': (this: DataView) => typeof DataView.prototype.byteLength;
'%DataViewPrototype.byteOffset%': (this: DataView) => typeof DataView.prototype.byteOffset;
'%DataViewPrototype.getInt8%': typeof DataView.prototype.getInt8;
'%DataViewPrototype.setInt8%': typeof DataView.prototype.setInt8;
'%DataViewPrototype.getUint8%': typeof DataView.prototype.getUint8;
'%DataViewPrototype.setUint8%': typeof DataView.prototype.setUint8;
'%DataViewPrototype.getInt16%': typeof DataView.prototype.getInt16;
'%DataViewPrototype.setInt16%': typeof DataView.prototype.setInt16;
'%DataViewPrototype.getUint16%': typeof DataView.prototype.getUint16;
'%DataViewPrototype.setUint16%': typeof DataView.prototype.setUint16;
'%DataViewPrototype.getInt32%': typeof DataView.prototype.getInt32;
'%DataViewPrototype.setInt32%': typeof DataView.prototype.setInt32;
'%DataViewPrototype.getUint32%': typeof DataView.prototype.getUint32;
'%DataViewPrototype.setUint32%': typeof DataView.prototype.setUint32;
'%DataViewPrototype.getFloat32%': typeof DataView.prototype.getFloat32;
'%DataViewPrototype.setFloat32%': typeof DataView.prototype.setFloat32;
'%DataViewPrototype.getFloat64%': typeof DataView.prototype.getFloat64;
'%DataViewPrototype.setFloat64%': typeof DataView.prototype.setFloat64;
'%DataViewPrototype.getBigInt64%': typeof DataView.prototype.getBigInt64;
'%DataViewPrototype.setBigInt64%': typeof DataView.prototype.setBigInt64;
'%DataViewPrototype.getBigUint64%': typeof DataView.prototype.getBigUint64;
'%DataViewPrototype.setBigUint64%': typeof DataView.prototype.setBigUint64;
'%Date.prototype%': Date;
'%Date.prototype.toString%': typeof Date.prototype.toString;
'%Date.prototype.toDateString%': typeof Date.prototype.toDateString;
'%Date.prototype.toTimeString%': typeof Date.prototype.toTimeString;
'%Date.prototype.toISOString%': typeof Date.prototype.toISOString;
'%Date.prototype.toUTCString%': typeof Date.prototype.toUTCString;
'%Date.prototype.getDate%': typeof Date.prototype.getDate;
'%Date.prototype.setDate%': typeof Date.prototype.setDate;
'%Date.prototype.getDay%': typeof Date.prototype.getDay;
'%Date.prototype.getFullYear%': typeof Date.prototype.getFullYear;
'%Date.prototype.setFullYear%': typeof Date.prototype.setFullYear;
'%Date.prototype.getHours%': typeof Date.prototype.getHours;
'%Date.prototype.setHours%': typeof Date.prototype.setHours;
'%Date.prototype.getMilliseconds%': typeof Date.prototype.getMilliseconds;
'%Date.prototype.setMilliseconds%': typeof Date.prototype.setMilliseconds;
'%Date.prototype.getMinutes%': typeof Date.prototype.getMinutes;
'%Date.prototype.setMinutes%': typeof Date.prototype.setMinutes;
'%Date.prototype.getMonth%': typeof Date.prototype.getMonth;
'%Date.prototype.setMonth%': typeof Date.prototype.setMonth;
'%Date.prototype.getSeconds%': typeof Date.prototype.getSeconds;
'%Date.prototype.setSeconds%': typeof Date.prototype.setSeconds;
'%Date.prototype.getTime%': typeof Date.prototype.getTime;
'%Date.prototype.setTime%': typeof Date.prototype.setTime;
'%Date.prototype.getTimezoneOffset%': typeof Date.prototype.getTimezoneOffset;
'%Date.prototype.getUTCDate%': typeof Date.prototype.getUTCDate;
'%Date.prototype.setUTCDate%': typeof Date.prototype.setUTCDate;
'%Date.prototype.getUTCDay%': typeof Date.prototype.getUTCDay;
'%Date.prototype.getUTCFullYear%': typeof Date.prototype.getUTCFullYear;
'%Date.prototype.setUTCFullYear%': typeof Date.prototype.setUTCFullYear;
'%Date.prototype.getUTCHours%': typeof Date.prototype.getUTCHours;
'%Date.prototype.setUTCHours%': typeof Date.prototype.setUTCHours;
'%Date.prototype.getUTCMilliseconds%': typeof Date.prototype.getUTCMilliseconds;
'%Date.prototype.setUTCMilliseconds%': typeof Date.prototype.setUTCMilliseconds;
'%Date.prototype.getUTCMinutes%': typeof Date.prototype.getUTCMinutes;
'%Date.prototype.setUTCMinutes%': typeof Date.prototype.setUTCMinutes;
'%Date.prototype.getUTCMonth%': typeof Date.prototype.getUTCMonth;
'%Date.prototype.setUTCMonth%': typeof Date.prototype.setUTCMonth;
'%Date.prototype.getUTCSeconds%': typeof Date.prototype.getUTCSeconds;
'%Date.prototype.setUTCSeconds%': typeof Date.prototype.setUTCSeconds;
'%Date.prototype.valueOf%': typeof Date.prototype.valueOf;
'%Date.prototype.toJSON%': typeof Date.prototype.toJSON;
'%Date.prototype.toLocaleString%': typeof Date.prototype.toLocaleString;
'%Date.prototype.toLocaleDateString%': typeof Date.prototype.toLocaleDateString;
'%Date.prototype.toLocaleTimeString%': typeof Date.prototype.toLocaleTimeString;
'%Date.now%': typeof Date.now;
'%Date.parse%': typeof Date.parse;
'%Date.UTC%': typeof Date.UTC;
'%DatePrototype.toString%': typeof Date.prototype.toString;
'%DatePrototype.toDateString%': typeof Date.prototype.toDateString;
'%DatePrototype.toTimeString%': typeof Date.prototype.toTimeString;
'%DatePrototype.toISOString%': typeof Date.prototype.toISOString;
'%DatePrototype.toUTCString%': typeof Date.prototype.toUTCString;
'%DatePrototype.getDate%': typeof Date.prototype.getDate;
'%DatePrototype.setDate%': typeof Date.prototype.setDate;
'%DatePrototype.getDay%': typeof Date.prototype.getDay;
'%DatePrototype.getFullYear%': typeof Date.prototype.getFullYear;
'%DatePrototype.setFullYear%': typeof Date.prototype.setFullYear;
'%DatePrototype.getHours%': typeof Date.prototype.getHours;
'%DatePrototype.setHours%': typeof Date.prototype.setHours;
'%DatePrototype.getMilliseconds%': typeof Date.prototype.getMilliseconds;
'%DatePrototype.setMilliseconds%': typeof Date.prototype.setMilliseconds;
'%DatePrototype.getMinutes%': typeof Date.prototype.getMinutes;
'%DatePrototype.setMinutes%': typeof Date.prototype.setMinutes;
'%DatePrototype.getMonth%': typeof Date.prototype.getMonth;
'%DatePrototype.setMonth%': typeof Date.prototype.setMonth;
'%DatePrototype.getSeconds%': typeof Date.prototype.getSeconds;
'%DatePrototype.setSeconds%': typeof Date.prototype.setSeconds;
'%DatePrototype.getTime%': typeof Date.prototype.getTime;
'%DatePrototype.setTime%': typeof Date.prototype.setTime;
'%DatePrototype.getTimezoneOffset%': typeof Date.prototype.getTimezoneOffset;
'%DatePrototype.getUTCDate%': typeof Date.prototype.getUTCDate;
'%DatePrototype.setUTCDate%': typeof Date.prototype.setUTCDate;
'%DatePrototype.getUTCDay%': typeof Date.prototype.getUTCDay;
'%DatePrototype.getUTCFullYear%': typeof Date.prototype.getUTCFullYear;
'%DatePrototype.setUTCFullYear%': typeof Date.prototype.setUTCFullYear;
'%DatePrototype.getUTCHours%': typeof Date.prototype.getUTCHours;
'%DatePrototype.setUTCHours%': typeof Date.prototype.setUTCHours;
'%DatePrototype.getUTCMilliseconds%': typeof Date.prototype.getUTCMilliseconds;
'%DatePrototype.setUTCMilliseconds%': typeof Date.prototype.setUTCMilliseconds;
'%DatePrototype.getUTCMinutes%': typeof Date.prototype.getUTCMinutes;
'%DatePrototype.setUTCMinutes%': typeof Date.prototype.setUTCMinutes;
'%DatePrototype.getUTCMonth%': typeof Date.prototype.getUTCMonth;
'%DatePrototype.setUTCMonth%': typeof Date.prototype.setUTCMonth;
'%DatePrototype.getUTCSeconds%': typeof Date.prototype.getUTCSeconds;
'%DatePrototype.setUTCSeconds%': typeof Date.prototype.setUTCSeconds;
'%DatePrototype.valueOf%': typeof Date.prototype.valueOf;
'%DatePrototype.toJSON%': typeof Date.prototype.toJSON;
'%DatePrototype.toLocaleString%': typeof Date.prototype.toLocaleString;
'%DatePrototype.toLocaleDateString%': typeof Date.prototype.toLocaleDateString;
'%DatePrototype.toLocaleTimeString%': typeof Date.prototype.toLocaleTimeString;
'%Error.prototype%': Error;
'%Error.prototype.name%': typeof Error.prototype.name;
'%Error.prototype.message%': typeof Error.prototype.message;
'%Error.prototype.toString%': typeof Error.prototype.toString;
'%ErrorPrototype.name%': typeof Error.prototype.name;
'%ErrorPrototype.message%': typeof Error.prototype.message;
'%ErrorPrototype.toString%': typeof Error.prototype.toString;
'%EvalError.prototype%': EvalError;
'%EvalError.prototype.name%': typeof EvalError.prototype.name;
'%EvalError.prototype.message%': typeof EvalError.prototype.message;
'%EvalErrorPrototype.name%': typeof EvalError.prototype.name;
'%EvalErrorPrototype.message%': typeof EvalError.prototype.message;
'%Float32Array.prototype%': Float32Array;
'%Float32Array.prototype.BYTES_PER_ELEMENT%': typeof Float32Array.prototype.BYTES_PER_ELEMENT;
'%Float32Array.BYTES_PER_ELEMENT%': typeof Float32Array.BYTES_PER_ELEMENT;
'%Float32ArrayPrototype.BYTES_PER_ELEMENT%': typeof Float32Array.prototype.BYTES_PER_ELEMENT;
'%Float64Array.prototype%': Float64Array;
'%Float64Array.prototype.BYTES_PER_ELEMENT%': typeof Float64Array.prototype.BYTES_PER_ELEMENT;
'%Float64Array.BYTES_PER_ELEMENT%': typeof Float64Array.BYTES_PER_ELEMENT;
'%Float64ArrayPrototype.BYTES_PER_ELEMENT%': typeof Float64Array.prototype.BYTES_PER_ELEMENT;
'%Function.prototype%': typeof Function.prototype;
'%Function.prototype.apply%': typeof Function.prototype.apply;
'%Function.prototype.bind%': typeof Function.prototype.bind;
'%Function.prototype.call%': typeof Function.prototype.call;
'%Function.prototype.toString%': typeof Function.prototype.toString;
'%FunctionPrototype.apply%': typeof Function.prototype.apply;
'%FunctionPrototype.bind%': typeof Function.prototype.bind;
'%FunctionPrototype.call%': typeof Function.prototype.call;
'%FunctionPrototype.toString%': typeof Function.prototype.toString;
'%Generator.prototype%': Generator<any>;
'%Generator.prototype.next%': Generator<any>['next'];
'%Generator.prototype.return%': Generator<any>['return'];
'%Generator.prototype.throw%': Generator<any>['throw'];
'%GeneratorFunction.prototype%': GeneratorFunction;
'%GeneratorFunction.prototype.prototype%': Generator<any>;
'%GeneratorFunction.prototype.prototype.next%': Generator<any>['next'];
'%GeneratorFunction.prototype.prototype.return%': Generator<any>['return'];
'%GeneratorFunction.prototype.prototype.throw%': Generator<any>['throw'];
'%GeneratorPrototype.next%': Generator<any>['next'];
'%GeneratorPrototype.return%': Generator<any>['return'];
'%GeneratorPrototype.throw%': Generator<any>['throw'];
'%Int8Array.prototype%': Int8Array;
'%Int8Array.prototype.BYTES_PER_ELEMENT%': typeof Int8Array.prototype.BYTES_PER_ELEMENT;
'%Int8Array.BYTES_PER_ELEMENT%': typeof Int8Array.BYTES_PER_ELEMENT;
'%Int8ArrayPrototype.BYTES_PER_ELEMENT%': typeof Int8Array.prototype.BYTES_PER_ELEMENT;
'%Int16Array.prototype%': Int16Array;
'%Int16Array.prototype.BYTES_PER_ELEMENT%': typeof Int16Array.prototype.BYTES_PER_ELEMENT;
'%Int16Array.BYTES_PER_ELEMENT%': typeof Int16Array.BYTES_PER_ELEMENT;
'%Int16ArrayPrototype.BYTES_PER_ELEMENT%': typeof Int16Array.prototype.BYTES_PER_ELEMENT;
'%Int32Array.prototype%': Int32Array;
'%Int32Array.prototype.BYTES_PER_ELEMENT%': typeof Int32Array.prototype.BYTES_PER_ELEMENT;
'%Int32Array.BYTES_PER_ELEMENT%': typeof Int32Array.BYTES_PER_ELEMENT;
'%Int32ArrayPrototype.BYTES_PER_ELEMENT%': typeof Int32Array.prototype.BYTES_PER_ELEMENT;
'%JSON.parse%': typeof JSON.parse;
'%JSON.stringify%': typeof JSON.stringify;
'%Map.prototype%': typeof Map.prototype;
'%Map.prototype.get%': typeof Map.prototype.get;
'%Map.prototype.set%': typeof Map.prototype.set;
'%Map.prototype.has%': typeof Map.prototype.has;
'%Map.prototype.delete%': typeof Map.prototype.delete;
'%Map.prototype.clear%': typeof Map.prototype.clear;
'%Map.prototype.entries%': typeof Map.prototype.entries;
'%Map.prototype.forEach%': typeof Map.prototype.forEach;
'%Map.prototype.keys%': typeof Map.prototype.keys;
'%Map.prototype.size%': (this: Map<any, any>) => typeof Map.prototype.size;
'%Map.prototype.values%': typeof Map.prototype.values;
'%MapIteratorPrototype.next%': IterableIterator<any>['next'];
'%MapPrototype.get%': typeof Map.prototype.get;
'%MapPrototype.set%': typeof Map.prototype.set;
'%MapPrototype.has%': typeof Map.prototype.has;
'%MapPrototype.delete%': typeof Map.prototype.delete;
'%MapPrototype.clear%': typeof Map.prototype.clear;
'%MapPrototype.entries%': typeof Map.prototype.entries;
'%MapPrototype.forEach%': typeof Map.prototype.forEach;
'%MapPrototype.keys%': typeof Map.prototype.keys;
'%MapPrototype.size%': (this: Map<any, any>) => typeof Map.prototype.size;
'%MapPrototype.values%': typeof Map.prototype.values;
'%Math.abs%': typeof Math.abs;
'%Math.acos%': typeof Math.acos;
'%Math.acosh%': typeof Math.acosh;
'%Math.asin%': typeof Math.asin;
'%Math.asinh%': typeof Math.asinh;
'%Math.atan%': typeof Math.atan;
'%Math.atanh%': typeof Math.atanh;
'%Math.atan2%': typeof Math.atan2;
'%Math.ceil%': typeof Math.ceil;
'%Math.cbrt%': typeof Math.cbrt;
'%Math.expm1%': typeof Math.expm1;
'%Math.clz32%': typeof Math.clz32;
'%Math.cos%': typeof Math.cos;
'%Math.cosh%': typeof Math.cosh;
'%Math.exp%': typeof Math.exp;
'%Math.floor%': typeof Math.floor;
'%Math.fround%': typeof Math.fround;
'%Math.hypot%': typeof Math.hypot;
'%Math.imul%': typeof Math.imul;
'%Math.log%': typeof Math.log;
'%Math.log1p%': typeof Math.log1p;
'%Math.log2%': typeof Math.log2;
'%Math.log10%': typeof Math.log10;
'%Math.max%': typeof Math.max;
'%Math.min%': typeof Math.min;
'%Math.pow%': typeof Math.pow;
'%Math.random%': typeof Math.random;
'%Math.round%': typeof Math.round;
'%Math.sign%': typeof Math.sign;
'%Math.sin%': typeof Math.sin;
'%Math.sinh%': typeof Math.sinh;
'%Math.sqrt%': typeof Math.sqrt;
'%Math.tan%': typeof Math.tan;
'%Math.tanh%': typeof Math.tanh;
'%Math.trunc%': typeof Math.trunc;
'%Math.E%': typeof Math.E;
'%Math.LN10%': typeof Math.LN10;
'%Math.LN2%': typeof Math.LN2;
'%Math.LOG10E%': typeof Math.LOG10E;
'%Math.LOG2E%': typeof Math.LOG2E;
'%Math.PI%': typeof Math.PI;
'%Math.SQRT1_2%': typeof Math.SQRT1_2;
'%Math.SQRT2%': typeof Math.SQRT2;
'%Number.prototype%': typeof Number.prototype;
'%Number.prototype.toExponential%': typeof Number.prototype.toExponential;
'%Number.prototype.toFixed%': typeof Number.prototype.toFixed;
'%Number.prototype.toPrecision%': typeof Number.prototype.toPrecision;
'%Number.prototype.toString%': typeof Number.prototype.toString;
'%Number.prototype.valueOf%': typeof Number.prototype.valueOf;
'%Number.prototype.toLocaleString%': typeof Number.prototype.toLocaleString;
'%Number.isFinite%': typeof Number.isFinite;
'%Number.isInteger%': typeof Number.isInteger;
'%Number.isNaN%': typeof Number.isNaN;
'%Number.isSafeInteger%': typeof Number.isSafeInteger;
'%Number.parseFloat%': typeof Number.parseFloat;
'%Number.parseInt%': typeof Number.parseInt;
'%Number.MAX_VALUE%': typeof Number.MAX_VALUE;
'%Number.MIN_VALUE%': typeof Number.MIN_VALUE;
'%Number.NaN%': typeof Number.NaN;
'%Number.NEGATIVE_INFINITY%': typeof Number.NEGATIVE_INFINITY;
'%Number.POSITIVE_INFINITY%': typeof Number.POSITIVE_INFINITY;
'%Number.MAX_SAFE_INTEGER%': typeof Number.MAX_SAFE_INTEGER;
'%Number.MIN_SAFE_INTEGER%': typeof Number.MIN_SAFE_INTEGER;
'%Number.EPSILON%': typeof Number.EPSILON;
'%NumberPrototype.toExponential%': typeof Number.prototype.toExponential;
'%NumberPrototype.toFixed%': typeof Number.prototype.toFixed;
'%NumberPrototype.toPrecision%': typeof Number.prototype.toPrecision;
'%NumberPrototype.toString%': typeof Number.prototype.toString;
'%NumberPrototype.valueOf%': typeof Number.prototype.valueOf;
'%NumberPrototype.toLocaleString%': typeof Number.prototype.toLocaleString;
'%Object.prototype%': typeof Object.prototype;
'%Object.prototype.hasOwnProperty%': typeof Object.prototype.hasOwnProperty;
'%Object.prototype.isPrototypeOf%': typeof Object.prototype.isPrototypeOf;
'%Object.prototype.propertyIsEnumerable%': typeof Object.prototype.propertyIsEnumerable;
'%Object.prototype.toString%': typeof Object.prototype.toString;
'%Object.prototype.valueOf%': typeof Object.prototype.valueOf;
'%Object.prototype.toLocaleString%': typeof Object.prototype.toLocaleString;
'%Object.assign%': typeof Object.assign;
'%Object.getOwnPropertyDescriptor%': typeof Object.getOwnPropertyDescriptor;
'%Object.getOwnPropertyDescriptors%': typeof Object.getOwnPropertyDescriptors;
'%Object.getOwnPropertyNames%': typeof Object.getOwnPropertyNames;
'%Object.getOwnPropertySymbols%': typeof Object.getOwnPropertySymbols;
'%Object.is%': typeof Object.is;
'%Object.preventExtensions%': typeof Object.preventExtensions;
'%Object.seal%': typeof Object.seal;
'%Object.create%': typeof Object.create;
'%Object.defineProperties%': typeof Object.defineProperties;
'%Object.defineProperty%': typeof Object.defineProperty;
'%Object.freeze%': typeof Object.freeze;
'%Object.getPrototypeOf%': typeof Object.getPrototypeOf;
'%Object.setPrototypeOf%': typeof Object.setPrototypeOf;
'%Object.isExtensible%': typeof Object.isExtensible;
'%Object.isFrozen%': typeof Object.isFrozen;
'%Object.isSealed%': typeof Object.isSealed;
'%Object.keys%': typeof Object.keys;
'%Object.entries%': typeof Object.entries;
'%Object.fromEntries%': typeof Object.fromEntries;
'%Object.values%': typeof Object.values;
'%ObjectPrototype.hasOwnProperty%': typeof Object.prototype.hasOwnProperty;
'%ObjectPrototype.isPrototypeOf%': typeof Object.prototype.isPrototypeOf;
'%ObjectPrototype.propertyIsEnumerable%': typeof Object.prototype.propertyIsEnumerable;
'%ObjectPrototype.toString%': typeof Object.prototype.toString;
'%ObjectPrototype.valueOf%': typeof Object.prototype.valueOf;
'%ObjectPrototype.toLocaleString%': typeof Object.prototype.toLocaleString;
'%Promise.prototype%': typeof Promise.prototype;
'%Promise.prototype.then%': typeof Promise.prototype.then;
'%Promise.prototype.catch%': typeof Promise.prototype.catch;
'%Promise.prototype.finally%': typeof Promise.prototype.finally;
'%Promise.all%': typeof Promise.all;
'%Promise.race%': typeof Promise.race;
'%Promise.resolve%': typeof Promise.resolve;
'%Promise.reject%': typeof Promise.reject;
'%Promise.allSettled%': typeof Promise.allSettled;
'%PromisePrototype.then%': typeof Promise.prototype.then;
'%PromisePrototype.catch%': typeof Promise.prototype.catch;
'%PromisePrototype.finally%': typeof Promise.prototype.finally;
'%Proxy.revocable%': typeof Proxy.revocable;
'%RangeError.prototype%': RangeError;
'%RangeError.prototype.name%': typeof RangeError.prototype.name;
'%RangeError.prototype.message%': typeof RangeError.prototype.message;
'%RangeErrorPrototype.name%': typeof RangeError.prototype.name;
'%RangeErrorPrototype.message%': typeof RangeError.prototype.message;
'%ReferenceError.prototype%': ReferenceError;
'%ReferenceError.prototype.name%': typeof ReferenceError.prototype.name;
'%ReferenceError.prototype.message%': typeof ReferenceError.prototype.message;
'%ReferenceErrorPrototype.name%': typeof ReferenceError.prototype.name;
'%ReferenceErrorPrototype.message%': typeof ReferenceError.prototype.message;
'%Reflect.defineProperty%': typeof Reflect.defineProperty;
'%Reflect.deleteProperty%': typeof Reflect.deleteProperty;
'%Reflect.apply%': typeof Reflect.apply;
'%Reflect.construct%': typeof Reflect.construct;
'%Reflect.get%': typeof Reflect.get;
'%Reflect.getOwnPropertyDescriptor%': typeof Reflect.getOwnPropertyDescriptor;
'%Reflect.getPrototypeOf%': typeof Reflect.getPrototypeOf;
'%Reflect.has%': typeof Reflect.has;
'%Reflect.isExtensible%': typeof Reflect.isExtensible;
'%Reflect.ownKeys%': typeof Reflect.ownKeys;
'%Reflect.preventExtensions%': typeof Reflect.preventExtensions;
'%Reflect.set%': typeof Reflect.set;
'%Reflect.setPrototypeOf%': typeof Reflect.setPrototypeOf;
'%RegExp.prototype%': RegExp;
'%RegExp.prototype.exec%': typeof RegExp.prototype.exec;
'%RegExp.prototype.dotAll%': (this: RegExp) => typeof RegExp.prototype.dotAll;
'%RegExp.prototype.flags%': (this: RegExp) => typeof RegExp.prototype.flags;
'%RegExp.prototype.global%': (this: RegExp) => typeof RegExp.prototype.global;
'%RegExp.prototype.ignoreCase%': (this: RegExp) => typeof RegExp.prototype.ignoreCase;
'%RegExp.prototype.multiline%': (this: RegExp) => typeof RegExp.prototype.multiline;
'%RegExp.prototype.source%': (this: RegExp) => typeof RegExp.prototype.source;
'%RegExp.prototype.sticky%': (this: RegExp) => typeof RegExp.prototype.sticky;
'%RegExp.prototype.unicode%': (this: RegExp) => typeof RegExp.prototype.unicode;
'%RegExp.prototype.compile%': typeof RegExp.prototype.compile;
'%RegExp.prototype.toString%': typeof RegExp.prototype.toString;
'%RegExp.prototype.test%': typeof RegExp.prototype.test;
'%RegExpPrototype.exec%': typeof RegExp.prototype.exec;
'%RegExpPrototype.dotAll%': (this: RegExp) => typeof RegExp.prototype.dotAll;
'%RegExpPrototype.flags%': (this: RegExp) => typeof RegExp.prototype.flags;
'%RegExpPrototype.global%': (this: RegExp) => typeof RegExp.prototype.global;
'%RegExpPrototype.ignoreCase%': (this: RegExp) => typeof RegExp.prototype.ignoreCase;
'%RegExpPrototype.multiline%': (this: RegExp) => typeof RegExp.prototype.multiline;
'%RegExpPrototype.source%': (this: RegExp) => typeof RegExp.prototype.source;
'%RegExpPrototype.sticky%': (this: RegExp) => typeof RegExp.prototype.sticky;
'%RegExpPrototype.unicode%': (this: RegExp) => typeof RegExp.prototype.unicode;
'%RegExpPrototype.compile%': typeof RegExp.prototype.compile;
'%RegExpPrototype.toString%': typeof RegExp.prototype.toString;
'%RegExpPrototype.test%': typeof RegExp.prototype.test;
'%Set.prototype%': typeof Set.prototype;
'%Set.prototype.has%': typeof Set.prototype.has;
'%Set.prototype.add%': typeof Set.prototype.add;
'%Set.prototype.delete%': typeof Set.prototype.delete;
'%Set.prototype.clear%': typeof Set.prototype.clear;
'%Set.prototype.entries%': typeof Set.prototype.entries;
'%Set.prototype.forEach%': typeof Set.prototype.forEach;
'%Set.prototype.size%': (this: Set<any>) => typeof Set.prototype.size;
'%Set.prototype.values%': typeof Set.prototype.values;
'%Set.prototype.keys%': typeof Set.prototype.keys;
'%SetIteratorPrototype.next%': IterableIterator<any>['next'];
'%SetPrototype.has%': typeof Set.prototype.has;
'%SetPrototype.add%': typeof Set.prototype.add;
'%SetPrototype.delete%': typeof Set.prototype.delete;
'%SetPrototype.clear%': typeof Set.prototype.clear;
'%SetPrototype.entries%': typeof Set.prototype.entries;
'%SetPrototype.forEach%': typeof Set.prototype.forEach;
'%SetPrototype.size%': (this: Set<any>) => typeof Set.prototype.size;
'%SetPrototype.values%': typeof Set.prototype.values;
'%SetPrototype.keys%': typeof Set.prototype.keys;
'%SharedArrayBuffer.prototype%': SharedArrayBuffer;
'%SharedArrayBuffer.prototype.byteLength%': (this: SharedArrayBuffer) => typeof SharedArrayBuffer.prototype.byteLength;
'%SharedArrayBuffer.prototype.slice%': typeof SharedArrayBuffer.prototype.slice;
'%SharedArrayBufferPrototype.byteLength%': (this: SharedArrayBuffer) => typeof SharedArrayBuffer.prototype.byteLength;
'%SharedArrayBufferPrototype.slice%': typeof SharedArrayBuffer.prototype.slice;
'%String.prototype%': typeof String.prototype;
'%String.prototype.length%': typeof String.prototype.length;
'%String.prototype.anchor%': typeof String.prototype.anchor;
'%String.prototype.big%': typeof String.prototype.big;
'%String.prototype.blink%': typeof String.prototype.blink;
'%String.prototype.bold%': typeof String.prototype.bold;
'%String.prototype.charAt%': typeof String.prototype.charAt;
'%String.prototype.charCodeAt%': typeof String.prototype.charCodeAt;
'%String.prototype.codePointAt%': typeof String.prototype.codePointAt;
'%String.prototype.concat%': typeof String.prototype.concat;
'%String.prototype.endsWith%': typeof String.prototype.endsWith;
'%String.prototype.fontcolor%': typeof String.prototype.fontcolor;
'%String.prototype.fontsize%': typeof String.prototype.fontsize;
'%String.prototype.fixed%': typeof String.prototype.fixed;
'%String.prototype.includes%': typeof String.prototype.includes;
'%String.prototype.indexOf%': typeof String.prototype.indexOf;
'%String.prototype.italics%': typeof String.prototype.italics;
'%String.prototype.lastIndexOf%': typeof String.prototype.lastIndexOf;
'%String.prototype.link%': typeof String.prototype.link;
'%String.prototype.localeCompare%': typeof String.prototype.localeCompare;
'%String.prototype.match%': typeof String.prototype.match;
'%String.prototype.matchAll%': typeof String.prototype.matchAll;
'%String.prototype.normalize%': typeof String.prototype.normalize;
'%String.prototype.padEnd%': typeof String.prototype.padEnd;
'%String.prototype.padStart%': typeof String.prototype.padStart;
'%String.prototype.repeat%': typeof String.prototype.repeat;
'%String.prototype.replace%': typeof String.prototype.replace;
'%String.prototype.search%': typeof String.prototype.search;
'%String.prototype.slice%': typeof String.prototype.slice;
'%String.prototype.small%': typeof String.prototype.small;
'%String.prototype.split%': typeof String.prototype.split;
'%String.prototype.strike%': typeof String.prototype.strike;
'%String.prototype.sub%': typeof String.prototype.sub;
'%String.prototype.substr%': typeof String.prototype.substr;
'%String.prototype.substring%': typeof String.prototype.substring;
'%String.prototype.sup%': typeof String.prototype.sup;
'%String.prototype.startsWith%': typeof String.prototype.startsWith;
'%String.prototype.toString%': typeof String.prototype.toString;
'%String.prototype.trim%': typeof String.prototype.trim;
'%String.prototype.trimStart%': typeof String.prototype.trimStart;
'%String.prototype.trimLeft%': typeof String.prototype.trimLeft;
'%String.prototype.trimEnd%': typeof String.prototype.trimEnd;
'%String.prototype.trimRight%': typeof String.prototype.trimRight;
'%String.prototype.toLocaleLowerCase%': typeof String.prototype.toLocaleLowerCase;
'%String.prototype.toLocaleUpperCase%': typeof String.prototype.toLocaleUpperCase;
'%String.prototype.toLowerCase%': typeof String.prototype.toLowerCase;
'%String.prototype.toUpperCase%': typeof String.prototype.toUpperCase;
'%String.prototype.valueOf%': typeof String.prototype.valueOf;
'%String.fromCharCode%': typeof String.fromCharCode;
'%String.fromCodePoint%': typeof String.fromCodePoint;
'%String.raw%': typeof String.raw;
'%StringIteratorPrototype.next%': IterableIterator<string>['next'];
'%StringPrototype.length%': typeof String.prototype.length;
'%StringPrototype.anchor%': typeof String.prototype.anchor;
'%StringPrototype.big%': typeof String.prototype.big;
'%StringPrototype.blink%': typeof String.prototype.blink;
'%StringPrototype.bold%': typeof String.prototype.bold;
'%StringPrototype.charAt%': typeof String.prototype.charAt;
'%StringPrototype.charCodeAt%': typeof String.prototype.charCodeAt;
'%StringPrototype.codePointAt%': typeof String.prototype.codePointAt;
'%StringPrototype.concat%': typeof String.prototype.concat;
'%StringPrototype.endsWith%': typeof String.prototype.endsWith;
'%StringPrototype.fontcolor%': typeof String.prototype.fontcolor;
'%StringPrototype.fontsize%': typeof String.prototype.fontsize;
'%StringPrototype.fixed%': typeof String.prototype.fixed;
'%StringPrototype.includes%': typeof String.prototype.includes;
'%StringPrototype.indexOf%': typeof String.prototype.indexOf;
'%StringPrototype.italics%': typeof String.prototype.italics;
'%StringPrototype.lastIndexOf%': typeof String.prototype.lastIndexOf;
'%StringPrototype.link%': typeof String.prototype.link;
'%StringPrototype.localeCompare%': typeof String.prototype.localeCompare;
'%StringPrototype.match%': typeof String.prototype.match;
'%StringPrototype.matchAll%': typeof String.prototype.matchAll;
'%StringPrototype.normalize%': typeof String.prototype.normalize;
'%StringPrototype.padEnd%': typeof String.prototype.padEnd;
'%StringPrototype.padStart%': typeof String.prototype.padStart;
'%StringPrototype.repeat%': typeof String.prototype.repeat;
'%StringPrototype.replace%': typeof String.prototype.replace;
'%StringPrototype.search%': typeof String.prototype.search;
'%StringPrototype.slice%': typeof String.prototype.slice;
'%StringPrototype.small%': typeof String.prototype.small;
'%StringPrototype.split%': typeof String.prototype.split;
'%StringPrototype.strike%': typeof String.prototype.strike;
'%StringPrototype.sub%': typeof String.prototype.sub;
'%StringPrototype.substr%': typeof String.prototype.substr;
'%StringPrototype.substring%': typeof String.prototype.substring;
'%StringPrototype.sup%': typeof String.prototype.sup;
'%StringPrototype.startsWith%': typeof String.prototype.startsWith;
'%StringPrototype.toString%': typeof String.prototype.toString;
'%StringPrototype.trim%': typeof String.prototype.trim;
'%StringPrototype.trimStart%': typeof String.prototype.trimStart;
'%StringPrototype.trimLeft%': typeof String.prototype.trimLeft;
'%StringPrototype.trimEnd%': typeof String.prototype.trimEnd;
'%StringPrototype.trimRight%': typeof String.prototype.trimRight;
'%StringPrototype.toLocaleLowerCase%': typeof String.prototype.toLocaleLowerCase;
'%StringPrototype.toLocaleUpperCase%': typeof String.prototype.toLocaleUpperCase;
'%StringPrototype.toLowerCase%': typeof String.prototype.toLowerCase;
'%StringPrototype.toUpperCase%': typeof String.prototype.toUpperCase;
'%StringPrototype.valueOf%': typeof String.prototype.valueOf;
'%Symbol.prototype%': typeof Symbol.prototype;
'%Symbol.prototype.toString%': typeof Symbol.prototype.toString;
'%Symbol.prototype.valueOf%': typeof Symbol.prototype.valueOf;
'%Symbol.prototype.description%': (this: symbol | Symbol) => typeof Symbol.prototype.description;
'%Symbol.for%': typeof Symbol.for;
'%Symbol.keyFor%': typeof Symbol.keyFor;
'%Symbol.asyncIterator%': typeof Symbol.asyncIterator;
'%Symbol.hasInstance%': typeof Symbol.hasInstance;
'%Symbol.isConcatSpreadable%': typeof Symbol.isConcatSpreadable;
'%Symbol.iterator%': typeof Symbol.iterator;
'%Symbol.match%': typeof Symbol.match;
'%Symbol.matchAll%': typeof Symbol.matchAll;
'%Symbol.replace%': typeof Symbol.replace;
'%Symbol.search%': typeof Symbol.search;
'%Symbol.species%': typeof Symbol.species;
'%Symbol.split%': typeof Symbol.split;
'%Symbol.toPrimitive%': typeof Symbol.toPrimitive;
'%Symbol.toStringTag%': typeof Symbol.toStringTag;
'%Symbol.unscopables%': typeof Symbol.unscopables;
'%SymbolPrototype.toString%': typeof Symbol.prototype.toString;
'%SymbolPrototype.valueOf%': typeof Symbol.prototype.valueOf;
'%SymbolPrototype.description%': (this: symbol | Symbol) => typeof Symbol.prototype.description;
'%SyntaxError.prototype%': SyntaxError;
'%SyntaxError.prototype.name%': typeof SyntaxError.prototype.name;
'%SyntaxError.prototype.message%': typeof SyntaxError.prototype.message;
'%SyntaxErrorPrototype.name%': typeof SyntaxError.prototype.name;
'%SyntaxErrorPrototype.message%': typeof SyntaxError.prototype.message;
'%TypedArray.prototype%': TypedArrayPrototype;
'%TypedArray.prototype.buffer%': (this: TypedArray) => TypedArrayPrototype['buffer'];
'%TypedArray.prototype.byteLength%': (this: TypedArray) => TypedArrayPrototype['byteLength'];
'%TypedArray.prototype.byteOffset%': (this: TypedArray) => TypedArrayPrototype['byteOffset'];
'%TypedArray.prototype.length%': (this: TypedArray) => TypedArrayPrototype['length'];
'%TypedArray.prototype.entries%': TypedArrayPrototype['entries'];
'%TypedArray.prototype.keys%': TypedArrayPrototype['keys'];
'%TypedArray.prototype.values%': TypedArrayPrototype['values'];
'%TypedArray.prototype.copyWithin%': TypedArrayPrototype['copyWithin'];
'%TypedArray.prototype.every%': TypedArrayPrototype['every'];
'%TypedArray.prototype.fill%': TypedArrayPrototype['fill'];
'%TypedArray.prototype.filter%': TypedArrayPrototype['filter'];
'%TypedArray.prototype.find%': TypedArrayPrototype['find'];
'%TypedArray.prototype.findIndex%': TypedArrayPrototype['findIndex'];
'%TypedArray.prototype.forEach%': TypedArrayPrototype['forEach'];
'%TypedArray.prototype.includes%': TypedArrayPrototype['includes'];
'%TypedArray.prototype.indexOf%': TypedArrayPrototype['indexOf'];
'%TypedArray.prototype.join%': TypedArrayPrototype['join'];
'%TypedArray.prototype.lastIndexOf%': TypedArrayPrototype['lastIndexOf'];
'%TypedArray.prototype.map%': TypedArrayPrototype['map'];
'%TypedArray.prototype.reverse%': TypedArrayPrototype['reverse'];
'%TypedArray.prototype.reduce%': TypedArrayPrototype['reduce'];
'%TypedArray.prototype.reduceRight%': TypedArrayPrototype['reduceRight'];
'%TypedArray.prototype.set%': TypedArrayPrototype['set'];
'%TypedArray.prototype.slice%': TypedArrayPrototype['slice'];
'%TypedArray.prototype.some%': TypedArrayPrototype['some'];
'%TypedArray.prototype.sort%': TypedArrayPrototype['sort'];
'%TypedArray.prototype.subarray%': TypedArrayPrototype['subarray'];
'%TypedArray.prototype.toLocaleString%': TypedArrayPrototype['toLocaleString'];
'%TypedArray.prototype.toString%': TypedArrayPrototype['toString'];
'%TypedArray.of%': TypedArrayConstructor['of'];
'%TypedArray.from%': TypedArrayConstructor['from'];
'%TypedArrayPrototype.buffer%': (this: TypedArray) => TypedArrayPrototype['buffer'];
'%TypedArrayPrototype.byteLength%': (this: TypedArray) => TypedArrayPrototype['byteLength'];
'%TypedArrayPrototype.byteOffset%': (this: TypedArray) => TypedArrayPrototype['byteOffset'];
'%TypedArrayPrototype.length%': (this: TypedArray) => TypedArrayPrototype['length'];
'%TypedArrayPrototype.entries%': TypedArrayPrototype['entries'];
'%TypedArrayPrototype.keys%': TypedArrayPrototype['keys'];
'%TypedArrayPrototype.values%': TypedArrayPrototype['values'];
'%TypedArrayPrototype.copyWithin%': TypedArrayPrototype['copyWithin'];
'%TypedArrayPrototype.every%': TypedArrayPrototype['every'];
'%TypedArrayPrototype.fill%': TypedArrayPrototype['fill'];
'%TypedArrayPrototype.filter%': TypedArrayPrototype['filter'];
'%TypedArrayPrototype.find%': TypedArrayPrototype['find'];
'%TypedArrayPrototype.findIndex%': TypedArrayPrototype['findIndex'];
'%TypedArrayPrototype.forEach%': TypedArrayPrototype['forEach'];
'%TypedArrayPrototype.includes%': TypedArrayPrototype['includes'];
'%TypedArrayPrototype.indexOf%': TypedArrayPrototype['indexOf'];
'%TypedArrayPrototype.join%': TypedArrayPrototype['join'];
'%TypedArrayPrototype.lastIndexOf%': TypedArrayPrototype['lastIndexOf'];
'%TypedArrayPrototype.map%': TypedArrayPrototype['map'];
'%TypedArrayPrototype.reverse%': TypedArrayPrototype['reverse'];
'%TypedArrayPrototype.reduce%': TypedArrayPrototype['reduce'];
'%TypedArrayPrototype.reduceRight%': TypedArrayPrototype['reduceRight'];
'%TypedArrayPrototype.set%': TypedArrayPrototype['set'];
'%TypedArrayPrototype.slice%': TypedArrayPrototype['slice'];
'%TypedArrayPrototype.some%': TypedArrayPrototype['some'];
'%TypedArrayPrototype.sort%': TypedArrayPrototype['sort'];
'%TypedArrayPrototype.subarray%': TypedArrayPrototype['subarray'];
'%TypedArrayPrototype.toLocaleString%': TypedArrayPrototype['toLocaleString'];
'%TypedArrayPrototype.toString%': TypedArrayPrototype['toString'];
'%TypeError.prototype%': TypeError;
'%TypeError.prototype.name%': typeof TypeError.prototype.name;
'%TypeError.prototype.message%': typeof TypeError.prototype.message;
'%TypeErrorPrototype.name%': typeof TypeError.prototype.name;
'%TypeErrorPrototype.message%': typeof TypeError.prototype.message;
'%Uint8Array.prototype%': Uint8Array;
'%Uint8Array.prototype.BYTES_PER_ELEMENT%': typeof Uint8Array.prototype.BYTES_PER_ELEMENT;
'%Uint8Array.BYTES_PER_ELEMENT%': typeof Uint8Array.BYTES_PER_ELEMENT;
'%Uint8ArrayPrototype.BYTES_PER_ELEMENT%': typeof Uint8Array.prototype.BYTES_PER_ELEMENT;
'%Uint8ClampedArray.prototype%': Uint8ClampedArray;
'%Uint8ClampedArray.prototype.BYTES_PER_ELEMENT%': typeof Uint8ClampedArray.prototype.BYTES_PER_ELEMENT;
'%Uint8ClampedArray.BYTES_PER_ELEMENT%': typeof Uint8ClampedArray.BYTES_PER_ELEMENT;
'%Uint8ClampedArrayPrototype.BYTES_PER_ELEMENT%': typeof Uint8ClampedArray.prototype.BYTES_PER_ELEMENT;
'%Uint16Array.prototype%': Uint16Array;
'%Uint16Array.prototype.BYTES_PER_ELEMENT%': typeof Uint16Array.prototype.BYTES_PER_ELEMENT;
'%Uint16Array.BYTES_PER_ELEMENT%': typeof Uint16Array.BYTES_PER_ELEMENT;
'%Uint16ArrayPrototype.BYTES_PER_ELEMENT%': typeof Uint16Array.prototype.BYTES_PER_ELEMENT;
'%Uint32Array.prototype%': Uint32Array;
'%Uint32Array.prototype.BYTES_PER_ELEMENT%': typeof Uint32Array.prototype.BYTES_PER_ELEMENT;
'%Uint32Array.BYTES_PER_ELEMENT%': typeof Uint32Array.BYTES_PER_ELEMENT;
'%Uint32ArrayPrototype.BYTES_PER_ELEMENT%': typeof Uint32Array.prototype.BYTES_PER_ELEMENT;
'%URIError.prototype%': URIError;
'%URIError.prototype.name%': typeof URIError.prototype.name;
'%URIError.prototype.message%': typeof URIError.prototype.message;
'%URIErrorPrototype.name%': typeof URIError.prototype.name;
'%URIErrorPrototype.message%': typeof URIError.prototype.message;
'%WeakMap.prototype%': typeof WeakMap.prototype;
'%WeakMap.prototype.delete%': typeof WeakMap.prototype.delete;
'%WeakMap.prototype.get%': typeof WeakMap.prototype.get;
'%WeakMap.prototype.set%': typeof WeakMap.prototype.set;
'%WeakMap.prototype.has%': typeof WeakMap.prototype.has;
'%WeakMapPrototype.delete%': typeof WeakMap.prototype.delete;
'%WeakMapPrototype.get%': typeof WeakMap.prototype.get;
'%WeakMapPrototype.set%': typeof WeakMap.prototype.set;
'%WeakMapPrototype.has%': typeof WeakMap.prototype.has;
'%WeakSet.prototype%': typeof WeakSet.prototype;
'%WeakSet.prototype.delete%': typeof WeakSet.prototype.delete;
'%WeakSet.prototype.has%': typeof WeakSet.prototype.has;
'%WeakSet.prototype.add%': typeof WeakSet.prototype.add;
'%WeakSetPrototype.delete%': typeof WeakSet.prototype.delete;
'%WeakSetPrototype.has%': typeof WeakSet.prototype.has;
'%WeakSetPrototype.add%': typeof WeakSet.prototype.add;
}
} | the_stack |
import { BehaviorSubject } from '~/node_modules/rxjs';
import { IUser } from '~/models/auth/user/IUser';
import { ICommunity } from '~/models/communities/community/ICommunity';
import {
ApproveFollowRequestFromUserParams,
BlockUserParams,
CancelRequestToFollowUserParams,
ClosePostParams,
CommentPostParams,
ConfirmConnectionWithUserParaUserParams,
ConnectWithUserParams,
DeleteNotificationParams,
DeletePostCommentParams,
DeletePostCommentReactionParams,
DeletePostParams,
DeletePostReactionParams,
DisablePostCommentsParams,
DisconnectFromUserParams,
EditPostCommentParams,
EnablePostCommentsParams,
FollowUserParams,
GetAdministratedCommunitiesParams,
GetCommunityAdministratorsParams,
GetCommunityMembersParams,
GetCommunityModeratorsParams,
GetCommunityParams,
GetCommunityPostsCountParams,
GetCommunityPostsParams,
GetConnectionsCircleParams,
GetFavoriteCommunitiesParams,
GetHashtagParams,
GetHashtagPostsParams,
GetJoinedCommunitiesParams,
GetModeratedCommunitiesParams,
GetNotificationsParams,
GetPostCommentReactionsEmojiApiCountParams,
GetPostCommentReactionsParams,
GetPostCommentRepliesParams,
GetPostCommentsParams,
GetPostMediaParams,
GetPostParams,
GetPostReactionsEmojiApiCountParams,
GetPostReactionsParams,
GetTimelinePostsParams,
GetTopPostsParams,
GetTrendingCommunitiesParams,
GetTrendingPostsParams,
GetUnreadNotificationsCountParams,
GetUserParams,
JoinCommunityParams,
LeaveCommunityParams,
OpenPostParams,
ReactToPostCommentParams,
ReactToPostParams,
ReadNotificationParams,
ReadNotificationsParams,
RejectFollowRequestFromUserParams,
ReplyToPostCommentParams,
ReportCommunityParams,
ReportHashtagParams,
ReportPostCommentParams,
ReportPostParams,
ReportUserParams,
RequestToFollowUserParams,
SearchCommunitiesParams,
SearchCommunityAdministratorsParams,
SearchCommunityMembersParams,
SearchCommunityModeratorsParams,
SearchHashtagsParams,
SearchUsersParams,
TranslatePostParams,
TranslatePostCommentParams,
UnblockUserParams,
UnfollowUserParams,
UpdateConnectionWithUserParaUserParams,
EditPostParams,
SearchJoinedCommunitiesParams,
CreateCommunityPostParams,
AddMediaToPostParams,
PublishPostParams,
GetPostStatusParams,
CreatePostParams,
PreviewLinkParams,
UpdateUserParams,
GetFollowersParams,
GetFollowingsParams,
SearchFollowersParams,
SearchFollowingsParams,
FavoriteCommunityParams,
UnfavoriteCommunityParams,
RemoveCommunityAdministratorParams,
UpdateCommunityParams,
UpdateCommunityAvatarParams,
DeleteCommunityAvatarParams,
UpdateCommunityCoverParams,
DeleteCommunityCoverParams,
RemoveCommunityModeratorParams,
GetCommunityBannedUsersParams,
SearchCommunityBannedUsersParams,
BanCommunityUserParams,
UnbanCommunityUserParams,
DeleteCommunityParams,
AddCommunityAdministratorParams,
AddCommunityModeratorParams,
CreateCommunityParams,
CreateConnectionsCircleParams,
UpdateConnectionsCircleParams,
DeleteConnectionsCircleParams,
CheckConnectionsCircleNameIsAvailableParams,
} from '~/services/user/UserServiceTypes';
import { IPost } from '~/models/posts/post/IPost';
import { ITopPost } from '~/models/posts/top-post/ITopPost';
import { ITrendingPost } from '~/models/posts/trending-post/ITrendingPost';
import { IPostMedia } from '~/models/posts/post-media/IPostMedia';
import { IPostComment } from '~/models/posts/post-comment/IPostComment';
import { IPostReaction } from '~/models/posts/post-reaction/IPostReaction';
import { IReactionsEmojiCount } from '~/models/posts/reactions-emoji-count/IReactionsEmojiCount';
import { IPostCommentReaction } from '~/models/posts/post-comment-reaction/IPostCommentReaction';
import { IEmojiGroup } from '~/models/common/emoji-group/IEmojiGroup';
import {
LoginApiParams,
RegistrationApiParams,
RegistrationResponse,
RequestResetPasswordApiParams,
ResetPasswordApiParams,
IsInviteTokenValidApiParams,
IsEmailAvailableApiParams,
IsUsernameAvailableApiParams
} from '~/services/Apis/auth/AuthApiServiceTypes';
import { INotification } from '~/models/notifications/notification/INotification';
import { IFollow } from '~/models/follows/follow/IFollow';
import { ICategory } from '~/models/common/category/ICategory';
import { IHashtag } from '~/models/common/hashtag/IHashtag';
import { IModerationCategory } from '~/models/moderation/moderation_category/IModerationCategory';
import { IConnection } from '~/models/connections/connection/IConnection';
import { ICircle } from '~/models/connections/circle/ICircle';
import { GetSuggestedCommunitiesApiParams } from '~/services/Apis/communities/CommunitiesApiServiceTypes';
import { PostStatus } from '~/models/posts/post/lib/PostStatus';
import { ILinkPreview } from '~/models/link-previews/link-preview/ILinkPreview';
export interface IUserService {
loggedInUser: BehaviorSubject<IUser | undefined>;
// AUTH STARTS
login(data: LoginApiParams): Promise<IUser>;
register(data: RegistrationApiParams): Promise<RegistrationResponse>;
isInviteTokenValid(data: IsInviteTokenValidApiParams): Promise<boolean>;
isEmailAvailable(data: IsEmailAvailableApiParams): Promise<boolean>;
isUsernameAvailable(data: IsUsernameAvailableApiParams): Promise<boolean>;
requestResetPassword(data: RequestResetPasswordApiParams): Promise<void>;
resetPassword(data: ResetPasswordApiParams): Promise<void>;
logout(): Promise<void>;
hasStoredAuthToken(): Promise<boolean>;
getStoredAuthToken(): Promise<string>;
loginWithAuthToken(token: string): Promise<IUser>;
storeAuthToken(token: string): void;
loginWithStoredAuthToken(): Promise<IUser>;
refreshLoggedInUser(): Promise<IUser>;
attemptToBootstrapLoggedInUser(): Promise<IUser | null>;
isLoggedIn(): boolean;
getUser(params: GetUserParams): Promise<IUser>;
updateUser(params: UpdateUserParams): Promise<IUser>;
searchUsers(params: SearchUsersParams): Promise<IHashtag[]>;
reportUser(params: ReportUserParams): Promise<void>;
blockUser(params: BlockUserParams): Promise<void>;
unblockUser(params: UnblockUserParams): Promise<void>;
searchFollowers(params: SearchFollowersParams): Promise<IUser[]>;
getFollowers(params: GetFollowersParams): Promise<IUser[]>;
searchFollowings(params: SearchFollowingsParams): Promise<IUser[]>;
getFollowings(params: GetFollowingsParams): Promise<IUser[]>;
// AUTH ENDS
// COMMUNITIES START
getTrendingCommunities(params?: GetTrendingCommunitiesParams): Promise<ICommunity[]>;
getFavoriteCommunities(params?: GetFavoriteCommunitiesParams): Promise<ICommunity[]>;
getSuggestedCommunities(params?: GetSuggestedCommunitiesApiParams): Promise<ICommunity[]>;
getAdministratedCommunities(params?: GetAdministratedCommunitiesParams): Promise<ICommunity[]>;
getModeratedCommunities(params?: GetModeratedCommunitiesParams): Promise<ICommunity[]>;
getJoinedCommunities(params?: GetJoinedCommunitiesParams): Promise<ICommunity[]>;
searchJoinedCommunities(params?: SearchJoinedCommunitiesParams): Promise<ICommunity[]>;
searchCommunities(params: SearchCommunitiesParams): Promise<ICommunity[]>;
getCommunity(params: GetCommunityParams): Promise<ICommunity>;
getCommunityMembers(params: GetCommunityMembersParams): Promise<IUser[]>;
getCommunityPosts(params: GetCommunityPostsParams): Promise<IPost[]>;
searchCommunityMembers(params: SearchCommunityMembersParams): Promise<IUser[]>;
getCommunityAdministrators(params: GetCommunityAdministratorsParams): Promise<IUser[]>;
searchCommunityAdministrators(params: SearchCommunityAdministratorsParams): Promise<IUser[]>;
addCommunityAdministrator(params: AddCommunityAdministratorParams): Promise<ICommunity>;
removeCommunityAdministrator(params: RemoveCommunityAdministratorParams): Promise<void>;
getCommunityModerators(params: GetCommunityModeratorsParams): Promise<IUser[]>;
searchCommunityModerators(params: SearchCommunityModeratorsParams): Promise<IUser[]>;
addCommunityModerator(params: AddCommunityModeratorParams): Promise<ICommunity>;
removeCommunityModerator(params: RemoveCommunityModeratorParams): Promise<void>;
getCommunityBannedUsers(params: GetCommunityBannedUsersParams): Promise<IUser[]>;
searchCommunityBannedUsers(params: SearchCommunityBannedUsersParams): Promise<IUser[]>;
banCommunityUser(params: BanCommunityUserParams): Promise<void>;
unbanCommunityUser(params: UnbanCommunityUserParams): Promise<void>;
getCommunityPostsCount(params: GetCommunityPostsCountParams): Promise<ICommunity>;
joinCommunity(params: JoinCommunityParams): Promise<ICommunity>;
leaveCommunity(params: LeaveCommunityParams): Promise<ICommunity>;
reportCommunity(params: ReportCommunityParams): Promise<void>;
favoriteCommunity(params: FavoriteCommunityParams): Promise<void>;
unfavoriteCommunity(params: UnfavoriteCommunityParams): Promise<void>;
createCommunity(params: CreateCommunityParams): Promise<ICommunity>;
updateCommunity(params: UpdateCommunityParams): Promise<ICommunity>;
updateCommunityAvatar(params: UpdateCommunityAvatarParams): Promise<ICommunity>;
deleteCommunityAvatar(params: DeleteCommunityAvatarParams): Promise<ICommunity>;
updateCommunityCover(params: UpdateCommunityCoverParams): Promise<ICommunity>;
deleteCommunityCover(params: DeleteCommunityCoverParams): Promise<ICommunity>;
createCommunityPost(params: CreateCommunityPostParams): Promise<IPost>;
deleteCommunity(params: DeleteCommunityParams): Promise<void>;
// COMMUNITIES END
// POSTS START
getTopPosts(params?: GetTopPostsParams): Promise<ITopPost[]>;
getTrendingPosts(params?: GetTrendingPostsParams): Promise<ITrendingPost[]>;
getTimelinePosts(params?: GetTimelinePostsParams): Promise<IPost[]>;
getPostMedia(params: GetPostMediaParams): Promise<IPostMedia[]>;
getPost(params: GetPostParams): Promise<IPost>;
deletePost(params: DeletePostParams): Promise<void>;
getPostComments(params: GetPostCommentsParams): Promise<IPostComment[]>;
getPostCommentReplies(params: GetPostCommentRepliesParams): Promise<IPostComment[]>;
commentPost(params: CommentPostParams): Promise<IPostComment>;
editPost(params: EditPostParams): Promise<IPost>;
createPost(params: CreatePostParams): Promise<IPost>;
addMediaToPost(params: AddMediaToPostParams): Promise<void>;
publishPost(params: PublishPostParams): Promise<void>;
getPostStatus(params: GetPostStatusParams): Promise<PostStatus>;
editPostComment(params: EditPostCommentParams): Promise<IPostComment>;
replyToPostComment(params: ReplyToPostCommentParams): Promise<IPostComment>;
deletePostComment(params: DeletePostCommentParams): Promise<void>;
getPostReactions(params: GetPostReactionsParams): Promise<IPostReaction[]>;
getPostReactionsEmojiCount(params: GetPostReactionsEmojiApiCountParams): Promise<IReactionsEmojiCount[]>;
reactToPost(params: ReactToPostParams): Promise<IPostReaction>;
deletePostReaction(params: DeletePostReactionParams): Promise<void>;
getPostCommentReactions(params: GetPostCommentReactionsParams): Promise<IPostCommentReaction[]>;
getPostCommentReactionsEmojiCount(params: GetPostCommentReactionsEmojiApiCountParams): Promise<IReactionsEmojiCount[]>;
reactToPostComment(params: ReactToPostCommentParams): Promise<IPostCommentReaction>;
deletePostCommentReaction(params: DeletePostCommentReactionParams): Promise<void>;
getReactionEmojiGroups(): Promise<IEmojiGroup[]>;
reportPost(params: ReportPostParams): Promise<void>;
reportPostComment(params: ReportPostCommentParams): Promise<void>;
openPost(params: OpenPostParams): Promise<void>;
closePost(params: ClosePostParams): Promise<void>;
enablePostComments(params: EnablePostCommentsParams): Promise<void>;
disablePostComments(params: DisablePostCommentsParams): Promise<void>;
translatePost(params: TranslatePostParams): Promise<String>;
translatePostComment(params: TranslatePostCommentParams): Promise<String>;
previewLink(params: PreviewLinkParams): Promise<ILinkPreview>;
linkIsPreviewable(params: PreviewLinkParams): Promise<boolean>;
// POSTS END
// NOTIFICATIONS START
readNotifications(params: ReadNotificationsParams): Promise<void>;
getNotifications(params: GetNotificationsParams): Promise<INotification[]>;
readNotification(params: ReadNotificationParams): Promise<void>;
deleteNotification(params: DeleteNotificationParams): Promise<void>;
getUnreadNotificationsCount(params: GetUnreadNotificationsCountParams): Promise<number>;
// NOTIFICATIONS END
// FOLLOWS START
followUser(params: FollowUserParams): Promise<IFollow>;
unfollowUser(params: UnfollowUserParams): Promise<IUser>;
requestToFollowUser(params: RequestToFollowUserParams): Promise<void>;
cancelRequestToFollowUser(params: CancelRequestToFollowUserParams): Promise<void>;
approveFollowRequestFromUser(params: ApproveFollowRequestFromUserParams): Promise<void>;
rejectFollowRequestFromUser(params: RejectFollowRequestFromUserParams): Promise<void>;
// FOLLOWS END
// CATEGORIES START
getCategories(): Promise<ICategory[]>
// CATEGORIES END
// HASHTAGS START
getHashtag(params: GetHashtagParams): Promise<IHashtag>;
getHashtagPosts(params: GetHashtagPostsParams): Promise<IPost[]>;
searchHashtags(params: SearchHashtagsParams): Promise<IHashtag[]>;
reportHashtag(params: ReportHashtagParams): Promise<void>;
// HASHTAGS END
// MODERATION START
getModerationCategories(): Promise<IModerationCategory[]>;
// MODERATION END
// CONNECTIONS START
connectWithUser(params: ConnectWithUserParams): Promise<IConnection>;
disconnectFromUser(params: DisconnectFromUserParams): Promise<void>;
confirmConnectionWithUser(params: ConfirmConnectionWithUserParaUserParams): Promise<IConnection>;
updateConnectionWithUser(params: UpdateConnectionWithUserParaUserParams): Promise<IConnection>;
getConnectionsCircle(params: GetConnectionsCircleParams): Promise<ICircle>;
getConnectionsCircles(): Promise<ICircle[]>;
createConnectionsCircle(params: CreateConnectionsCircleParams): Promise<ICircle>;
updateConnectionsCircle(params: UpdateConnectionsCircleParams): Promise<ICircle>;
deleteConnectionsCircle(params: DeleteConnectionsCircleParams): Promise<ICircle>;
checkConnectionsCircleNameIsAvailable(params: CheckConnectionsCircleNameIsAvailableParams): Promise<boolean>;
// CONNECTIONS END
} | the_stack |
declare module com {
export module google {
export module firebase {
export module database {
export class BuildConfig {
public static class: java.lang.Class<com.google.firebase.database.BuildConfig>;
public static DEBUG: boolean;
public static APPLICATION_ID: string;
public static BUILD_TYPE: string;
public static FLAVOR: string;
public static VERSION_CODE: number;
public static VERSION_NAME: string;
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class ChildEventListener {
public static class: java.lang.Class<com.google.firebase.database.ChildEventListener>;
/**
* Constructs a new instance of the com.google.firebase.database.ChildEventListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onChildAdded(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
onChildChanged(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
onChildRemoved(param0: com.google.firebase.database.DataSnapshot): void;
onChildMoved(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
onCancelled(param0: com.google.firebase.database.DatabaseError): void;
});
public constructor();
public onChildChanged(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
public onCancelled(param0: com.google.firebase.database.DatabaseError): void;
public onChildRemoved(param0: com.google.firebase.database.DataSnapshot): void;
public onChildMoved(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
public onChildAdded(param0: com.google.firebase.database.DataSnapshot, param1: string): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class DataSnapshot {
public static class: java.lang.Class<com.google.firebase.database.DataSnapshot>;
public getValue(): any;
public child(param0: string): com.google.firebase.database.DataSnapshot;
public getRef(): com.google.firebase.database.DatabaseReference;
public getChildrenCount(): number;
public getValue(param0: java.lang.Class): any;
public getValue(param0: com.google.firebase.database.GenericTypeIndicator<any>): any;
public exists(): boolean;
public getKey(): string;
public getPriority(): any;
public hasChild(param0: string): boolean;
public toString(): string;
public getChildren(): java.lang.Iterable<com.google.firebase.database.DataSnapshot>;
public getValue(param0: boolean): any;
public hasChildren(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class DatabaseError {
public static class: java.lang.Class<com.google.firebase.database.DatabaseError>;
public static DATA_STALE: number;
public static OPERATION_FAILED: number;
public static PERMISSION_DENIED: number;
public static DISCONNECTED: number;
public static EXPIRED_TOKEN: number;
public static INVALID_TOKEN: number;
public static MAX_RETRIES: number;
public static OVERRIDDEN_BY_SET: number;
public static UNAVAILABLE: number;
public static USER_CODE_EXCEPTION: number;
public static NETWORK_ERROR: number;
public static WRITE_CANCELED: number;
public static UNKNOWN_ERROR: number;
public static fromStatus(param0: string): com.google.firebase.database.DatabaseError;
public toString(): string;
public static fromStatus(param0: string, param1: string, param2: string): com.google.firebase.database.DatabaseError;
public static fromCode(param0: number): com.google.firebase.database.DatabaseError;
public static fromException(param0: java.lang.Throwable): com.google.firebase.database.DatabaseError;
public getMessage(): string;
public toException(): com.google.firebase.database.DatabaseException;
public static fromStatus(param0: string, param1: string): com.google.firebase.database.DatabaseError;
public getDetails(): string;
public getCode(): number;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class DatabaseException {
public static class: java.lang.Class<com.google.firebase.database.DatabaseException>;
public constructor(param0: string, param1: java.lang.Throwable);
public constructor(param0: string);
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class DatabaseReference extends com.google.firebase.database.Query {
public static class: java.lang.Class<com.google.firebase.database.DatabaseReference>;
public runTransaction(param0: com.google.firebase.database.Transaction.Handler, param1: boolean): void;
public getDatabase(): com.google.firebase.database.FirebaseDatabase;
public static goOffline(): void;
public getRoot(): com.google.firebase.database.DatabaseReference;
public setPriority(param0: any, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public updateChildren(param0: java.util.Map<string,any>, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public setValue(param0: any, param1: any): com.google.android.gms.tasks.Task<java.lang.Void>;
public getKey(): string;
public equals(param0: any): boolean;
public toString(): string;
public getParent(): com.google.firebase.database.DatabaseReference;
public removeValue(param0: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public onDisconnect(): com.google.firebase.database.OnDisconnect;
public setValue(param0: any, param1: any, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public setPriority(param0: any): com.google.android.gms.tasks.Task<java.lang.Void>;
public removeValue(): com.google.android.gms.tasks.Task<java.lang.Void>;
public static goOnline(): void;
public setValue(param0: any): com.google.android.gms.tasks.Task<java.lang.Void>;
public updateChildren(param0: java.util.Map<string,any>): com.google.android.gms.tasks.Task<java.lang.Void>;
public runTransaction(param0: com.google.firebase.database.Transaction.Handler): void;
public hashCode(): number;
public child(param0: string): com.google.firebase.database.DatabaseReference;
public push(): com.google.firebase.database.DatabaseReference;
public setValue(param0: any, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
}
export module DatabaseReference {
export class CompletionListener {
public static class: java.lang.Class<com.google.firebase.database.DatabaseReference.CompletionListener>;
/**
* Constructs a new instance of the com.google.firebase.database.DatabaseReference$CompletionListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onComplete(param0: com.google.firebase.database.DatabaseError, param1: com.google.firebase.database.DatabaseReference): void;
});
public constructor();
public onComplete(param0: com.google.firebase.database.DatabaseError, param1: com.google.firebase.database.DatabaseReference): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class DatabaseRegistrar {
public static class: java.lang.Class<com.google.firebase.database.DatabaseRegistrar>;
public constructor();
public getComponents(): java.util.List<com.google.firebase.components.Component<any>>;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class Exclude {
public static class: java.lang.Class<com.google.firebase.database.Exclude>;
/**
* Constructs a new instance of the com.google.firebase.database.Exclude interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class FirebaseDatabase {
public static class: java.lang.Class<com.google.firebase.database.FirebaseDatabase>;
public static getInstance(param0: com.google.firebase.FirebaseApp): com.google.firebase.database.FirebaseDatabase;
public setLogLevel(param0: com.google.firebase.database.Logger.Level): void;
public getReferenceFromUrl(param0: string): com.google.firebase.database.DatabaseReference;
public getReference(): com.google.firebase.database.DatabaseReference;
public purgeOutstandingWrites(): void;
public goOffline(): void;
public static getInstance(): com.google.firebase.database.FirebaseDatabase;
public getReference(param0: string): com.google.firebase.database.DatabaseReference;
public static getInstance(param0: string): com.google.firebase.database.FirebaseDatabase;
public getApp(): com.google.firebase.FirebaseApp;
public static getInstance(param0: com.google.firebase.FirebaseApp, param1: string): com.google.firebase.database.FirebaseDatabase;
public goOnline(): void;
public setPersistenceCacheSizeBytes(param0: number): void;
public static getSdkVersion(): string;
public setPersistenceEnabled(param0: boolean): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class FirebaseDatabaseComponent {
public static class: java.lang.Class<com.google.firebase.database.FirebaseDatabaseComponent>;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export abstract class GenericTypeIndicator<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.GenericTypeIndicator<any>>;
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class IgnoreExtraProperties {
public static class: java.lang.Class<com.google.firebase.database.IgnoreExtraProperties>;
/**
* Constructs a new instance of the com.google.firebase.database.IgnoreExtraProperties interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class InternalHelpers {
public static class: java.lang.Class<com.google.firebase.database.InternalHelpers>;
public constructor();
public static createDatabaseForTests(param0: com.google.firebase.FirebaseApp, param1: com.google.firebase.database.core.RepoInfo, param2: com.google.firebase.database.core.DatabaseConfig): com.google.firebase.database.FirebaseDatabase;
public static createDataSnapshot(param0: com.google.firebase.database.DatabaseReference, param1: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.DataSnapshot;
public static createReference(param0: com.google.firebase.database.core.Repo, param1: com.google.firebase.database.core.Path): com.google.firebase.database.DatabaseReference;
public static createMutableData(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.MutableData;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class Logger {
public static class: java.lang.Class<com.google.firebase.database.Logger>;
/**
* Constructs a new instance of the com.google.firebase.database.Logger interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
export module Logger {
export class Level {
public static class: java.lang.Class<com.google.firebase.database.Logger.Level>;
public static DEBUG: com.google.firebase.database.Logger.Level;
public static INFO: com.google.firebase.database.Logger.Level;
public static WARN: com.google.firebase.database.Logger.Level;
public static ERROR: com.google.firebase.database.Logger.Level;
public static NONE: com.google.firebase.database.Logger.Level;
public static valueOf(param0: string): com.google.firebase.database.Logger.Level;
public static values(): native.Array<com.google.firebase.database.Logger.Level>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class MutableData {
public static class: java.lang.Class<com.google.firebase.database.MutableData>;
public getValue(): any;
public getChildren(): java.lang.Iterable<com.google.firebase.database.MutableData>;
public setValue(param0: any): void;
public getChildrenCount(): number;
public getValue(param0: java.lang.Class): any;
public setPriority(param0: any): void;
public getValue(param0: com.google.firebase.database.GenericTypeIndicator<any>): any;
public child(param0: string): com.google.firebase.database.MutableData;
public getKey(): string;
public getPriority(): any;
public equals(param0: any): boolean;
public hasChild(param0: string): boolean;
public toString(): string;
public hasChildren(): boolean;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class OnDisconnect {
public static class: java.lang.Class<com.google.firebase.database.OnDisconnect>;
public setValue(param0: any, param1: number, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public updateChildren(param0: java.util.Map<string,any>, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public setValue(param0: any, param1: java.util.Map, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public cancel(): com.google.android.gms.tasks.Task<java.lang.Void>;
public removeValue(param0: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public removeValue(): com.google.android.gms.tasks.Task<java.lang.Void>;
public setValue(param0: any, param1: number): com.google.android.gms.tasks.Task<java.lang.Void>;
public setValue(param0: any): com.google.android.gms.tasks.Task<java.lang.Void>;
public setValue(param0: any, param1: string): com.google.android.gms.tasks.Task<java.lang.Void>;
public updateChildren(param0: java.util.Map<string,any>): com.google.android.gms.tasks.Task<java.lang.Void>;
public cancel(param0: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public setValue(param0: any, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public setValue(param0: any, param1: string, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class PropertyName {
public static class: java.lang.Class<com.google.firebase.database.PropertyName>;
/**
* Constructs a new instance of the com.google.firebase.database.PropertyName interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class Query {
public static class: java.lang.Class<com.google.firebase.database.Query>;
public repo: com.google.firebase.database.core.Repo;
public path: com.google.firebase.database.core.Path;
public params: com.google.firebase.database.core.view.QueryParams;
public removeEventListener(param0: com.google.firebase.database.ValueEventListener): void;
public endAt(param0: number, param1: string): com.google.firebase.database.Query;
public keepSynced(param0: boolean): void;
public equalTo(param0: boolean, param1: string): com.google.firebase.database.Query;
public endAt(param0: string): com.google.firebase.database.Query;
public startAt(param0: string, param1: string): com.google.firebase.database.Query;
public endAt(param0: boolean): com.google.firebase.database.Query;
public startAt(param0: number, param1: string): com.google.firebase.database.Query;
public startAt(param0: number): com.google.firebase.database.Query;
public limitToFirst(param0: number): com.google.firebase.database.Query;
public startAt(param0: string): com.google.firebase.database.Query;
public equalTo(param0: number, param1: string): com.google.firebase.database.Query;
public orderByChild(param0: string): com.google.firebase.database.Query;
public equalTo(param0: number): com.google.firebase.database.Query;
public getPath(): com.google.firebase.database.core.Path;
public equalTo(param0: string): com.google.firebase.database.Query;
public endAt(param0: string, param1: string): com.google.firebase.database.Query;
public orderByPriority(): com.google.firebase.database.Query;
public endAt(param0: boolean, param1: string): com.google.firebase.database.Query;
public getRef(): com.google.firebase.database.DatabaseReference;
public limitToLast(param0: number): com.google.firebase.database.Query;
public addListenerForSingleValueEvent(param0: com.google.firebase.database.ValueEventListener): void;
public equalTo(param0: string, param1: string): com.google.firebase.database.Query;
public getRepo(): com.google.firebase.database.core.Repo;
public addChildEventListener(param0: com.google.firebase.database.ChildEventListener): com.google.firebase.database.ChildEventListener;
public equalTo(param0: boolean): com.google.firebase.database.Query;
public addValueEventListener(param0: com.google.firebase.database.ValueEventListener): com.google.firebase.database.ValueEventListener;
public startAt(param0: boolean): com.google.firebase.database.Query;
public removeEventListener(param0: com.google.firebase.database.ChildEventListener): void;
public orderByValue(): com.google.firebase.database.Query;
public endAt(param0: number): com.google.firebase.database.Query;
public orderByKey(): com.google.firebase.database.Query;
public getSpec(): com.google.firebase.database.core.view.QuerySpec;
public startAt(param0: boolean, param1: string): com.google.firebase.database.Query;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class ServerValue {
public static class: java.lang.Class<com.google.firebase.database.ServerValue>;
public static TIMESTAMP: java.util.Map<string,string>;
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class ThrowOnExtraProperties {
public static class: java.lang.Class<com.google.firebase.database.ThrowOnExtraProperties>;
/**
* Constructs a new instance of the com.google.firebase.database.ThrowOnExtraProperties interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
});
public constructor();
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class Transaction {
public static class: java.lang.Class<com.google.firebase.database.Transaction>;
public constructor();
public static success(param0: com.google.firebase.database.MutableData): com.google.firebase.database.Transaction.Result;
public static abort(): com.google.firebase.database.Transaction.Result;
}
export module Transaction {
export class Handler {
public static class: java.lang.Class<com.google.firebase.database.Transaction.Handler>;
/**
* Constructs a new instance of the com.google.firebase.database.Transaction$Handler interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
doTransaction(param0: com.google.firebase.database.MutableData): com.google.firebase.database.Transaction.Result;
onComplete(param0: com.google.firebase.database.DatabaseError, param1: boolean, param2: com.google.firebase.database.DataSnapshot): void;
});
public constructor();
public onComplete(param0: com.google.firebase.database.DatabaseError, param1: boolean, param2: com.google.firebase.database.DataSnapshot): void;
public doTransaction(param0: com.google.firebase.database.MutableData): com.google.firebase.database.Transaction.Result;
}
export class Result {
public static class: java.lang.Class<com.google.firebase.database.Transaction.Result>;
public isSuccess(): boolean;
public getNode(): com.google.firebase.database.snapshot.Node;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export class ValueEventListener {
public static class: java.lang.Class<com.google.firebase.database.ValueEventListener>;
/**
* Constructs a new instance of the com.google.firebase.database.ValueEventListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onDataChange(param0: com.google.firebase.database.DataSnapshot): void;
onCancelled(param0: com.google.firebase.database.DatabaseError): void;
});
public constructor();
public onCancelled(param0: com.google.firebase.database.DatabaseError): void;
public onDataChange(param0: com.google.firebase.database.DataSnapshot): void;
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module android {
export abstract class AndroidAuthTokenProvider extends com.google.firebase.database.core.AuthTokenProvider {
public static class: java.lang.Class<com.google.firebase.database.android.AndroidAuthTokenProvider>;
public static forUnauthenticatedAccess(): com.google.firebase.database.core.AuthTokenProvider;
public constructor();
public static forAuthenticatedAccess(param0: com.google.firebase.auth.internal.InternalAuthProvider): com.google.firebase.database.core.AuthTokenProvider;
public removeTokenChangeListener(param0: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
public getToken(param0: boolean, param1: com.google.firebase.database.core.AuthTokenProvider.GetTokenCompletionListener): void;
public addTokenChangeListener(param0: java.util.concurrent.ExecutorService, param1: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module android {
export class AndroidEventTarget extends com.google.firebase.database.core.EventTarget {
public static class: java.lang.Class<com.google.firebase.database.android.AndroidEventTarget>;
public constructor();
public shutdown(): void;
public postEvent(param0: java.lang.Runnable): void;
public restart(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module android {
export class AndroidPlatform extends com.google.firebase.database.core.Platform {
public static class: java.lang.Class<com.google.firebase.database.android.AndroidPlatform>;
public newPersistentConnection(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.connection.ConnectionContext, param2: com.google.firebase.database.connection.HostInfo, param3: com.google.firebase.database.connection.PersistentConnection.Delegate): com.google.firebase.database.connection.PersistentConnection;
public getSSLCacheDirectory(): java.io.File;
public getPlatformVersion(): string;
public newLogger(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.logging.Logger.Level, param2: java.util.List<string>): com.google.firebase.database.logging.Logger;
public getUserAgent(param0: com.google.firebase.database.core.Context): string;
public createPersistenceManager(param0: com.google.firebase.database.core.Context, param1: string): com.google.firebase.database.core.persistence.PersistenceManager;
public newEventTarget(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.EventTarget;
public newRunLoop(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.RunLoop;
public constructor(param0: com.google.firebase.FirebaseApp);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module android {
export class SqlPersistenceStorageEngine extends com.google.firebase.database.core.persistence.PersistenceStorageEngine {
public static class: java.lang.Class<com.google.firebase.database.android.SqlPersistenceStorageEngine>;
public updateTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public close(): void;
public loadTrackedQueryKeys(param0: number): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
public pruneCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.persistence.PruneForest): void;
public loadTrackedQueryKeys(param0: java.util.Set<java.lang.Long>): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
public saveTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public saveTrackedQuery(param0: com.google.firebase.database.core.persistence.TrackedQuery): void;
public serverCache(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public beginTransaction(): void;
public serverCacheEstimatedSizeInBytes(): number;
public deleteTrackedQuery(param0: number): void;
public constructor(param0: globalAndroid.content.Context, param1: com.google.firebase.database.core.Context, param2: string);
public setTransactionSuccessful(): void;
public saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
public loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public overwriteServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public removeAllUserWrites(): void;
public saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
public resetPreviouslyActiveTrackedQueries(param0: number): void;
public purgeCache(): void;
public endTransaction(): void;
public loadTrackedQueries(): java.util.List<com.google.firebase.database.core.persistence.TrackedQuery>;
public removeUserWrite(param0: number): void;
public mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
}
export module SqlPersistenceStorageEngine {
export class PersistentCacheOpenHelper {
public static class: java.lang.Class<com.google.firebase.database.android.SqlPersistenceStorageEngine.PersistentCacheOpenHelper>;
public onUpgrade(param0: globalAndroid.database.sqlite.SQLiteDatabase, param1: number, param2: number): void;
public onCreate(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public constructor(param0: globalAndroid.content.Context, param1: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module annotations {
export class NotNull {
public static class: java.lang.Class<com.google.firebase.database.annotations.NotNull>;
/**
* Constructs a new instance of the com.google.firebase.database.annotations.NotNull interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module annotations {
export class Nullable {
public static class: java.lang.Class<com.google.firebase.database.annotations.Nullable>;
/**
* Constructs a new instance of the com.google.firebase.database.annotations.Nullable interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
value(): string;
});
public constructor();
public value(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class CompoundHash {
public static class: java.lang.Class<com.google.firebase.database.connection.CompoundHash>;
public getPosts(): java.util.List<java.util.List<string>>;
public constructor(param0: java.util.List<java.util.List<string>>, param1: java.util.List<string>);
public getHashes(): java.util.List<string>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class Connection extends com.google.firebase.database.connection.WebsocketConnection.Delegate {
public static class: java.lang.Class<com.google.firebase.database.connection.Connection>;
public close(): void;
public sendRequest(param0: java.util.Map<string,any>, param1: boolean): void;
public open(): void;
public onMessage(param0: java.util.Map<string,any>): void;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: com.google.firebase.database.connection.HostInfo, param2: string, param3: com.google.firebase.database.connection.Connection.Delegate, param4: string);
public onDisconnect(param0: boolean): void;
public injectConnectionFailure(): void;
public close(param0: com.google.firebase.database.connection.Connection.DisconnectReason): void;
}
export module Connection {
export class Delegate {
public static class: java.lang.Class<com.google.firebase.database.connection.Connection.Delegate>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.Connection$Delegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onCacheHost(param0: string): void;
onReady(param0: number, param1: string): void;
onDataMessage(param0: java.util.Map<string,any>): void;
onDisconnect(param0: com.google.firebase.database.connection.Connection.DisconnectReason): void;
onKill(param0: string): void;
});
public constructor();
public onReady(param0: number, param1: string): void;
public onKill(param0: string): void;
public onCacheHost(param0: string): void;
public onDisconnect(param0: com.google.firebase.database.connection.Connection.DisconnectReason): void;
public onDataMessage(param0: java.util.Map<string,any>): void;
}
export class DisconnectReason {
public static class: java.lang.Class<com.google.firebase.database.connection.Connection.DisconnectReason>;
public static SERVER_RESET: com.google.firebase.database.connection.Connection.DisconnectReason;
public static OTHER: com.google.firebase.database.connection.Connection.DisconnectReason;
public static valueOf(param0: string): com.google.firebase.database.connection.Connection.DisconnectReason;
public static values(): native.Array<com.google.firebase.database.connection.Connection.DisconnectReason>;
}
export class State {
public static class: java.lang.Class<com.google.firebase.database.connection.Connection.State>;
public static REALTIME_CONNECTING: com.google.firebase.database.connection.Connection.State;
public static REALTIME_CONNECTED: com.google.firebase.database.connection.Connection.State;
public static REALTIME_DISCONNECTED: com.google.firebase.database.connection.Connection.State;
public static values(): native.Array<com.google.firebase.database.connection.Connection.State>;
public static valueOf(param0: string): com.google.firebase.database.connection.Connection.State;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class ConnectionAuthTokenProvider {
public static class: java.lang.Class<com.google.firebase.database.connection.ConnectionAuthTokenProvider>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.ConnectionAuthTokenProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getToken(param0: boolean, param1: com.google.firebase.database.connection.ConnectionAuthTokenProvider.GetTokenCallback): void;
});
public constructor();
public getToken(param0: boolean, param1: com.google.firebase.database.connection.ConnectionAuthTokenProvider.GetTokenCallback): void;
}
export module ConnectionAuthTokenProvider {
export class GetTokenCallback {
public static class: java.lang.Class<com.google.firebase.database.connection.ConnectionAuthTokenProvider.GetTokenCallback>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.ConnectionAuthTokenProvider$GetTokenCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onSuccess(param0: string): void;
onError(param0: string): void;
});
public constructor();
public onError(param0: string): void;
public onSuccess(param0: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class ConnectionContext {
public static class: java.lang.Class<com.google.firebase.database.connection.ConnectionContext>;
public constructor(param0: com.google.firebase.database.logging.Logger, param1: com.google.firebase.database.connection.ConnectionAuthTokenProvider, param2: java.util.concurrent.ScheduledExecutorService, param3: boolean, param4: string, param5: string, param6: string);
public isPersistenceEnabled(): boolean;
public getAuthTokenProvider(): com.google.firebase.database.connection.ConnectionAuthTokenProvider;
public getExecutorService(): java.util.concurrent.ScheduledExecutorService;
public getUserAgent(): string;
public getLogger(): com.google.firebase.database.logging.Logger;
public getClientSdkVersion(): string;
public getSslCacheDirectory(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class ConnectionUtils {
public static class: java.lang.Class<com.google.firebase.database.connection.ConnectionUtils>;
public constructor();
public static pathToString(param0: java.util.List<string>): string;
public static hardAssert(param0: boolean): void;
public static longFromObject(param0: any): java.lang.Long;
public static stringToPath(param0: string): java.util.List<string>;
public static hardAssert(param0: boolean, param1: string, param2: native.Array<any>): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class Constants {
public static class: java.lang.Class<com.google.firebase.database.connection.Constants>;
public static DOT_INFO_SERVERTIME_OFFSET: string;
public static WIRE_PROTOCOL_VERSION: string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class HostInfo {
public static class: java.lang.Class<com.google.firebase.database.connection.HostInfo>;
public static getConnectionUrl(param0: string, param1: boolean, param2: string, param3: string): java.net.URI;
public isSecure(): boolean;
public getHost(): string;
public constructor(param0: string, param1: string, param2: boolean);
public toString(): string;
public getNamespace(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class ListenHashProvider {
public static class: java.lang.Class<com.google.firebase.database.connection.ListenHashProvider>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.ListenHashProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getSimpleHash(): string;
shouldIncludeCompoundHash(): boolean;
getCompoundHash(): com.google.firebase.database.connection.CompoundHash;
});
public constructor();
public shouldIncludeCompoundHash(): boolean;
public getSimpleHash(): string;
public getCompoundHash(): com.google.firebase.database.connection.CompoundHash;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class PersistentConnection {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnection>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.PersistentConnection interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
initialize(): void;
shutdown(): void;
refreshAuthToken(): void;
refreshAuthToken(param0: string): void;
listen(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.ListenHashProvider, param3: java.lang.Long, param4: com.google.firebase.database.connection.RequestResultCallback): void;
unlisten(param0: java.util.List<string>, param1: java.util.Map<string,any>): void;
purgeOutstandingWrites(): void;
put(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
compareAndPut(param0: java.util.List<string>, param1: any, param2: string, param3: com.google.firebase.database.connection.RequestResultCallback): void;
merge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
onDisconnectPut(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
onDisconnectMerge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
onDisconnectCancel(param0: java.util.List<string>, param1: com.google.firebase.database.connection.RequestResultCallback): void;
interrupt(param0: string): void;
resume(param0: string): void;
isInterrupted(param0: string): boolean;
});
public constructor();
public onDisconnectCancel(param0: java.util.List<string>, param1: com.google.firebase.database.connection.RequestResultCallback): void;
public put(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public unlisten(param0: java.util.List<string>, param1: java.util.Map<string,any>): void;
public isInterrupted(param0: string): boolean;
public refreshAuthToken(): void;
public onDisconnectPut(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public listen(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.ListenHashProvider, param3: java.lang.Long, param4: com.google.firebase.database.connection.RequestResultCallback): void;
public shutdown(): void;
public purgeOutstandingWrites(): void;
public resume(param0: string): void;
public refreshAuthToken(param0: string): void;
public interrupt(param0: string): void;
public initialize(): void;
public compareAndPut(param0: java.util.List<string>, param1: any, param2: string, param3: com.google.firebase.database.connection.RequestResultCallback): void;
public onDisconnectMerge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public merge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
}
export module PersistentConnection {
export class Delegate {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnection.Delegate>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.PersistentConnection$Delegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onDataUpdate(param0: java.util.List<string>, param1: any, param2: boolean, param3: java.lang.Long): void;
onRangeMergeUpdate(param0: java.util.List<string>, param1: java.util.List<com.google.firebase.database.connection.RangeMerge>, param2: java.lang.Long): void;
onConnect(): void;
onDisconnect(): void;
onAuthStatus(param0: boolean): void;
onServerInfoUpdate(param0: java.util.Map<string,any>): void;
});
public constructor();
public onServerInfoUpdate(param0: java.util.Map<string,any>): void;
public onAuthStatus(param0: boolean): void;
public onConnect(): void;
public onDataUpdate(param0: java.util.List<string>, param1: any, param2: boolean, param3: java.lang.Long): void;
public onDisconnect(): void;
public onRangeMergeUpdate(param0: java.util.List<string>, param1: java.util.List<com.google.firebase.database.connection.RangeMerge>, param2: java.lang.Long): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class PersistentConnectionImpl implements com.google.firebase.database.connection.Connection.Delegate, com.google.firebase.database.connection.PersistentConnection {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl>;
public onDisconnectCancel(param0: java.util.List<string>, param1: com.google.firebase.database.connection.RequestResultCallback): void;
public onReady(param0: number, param1: string): void;
public put(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public unlisten(param0: java.util.List<string>, param1: java.util.Map<string,any>): void;
public isInterrupted(param0: string): boolean;
public onDataMessage(param0: java.util.Map<string,any>): void;
public refreshAuthToken(): void;
public onKill(param0: string): void;
public onDisconnectPut(param0: java.util.List<string>, param1: any, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public onCacheHost(param0: string): void;
public listen(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.ListenHashProvider, param3: java.lang.Long, param4: com.google.firebase.database.connection.RequestResultCallback): void;
public openNetworkConnection(param0: string): void;
public injectConnectionFailure(): void;
public shutdown(): void;
public purgeOutstandingWrites(): void;
public resume(param0: string): void;
public onDisconnect(param0: com.google.firebase.database.connection.Connection.DisconnectReason): void;
public interrupt(param0: string): void;
public refreshAuthToken(param0: string): void;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: com.google.firebase.database.connection.HostInfo, param2: com.google.firebase.database.connection.PersistentConnection.Delegate);
public initialize(): void;
public compareAndPut(param0: java.util.List<string>, param1: any, param2: string, param3: com.google.firebase.database.connection.RequestResultCallback): void;
public onDisconnectMerge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
public merge(param0: java.util.List<string>, param1: java.util.Map<string,any>, param2: com.google.firebase.database.connection.RequestResultCallback): void;
}
export module PersistentConnectionImpl {
export class ConnectionRequestCallback {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionRequestCallback>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.PersistentConnectionImpl$ConnectionRequestCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onResponse(param0: java.util.Map<string,any>): void;
});
public constructor();
public onResponse(param0: java.util.Map<string,any>): void;
}
export class ConnectionState {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState>;
public static Disconnected: com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
public static GettingToken: com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
public static Connecting: com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
public static Authenticating: com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
public static Connected: com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
public static values(): native.Array<com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState>;
public static valueOf(param0: string): com.google.firebase.database.connection.PersistentConnectionImpl.ConnectionState;
}
export class ListenQuerySpec {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.ListenQuerySpec>;
public constructor(param0: java.util.List<string>, param1: java.util.Map<string,any>);
public hashCode(): number;
public toString(): string;
public equals(param0: any): boolean;
}
export class OutstandingDisconnect {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.OutstandingDisconnect>;
public getPath(): java.util.List<string>;
public getOnComplete(): com.google.firebase.database.connection.RequestResultCallback;
public getAction(): string;
public getData(): any;
}
export class OutstandingListen {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.OutstandingListen>;
public getHashFunction(): com.google.firebase.database.connection.ListenHashProvider;
public toString(): string;
public getQuery(): com.google.firebase.database.connection.PersistentConnectionImpl.ListenQuerySpec;
public getTag(): java.lang.Long;
}
export class OutstandingPut {
public static class: java.lang.Class<com.google.firebase.database.connection.PersistentConnectionImpl.OutstandingPut>;
public wasSent(): boolean;
public getOnComplete(): com.google.firebase.database.connection.RequestResultCallback;
public getAction(): string;
public markSent(): void;
public getRequest(): java.util.Map<string,any>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class RangeMerge {
public static class: java.lang.Class<com.google.firebase.database.connection.RangeMerge>;
public getOptExclusiveStart(): java.util.List<string>;
public getOptInclusiveEnd(): java.util.List<string>;
public getSnap(): any;
public constructor(param0: java.util.List<string>, param1: java.util.List<string>, param2: any);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class RequestResultCallback {
public static class: java.lang.Class<com.google.firebase.database.connection.RequestResultCallback>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.RequestResultCallback interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onRequestResult(param0: string, param1: string): void;
});
public constructor();
public onRequestResult(param0: string, param1: string): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export class WebsocketConnection {
public static class: java.lang.Class<com.google.firebase.database.connection.WebsocketConnection>;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: com.google.firebase.database.connection.HostInfo, param2: string, param3: com.google.firebase.database.connection.WebsocketConnection.Delegate, param4: string);
public send(param0: java.util.Map<string,any>): void;
public start(): void;
public close(): void;
public open(): void;
}
export module WebsocketConnection {
export class Delegate {
public static class: java.lang.Class<com.google.firebase.database.connection.WebsocketConnection.Delegate>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.WebsocketConnection$Delegate interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onMessage(param0: java.util.Map<string,any>): void;
onDisconnect(param0: boolean): void;
});
public constructor();
public onMessage(param0: java.util.Map<string,any>): void;
public onDisconnect(param0: boolean): void;
}
export class WSClient {
public static class: java.lang.Class<com.google.firebase.database.connection.WebsocketConnection.WSClient>;
/**
* Constructs a new instance of the com.google.firebase.database.connection.WebsocketConnection$WSClient interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
connect(): void;
close(): void;
send(param0: string): void;
});
public constructor();
public close(): void;
public send(param0: string): void;
public connect(): void;
}
export class WSClientTubesock implements com.google.firebase.database.connection.WebsocketConnection.WSClient, com.google.firebase.database.tubesock.WebSocketEventHandler {
public static class: java.lang.Class<com.google.firebase.database.connection.WebsocketConnection.WSClientTubesock>;
public onClose(): void;
public send(param0: string): void;
public close(): void;
public onLogMessage(param0: string): void;
public onOpen(): void;
public connect(): void;
public onMessage(param0: com.google.firebase.database.tubesock.WebSocketMessage): void;
public onError(param0: com.google.firebase.database.tubesock.WebSocketException): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export module util {
export class RetryHelper {
public static class: java.lang.Class<com.google.firebase.database.connection.util.RetryHelper>;
public setMaxDelay(): void;
public cancel(): void;
public retry(param0: java.lang.Runnable): void;
public signalSuccess(): void;
}
export module RetryHelper {
export class Builder {
public static class: java.lang.Class<com.google.firebase.database.connection.util.RetryHelper.Builder>;
public withRetryExponent(param0: number): com.google.firebase.database.connection.util.RetryHelper.Builder;
public build(): com.google.firebase.database.connection.util.RetryHelper;
public constructor(param0: java.util.concurrent.ScheduledExecutorService, param1: com.google.firebase.database.logging.Logger, param2: string);
public withJitterFactor(param0: number): com.google.firebase.database.connection.util.RetryHelper.Builder;
public withMaxDelay(param0: number): com.google.firebase.database.connection.util.RetryHelper.Builder;
public withMinDelayAfterFailure(param0: number): com.google.firebase.database.connection.util.RetryHelper.Builder;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module connection {
export module util {
export class StringListReader {
public static class: java.lang.Class<com.google.firebase.database.connection.util.StringListReader>;
public constructor();
public skip(param0: number): number;
public close(): void;
public read(): number;
public toString(): string;
public reset(): void;
public mark(param0: number): void;
public markSupported(): boolean;
public read(param0: native.Array<string>, param1: number, param2: number): number;
public freeze(): void;
public ready(): boolean;
public addString(param0: string): void;
public read(param0: java.nio.CharBuffer): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class AuthTokenProvider {
public static class: java.lang.Class<com.google.firebase.database.core.AuthTokenProvider>;
/**
* Constructs a new instance of the com.google.firebase.database.core.AuthTokenProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getToken(param0: boolean, param1: com.google.firebase.database.core.AuthTokenProvider.GetTokenCompletionListener): void;
addTokenChangeListener(param0: java.util.concurrent.ExecutorService, param1: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
removeTokenChangeListener(param0: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
});
public constructor();
public removeTokenChangeListener(param0: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
public getToken(param0: boolean, param1: com.google.firebase.database.core.AuthTokenProvider.GetTokenCompletionListener): void;
public addTokenChangeListener(param0: java.util.concurrent.ExecutorService, param1: com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener): void;
}
export module AuthTokenProvider {
export class GetTokenCompletionListener {
public static class: java.lang.Class<com.google.firebase.database.core.AuthTokenProvider.GetTokenCompletionListener>;
/**
* Constructs a new instance of the com.google.firebase.database.core.AuthTokenProvider$GetTokenCompletionListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onSuccess(param0: string): void;
onError(param0: string): void;
});
public constructor();
public onError(param0: string): void;
public onSuccess(param0: string): void;
}
export class TokenChangeListener {
public static class: java.lang.Class<com.google.firebase.database.core.AuthTokenProvider.TokenChangeListener>;
/**
* Constructs a new instance of the com.google.firebase.database.core.AuthTokenProvider$TokenChangeListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onTokenChange(param0: string): void;
onTokenChange(): void;
});
public constructor();
public onTokenChange(param0: string): void;
public onTokenChange(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ChildEventRegistration extends com.google.firebase.database.core.EventRegistration {
public static class: java.lang.Class<com.google.firebase.database.core.ChildEventRegistration>;
public constructor(param0: com.google.firebase.database.core.Repo, param1: com.google.firebase.database.ChildEventListener, param2: com.google.firebase.database.core.view.QuerySpec);
public respondsTo(param0: com.google.firebase.database.core.view.Event.EventType): boolean;
public fireEvent(param0: com.google.firebase.database.core.view.DataEvent): void;
public constructor();
public isSameListener(param0: com.google.firebase.database.core.EventRegistration): boolean;
public createEvent(param0: com.google.firebase.database.core.view.Change, param1: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.DataEvent;
public clone(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.EventRegistration;
public equals(param0: any): boolean;
public hashCode(): number;
public fireCancelEvent(param0: com.google.firebase.database.DatabaseError): void;
public getQuerySpec(): com.google.firebase.database.core.view.QuerySpec;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class CompoundWrite extends java.lang.Iterable<java.util.Map.Entry<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>> {
public static class: java.lang.Class<com.google.firebase.database.core.CompoundWrite>;
public static fromPathMerge(param0: java.util.Map<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>): com.google.firebase.database.core.CompoundWrite;
public childCompoundWrites(): java.util.Map<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.core.CompoundWrite>;
public hasCompleteWrite(param0: com.google.firebase.database.core.Path): boolean;
public rootWrite(): com.google.firebase.database.snapshot.Node;
public childCompoundWrite(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.CompoundWrite;
public addWrite(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.CompoundWrite;
public equals(param0: any): boolean;
public hashCode(): number;
public iterator(): java.util.Iterator<java.util.Map.Entry<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>>;
public removeWrite(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.CompoundWrite;
public static fromValue(param0: java.util.Map<string,any>): com.google.firebase.database.core.CompoundWrite;
public getValue(param0: boolean): java.util.Map<string,any>;
public toString(): string;
public addWrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.CompoundWrite;
public static fromChildMerge(param0: java.util.Map<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.snapshot.Node>): com.google.firebase.database.core.CompoundWrite;
public static emptyWrite(): com.google.firebase.database.core.CompoundWrite;
public getCompleteNode(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getCompleteChildren(): java.util.List<com.google.firebase.database.snapshot.NamedNode>;
public apply(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public addWrites(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): com.google.firebase.database.core.CompoundWrite;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Constants {
public static class: java.lang.Class<com.google.firebase.database.core.Constants>;
public static DOT_INFO: com.google.firebase.database.snapshot.ChildKey;
public static DOT_INFO_SERVERTIME_OFFSET: com.google.firebase.database.snapshot.ChildKey;
public static DOT_INFO_AUTHENTICATED: com.google.firebase.database.snapshot.ChildKey;
public static DOT_INFO_CONNECTED: com.google.firebase.database.snapshot.ChildKey;
public static WIRE_PROTOCOL_VERSION: string;
public constructor();
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Context {
public static class: java.lang.Class<com.google.firebase.database.core.Context>;
public logger: com.google.firebase.database.logging.Logger;
public eventTarget: com.google.firebase.database.core.EventTarget;
public authTokenProvider: com.google.firebase.database.core.AuthTokenProvider;
public runLoop: com.google.firebase.database.core.RunLoop;
public persistenceKey: string;
public loggedComponents: java.util.List<string>;
public userAgent: string;
public logLevel: com.google.firebase.database.logging.Logger.Level;
public persistenceEnabled: boolean;
public cacheSize: number;
public firebaseApp: com.google.firebase.FirebaseApp;
public getOptDebugLogComponents(): java.util.List<string>;
public getLogger(param0: string): com.google.firebase.database.logging.LogWrapper;
public getPersistenceCacheSizeBytes(): number;
public getRunLoop(): com.google.firebase.database.core.RunLoop;
public constructor();
public isPersistenceEnabled(): boolean;
public isStopped(): boolean;
public getAuthTokenProvider(): com.google.firebase.database.core.AuthTokenProvider;
public getUserAgent(): string;
public getConnectionContext(): com.google.firebase.database.connection.ConnectionContext;
public getLogger(): com.google.firebase.database.logging.Logger;
public getSessionPersistenceKey(): string;
public requireStarted(): void;
public newPersistentConnection(param0: com.google.firebase.database.connection.HostInfo, param1: com.google.firebase.database.connection.PersistentConnection.Delegate): com.google.firebase.database.connection.PersistentConnection;
public getSSLCacheDirectory(): java.io.File;
public getPlatformVersion(): string;
public getEventTarget(): com.google.firebase.database.core.EventTarget;
public assertUnfrozen(): void;
public getLogger(param0: string, param1: string): com.google.firebase.database.logging.LogWrapper;
public isFrozen(): boolean;
public getLogLevel(): com.google.firebase.database.logging.Logger.Level;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class DatabaseConfig extends com.google.firebase.database.core.Context {
public static class: java.lang.Class<com.google.firebase.database.core.DatabaseConfig>;
public constructor();
public setLogger(param0: com.google.firebase.database.logging.Logger): void;
public setSessionPersistenceKey(param0: string): void;
public setPersistenceCacheSizeBytes(param0: number): void;
public setFirebaseApp(param0: com.google.firebase.FirebaseApp): void;
public setAuthTokenProvider(param0: com.google.firebase.database.core.AuthTokenProvider): void;
public setPersistenceEnabled(param0: boolean): void;
public setDebugLogComponents(param0: java.util.List<string>): void;
public setLogLevel(param0: com.google.firebase.database.Logger.Level): void;
public setEventTarget(param0: com.google.firebase.database.core.EventTarget): void;
public setRunLoop(param0: com.google.firebase.database.core.RunLoop): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export abstract class EventRegistration {
public static class: java.lang.Class<com.google.firebase.database.core.EventRegistration>;
public respondsTo(param0: com.google.firebase.database.core.view.Event.EventType): boolean;
public constructor();
public isSameListener(param0: com.google.firebase.database.core.EventRegistration): boolean;
public createEvent(param0: com.google.firebase.database.core.view.Change, param1: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.DataEvent;
public clone(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.EventRegistration;
public setOnZombied(param0: com.google.firebase.database.core.EventRegistrationZombieListener): void;
public isUserInitiated(): boolean;
public fireCancelEvent(param0: com.google.firebase.database.DatabaseError): void;
public getQuerySpec(): com.google.firebase.database.core.view.QuerySpec;
public fireEvent(param0: com.google.firebase.database.core.view.DataEvent): void;
public isZombied(): boolean;
public setIsUserInitiated(param0: boolean): void;
public zombify(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class EventRegistrationZombieListener {
public static class: java.lang.Class<com.google.firebase.database.core.EventRegistrationZombieListener>;
/**
* Constructs a new instance of the com.google.firebase.database.core.EventRegistrationZombieListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onZombied(param0: com.google.firebase.database.core.EventRegistration): void;
});
public constructor();
public onZombied(param0: com.google.firebase.database.core.EventRegistration): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class EventTarget {
public static class: java.lang.Class<com.google.firebase.database.core.EventTarget>;
/**
* Constructs a new instance of the com.google.firebase.database.core.EventTarget interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
postEvent(param0: java.lang.Runnable): void;
shutdown(): void;
restart(): void;
});
public constructor();
public shutdown(): void;
public postEvent(param0: java.lang.Runnable): void;
public restart(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Path extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.Path>;
public child(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.Path;
public wireFormat(): string;
public static getRelative(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.Path): com.google.firebase.database.core.Path;
public equals(param0: any): boolean;
public hashCode(): number;
public constructor(param0: native.Array<com.google.firebase.database.snapshot.ChildKey>);
public toString(): string;
public getParent(): com.google.firebase.database.core.Path;
public getFront(): com.google.firebase.database.snapshot.ChildKey;
public popFront(): com.google.firebase.database.core.Path;
public isEmpty(): boolean;
public contains(param0: com.google.firebase.database.core.Path): boolean;
public static getEmptyPath(): com.google.firebase.database.core.Path;
public constructor(param0: java.util.List<string>);
public size(): number;
public compareTo(param0: com.google.firebase.database.core.Path): number;
public child(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.Path;
public getBack(): com.google.firebase.database.snapshot.ChildKey;
public asList(): java.util.List<string>;
public iterator(): java.util.Iterator<com.google.firebase.database.snapshot.ChildKey>;
public constructor(param0: string);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Platform {
public static class: java.lang.Class<com.google.firebase.database.core.Platform>;
/**
* Constructs a new instance of the com.google.firebase.database.core.Platform interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
newLogger(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.logging.Logger.Level, param2: java.util.List<string>): com.google.firebase.database.logging.Logger;
newEventTarget(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.EventTarget;
newRunLoop(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.RunLoop;
newPersistentConnection(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.connection.ConnectionContext, param2: com.google.firebase.database.connection.HostInfo, param3: com.google.firebase.database.connection.PersistentConnection.Delegate): com.google.firebase.database.connection.PersistentConnection;
getUserAgent(param0: com.google.firebase.database.core.Context): string;
getPlatformVersion(): string;
createPersistenceManager(param0: com.google.firebase.database.core.Context, param1: string): com.google.firebase.database.core.persistence.PersistenceManager;
getSSLCacheDirectory(): java.io.File;
});
public constructor();
public newPersistentConnection(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.connection.ConnectionContext, param2: com.google.firebase.database.connection.HostInfo, param3: com.google.firebase.database.connection.PersistentConnection.Delegate): com.google.firebase.database.connection.PersistentConnection;
public getSSLCacheDirectory(): java.io.File;
public getPlatformVersion(): string;
public newLogger(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.logging.Logger.Level, param2: java.util.List<string>): com.google.firebase.database.logging.Logger;
public getUserAgent(param0: com.google.firebase.database.core.Context): string;
public createPersistenceManager(param0: com.google.firebase.database.core.Context, param1: string): com.google.firebase.database.core.persistence.PersistenceManager;
public newEventTarget(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.EventTarget;
public newRunLoop(param0: com.google.firebase.database.core.Context): com.google.firebase.database.core.RunLoop;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Repo extends com.google.firebase.database.connection.PersistentConnection.Delegate {
public static class: java.lang.Class<com.google.firebase.database.core.Repo>;
public dataUpdateCount: number;
public getDatabase(): com.google.firebase.database.FirebaseDatabase;
public onServerInfoUpdate(param0: com.google.firebase.database.snapshot.ChildKey, param1: any): void;
public onDisconnectCancel(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public onServerInfoUpdate(param0: java.util.Map<string,any>): void;
public postEvent(param0: java.lang.Runnable): void;
public onDataUpdate(param0: java.util.List<string>, param1: any, param2: boolean, param3: java.lang.Long): void;
public getRepoInfo(): com.google.firebase.database.core.RepoInfo;
public getServerTime(): number;
public toString(): string;
public keepSynced(param0: com.google.firebase.database.core.view.QuerySpec, param1: boolean): void;
public onDisconnect(): void;
public addEventCallback(param0: com.google.firebase.database.core.EventRegistration): void;
public setHijackHash(param0: boolean): void;
public updateChildren(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: com.google.firebase.database.DatabaseReference.CompletionListener, param3: java.util.Map<string,any>): void;
public purgeOutstandingWrites(): void;
public onAuthStatus(param0: boolean): void;
public startTransaction(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.Transaction.Handler, param2: boolean): void;
public onDisconnectSetValue(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
public onDisconnectUpdate(param0: com.google.firebase.database.core.Path, param1: java.util.Map<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>, param2: com.google.firebase.database.DatabaseReference.CompletionListener, param3: java.util.Map<string,any>): void;
public onRangeMergeUpdate(param0: java.util.List<string>, param1: java.util.List<com.google.firebase.database.connection.RangeMerge>, param2: java.lang.Long): void;
public scheduleNow(param0: java.lang.Runnable): void;
public onConnect(): void;
public removeEventCallback(param0: com.google.firebase.database.core.EventRegistration): void;
public setValue(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.DatabaseReference.CompletionListener): void;
}
export module Repo {
export class TransactionData extends java.lang.Comparable<com.google.firebase.database.core.Repo.TransactionData> {
public static class: java.lang.Class<com.google.firebase.database.core.Repo.TransactionData>;
public compareTo(param0: com.google.firebase.database.core.Repo.TransactionData): number;
}
export class TransactionStatus {
public static class: java.lang.Class<com.google.firebase.database.core.Repo.TransactionStatus>;
public static INITIALIZING: com.google.firebase.database.core.Repo.TransactionStatus;
public static RUN: com.google.firebase.database.core.Repo.TransactionStatus;
public static SENT: com.google.firebase.database.core.Repo.TransactionStatus;
public static COMPLETED: com.google.firebase.database.core.Repo.TransactionStatus;
public static SENT_NEEDS_ABORT: com.google.firebase.database.core.Repo.TransactionStatus;
public static NEEDS_ABORT: com.google.firebase.database.core.Repo.TransactionStatus;
public static values(): native.Array<com.google.firebase.database.core.Repo.TransactionStatus>;
public static valueOf(param0: string): com.google.firebase.database.core.Repo.TransactionStatus;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class RepoInfo {
public static class: java.lang.Class<com.google.firebase.database.core.RepoInfo>;
public host: string;
public secure: boolean;
public namespace: string;
public internalHost: string;
public constructor();
public toDebugString(): string;
public isSecure(): boolean;
public isDemoHost(): boolean;
public equals(param0: any): boolean;
public hashCode(): number;
public isCustomHost(): boolean;
public toString(): string;
public getConnectionURL(param0: string): java.net.URI;
public isCacheableHost(): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class RepoManager {
public static class: java.lang.Class<com.google.firebase.database.core.RepoManager>;
public static interrupt(param0: com.google.firebase.database.core.Context): void;
public static resume(param0: com.google.firebase.database.core.Context): void;
public constructor();
public static resume(param0: com.google.firebase.database.core.Repo): void;
public static interrupt(param0: com.google.firebase.database.core.Repo): void;
public static getRepo(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.core.RepoInfo): com.google.firebase.database.core.Repo;
public static createRepo(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.core.RepoInfo, param2: com.google.firebase.database.FirebaseDatabase): com.google.firebase.database.core.Repo;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class RunLoop {
public static class: java.lang.Class<com.google.firebase.database.core.RunLoop>;
/**
* Constructs a new instance of the com.google.firebase.database.core.RunLoop interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
scheduleNow(param0: java.lang.Runnable): void;
schedule(param0: java.lang.Runnable, param1: number): java.util.concurrent.ScheduledFuture;
shutdown(): void;
restart(): void;
});
public constructor();
public shutdown(): void;
public scheduleNow(param0: java.lang.Runnable): void;
public restart(): void;
public schedule(param0: java.lang.Runnable, param1: number): java.util.concurrent.ScheduledFuture;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ServerValues {
public static class: java.lang.Class<com.google.firebase.database.core.ServerValues>;
public static NAME_SUBKEY_SERVERVALUE: string;
public static generateServerValues(param0: com.google.firebase.database.core.utilities.Clock): java.util.Map<string,any>;
public static resolveDeferredValueSnapshot(param0: com.google.firebase.database.snapshot.Node, param1: java.util.Map<string,any>): com.google.firebase.database.snapshot.Node;
public constructor();
public static resolveDeferredValueMerge(param0: com.google.firebase.database.core.CompoundWrite, param1: java.util.Map<string,any>): com.google.firebase.database.core.CompoundWrite;
public static resolveDeferredValue(param0: any, param1: java.util.Map<string,any>): any;
public static resolveDeferredValueTree(param0: com.google.firebase.database.core.SparseSnapshotTree, param1: java.util.Map<string,any>): com.google.firebase.database.core.SparseSnapshotTree;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class SnapshotHolder {
public static class: java.lang.Class<com.google.firebase.database.core.SnapshotHolder>;
public getRootNode(): com.google.firebase.database.snapshot.Node;
public constructor(param0: com.google.firebase.database.snapshot.Node);
public getNode(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public update(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class SparseSnapshotTree {
public static class: java.lang.Class<com.google.firebase.database.core.SparseSnapshotTree>;
public constructor();
public remember(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public forget(param0: com.google.firebase.database.core.Path): boolean;
public forEachChild(param0: com.google.firebase.database.core.SparseSnapshotTree.SparseSnapshotChildVisitor): void;
public forEachTree(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.SparseSnapshotTree.SparseSnapshotTreeVisitor): void;
}
export module SparseSnapshotTree {
export class SparseSnapshotChildVisitor {
public static class: java.lang.Class<com.google.firebase.database.core.SparseSnapshotTree.SparseSnapshotChildVisitor>;
/**
* Constructs a new instance of the com.google.firebase.database.core.SparseSnapshotTree$SparseSnapshotChildVisitor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
visitChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.core.SparseSnapshotTree): void;
});
public constructor();
public visitChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.core.SparseSnapshotTree): void;
}
export class SparseSnapshotTreeVisitor {
public static class: java.lang.Class<com.google.firebase.database.core.SparseSnapshotTree.SparseSnapshotTreeVisitor>;
/**
* Constructs a new instance of the com.google.firebase.database.core.SparseSnapshotTree$SparseSnapshotTreeVisitor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
visitTree(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
});
public constructor();
public visitTree(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class SyncPoint {
public static class: java.lang.Class<com.google.firebase.database.core.SyncPoint>;
public hasCompleteView(): boolean;
public viewForQuery(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.View;
public viewExistsForQuery(param0: com.google.firebase.database.core.view.QuerySpec): boolean;
public addEventRegistration(param0: com.google.firebase.database.core.EventRegistration, param1: com.google.firebase.database.core.WriteTreeRef, param2: com.google.firebase.database.core.view.CacheNode): java.util.List<com.google.firebase.database.core.view.DataEvent>;
public getCompleteView(): com.google.firebase.database.core.view.View;
public removeEventRegistration(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.EventRegistration, param2: com.google.firebase.database.DatabaseError): com.google.firebase.database.core.utilities.Pair<java.util.List<com.google.firebase.database.core.view.QuerySpec>,java.util.List<com.google.firebase.database.core.view.Event>>;
public constructor(param0: com.google.firebase.database.core.persistence.PersistenceManager);
public isEmpty(): boolean;
public applyOperation(param0: com.google.firebase.database.core.operation.Operation, param1: com.google.firebase.database.core.WriteTreeRef, param2: com.google.firebase.database.snapshot.Node): java.util.List<com.google.firebase.database.core.view.DataEvent>;
public getCompleteServerCache(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public getQueryViews(): java.util.List<com.google.firebase.database.core.view.View>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class SyncTree {
public static class: java.lang.Class<com.google.firebase.database.core.SyncTree>;
public applyTaggedQueryMerge(param0: com.google.firebase.database.core.Path, param1: java.util.Map<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>, param2: com.google.firebase.database.core.Tag): java.util.List<any>;
public addEventRegistration(param0: com.google.firebase.database.core.EventRegistration): java.util.List<any>;
public calcCompleteEventCache(param0: com.google.firebase.database.core.Path, param1: java.util.List<java.lang.Long>): com.google.firebase.database.snapshot.Node;
public applyTaggedQueryOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.core.Tag): java.util.List<any>;
public applyServerOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): java.util.List<any>;
public applyUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: com.google.firebase.database.core.CompoundWrite, param3: number, param4: boolean): java.util.List<any>;
public removeEventRegistration(param0: com.google.firebase.database.core.EventRegistration): java.util.List<com.google.firebase.database.core.view.Event>;
public constructor(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.core.persistence.PersistenceManager, param2: com.google.firebase.database.core.SyncTree.ListenProvider);
public applyListenComplete(param0: com.google.firebase.database.core.Path): java.util.List<any>;
public keepSynced(param0: com.google.firebase.database.core.view.QuerySpec, param1: boolean): void;
public applyUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.Node, param3: number, param4: boolean, param5: boolean): java.util.List<any>;
public ackUserWrite(param0: number, param1: boolean, param2: boolean, param3: com.google.firebase.database.core.utilities.Clock): java.util.List<any>;
public applyTaggedRangeMerges(param0: com.google.firebase.database.core.Path, param1: java.util.List<com.google.firebase.database.snapshot.RangeMerge>, param2: com.google.firebase.database.core.Tag): java.util.List<any>;
public isEmpty(): boolean;
public removeAllWrites(): java.util.List<any>;
public applyServerMerge(param0: com.google.firebase.database.core.Path, param1: java.util.Map<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>): java.util.List<any>;
public applyServerRangeMerges(param0: com.google.firebase.database.core.Path, param1: java.util.List<com.google.firebase.database.snapshot.RangeMerge>): java.util.List<any>;
public removeAllEventRegistrations(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.DatabaseError): java.util.List<com.google.firebase.database.core.view.Event>;
public applyTaggedListenComplete(param0: com.google.firebase.database.core.Tag): java.util.List<any>;
}
export module SyncTree {
export class CompletionListener {
public static class: java.lang.Class<com.google.firebase.database.core.SyncTree.CompletionListener>;
/**
* Constructs a new instance of the com.google.firebase.database.core.SyncTree$CompletionListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onListenComplete(param0: com.google.firebase.database.DatabaseError): java.util.List<any>;
});
public constructor();
public onListenComplete(param0: com.google.firebase.database.DatabaseError): java.util.List<any>;
}
export class KeepSyncedEventRegistration extends com.google.firebase.database.core.EventRegistration {
public static class: java.lang.Class<com.google.firebase.database.core.SyncTree.KeepSyncedEventRegistration>;
public constructor();
public fireCancelEvent(param0: com.google.firebase.database.DatabaseError): void;
public getQuerySpec(): com.google.firebase.database.core.view.QuerySpec;
public createEvent(param0: com.google.firebase.database.core.view.Change, param1: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.DataEvent;
public hashCode(): number;
public fireEvent(param0: com.google.firebase.database.core.view.DataEvent): void;
public isSameListener(param0: com.google.firebase.database.core.EventRegistration): boolean;
public constructor(param0: com.google.firebase.database.core.view.QuerySpec);
public clone(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.EventRegistration;
public equals(param0: any): boolean;
public respondsTo(param0: com.google.firebase.database.core.view.Event.EventType): boolean;
}
export class ListenContainer implements com.google.firebase.database.connection.ListenHashProvider, com.google.firebase.database.core.SyncTree.CompletionListener {
public static class: java.lang.Class<com.google.firebase.database.core.SyncTree.ListenContainer>;
public onListenComplete(param0: com.google.firebase.database.DatabaseError): java.util.List<any>;
public constructor(param0: com.google.firebase.database.core.SyncTree, param1: com.google.firebase.database.core.view.View);
public getSimpleHash(): string;
public getCompoundHash(): com.google.firebase.database.connection.CompoundHash;
public shouldIncludeCompoundHash(): boolean;
}
export class ListenProvider {
public static class: java.lang.Class<com.google.firebase.database.core.SyncTree.ListenProvider>;
/**
* Constructs a new instance of the com.google.firebase.database.core.SyncTree$ListenProvider interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
startListening(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.Tag, param2: com.google.firebase.database.connection.ListenHashProvider, param3: com.google.firebase.database.core.SyncTree.CompletionListener): void;
stopListening(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.Tag): void;
});
public constructor();
public stopListening(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.Tag): void;
public startListening(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.Tag, param2: com.google.firebase.database.connection.ListenHashProvider, param3: com.google.firebase.database.core.SyncTree.CompletionListener): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class Tag {
public static class: java.lang.Class<com.google.firebase.database.core.Tag>;
public constructor(param0: number);
public equals(param0: any): boolean;
public hashCode(): number;
public getTagNumber(): number;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ThreadBackgroundExecutor {
public static class: java.lang.Class<com.google.firebase.database.core.ThreadBackgroundExecutor>;
public constructor();
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ThreadInitializer {
public static class: java.lang.Class<com.google.firebase.database.core.ThreadInitializer>;
/**
* Constructs a new instance of the com.google.firebase.database.core.ThreadInitializer interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setName(param0: java.lang.Thread, param1: string): void;
setDaemon(param0: java.lang.Thread, param1: boolean): void;
setUncaughtExceptionHandler(param0: java.lang.Thread, param1: java.lang.Thread.UncaughtExceptionHandler): void;
<clinit>(): void;
});
public constructor();
public static defaultInstance: com.google.firebase.database.core.ThreadInitializer;
public setName(param0: java.lang.Thread, param1: string): void;
public setUncaughtExceptionHandler(param0: java.lang.Thread, param1: java.lang.Thread.UncaughtExceptionHandler): void;
public setDaemon(param0: java.lang.Thread, param1: boolean): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ThreadPoolEventTarget extends com.google.firebase.database.core.EventTarget {
public static class: java.lang.Class<com.google.firebase.database.core.ThreadPoolEventTarget>;
public shutdown(): void;
public constructor(param0: java.util.concurrent.ThreadFactory, param1: com.google.firebase.database.core.ThreadInitializer);
public postEvent(param0: java.lang.Runnable): void;
public restart(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class UserWriteRecord {
public static class: java.lang.Class<com.google.firebase.database.core.UserWriteRecord>;
public constructor(param0: number, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.snapshot.Node, param3: boolean);
public isMerge(): boolean;
public constructor(param0: number, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.core.CompoundWrite);
public isVisible(): boolean;
public getMerge(): com.google.firebase.database.core.CompoundWrite;
public isOverwrite(): boolean;
public equals(param0: any): boolean;
public hashCode(): number;
public getPath(): com.google.firebase.database.core.Path;
public getOverwrite(): com.google.firebase.database.snapshot.Node;
public getWriteId(): number;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ValidationPath {
public static class: java.lang.Class<com.google.firebase.database.core.ValidationPath>;
public static MAX_PATH_LENGTH_BYTES: number;
public static MAX_PATH_DEPTH: number;
public static validateWithObject(param0: com.google.firebase.database.core.Path, param1: any): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ValueEventRegistration extends com.google.firebase.database.core.EventRegistration {
public static class: java.lang.Class<com.google.firebase.database.core.ValueEventRegistration>;
public respondsTo(param0: com.google.firebase.database.core.view.Event.EventType): boolean;
public fireEvent(param0: com.google.firebase.database.core.view.DataEvent): void;
public constructor();
public constructor(param0: com.google.firebase.database.core.Repo, param1: com.google.firebase.database.ValueEventListener, param2: com.google.firebase.database.core.view.QuerySpec);
public isSameListener(param0: com.google.firebase.database.core.EventRegistration): boolean;
public createEvent(param0: com.google.firebase.database.core.view.Change, param1: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.DataEvent;
public clone(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.EventRegistration;
public equals(param0: any): boolean;
public hashCode(): number;
public fireCancelEvent(param0: com.google.firebase.database.DatabaseError): void;
public getQuerySpec(): com.google.firebase.database.core.view.QuerySpec;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class WriteTree {
public static class: java.lang.Class<com.google.firebase.database.core.WriteTree>;
public childWrites(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.WriteTreeRef;
public constructor();
public removeWrite(param0: number): boolean;
public getCompleteWriteData(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public calcEventCacheAfterServerOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public calcCompleteChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.core.view.CacheNode): com.google.firebase.database.snapshot.Node;
public calcCompleteEventCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: java.util.List<java.lang.Long>, param3: boolean): com.google.firebase.database.snapshot.Node;
public calcNextNodeAfterPost(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.NamedNode, param3: boolean, param4: com.google.firebase.database.snapshot.Index): com.google.firebase.database.snapshot.NamedNode;
public calcCompleteEventCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public purgeAllWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public calcCompleteEventCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: java.util.List<java.lang.Long>): com.google.firebase.database.snapshot.Node;
public getWrite(param0: number): com.google.firebase.database.core.UserWriteRecord;
public addMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: java.lang.Long): void;
public shadowingWrite(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public calcCompleteEventChildren(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public addOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: java.lang.Long, param3: boolean): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class WriteTreeRef {
public static class: java.lang.Class<com.google.firebase.database.core.WriteTreeRef>;
public calcNextNodeAfterPost(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean, param3: com.google.firebase.database.snapshot.Index): com.google.firebase.database.snapshot.NamedNode;
public calcCompleteEventCache(param0: com.google.firebase.database.snapshot.Node, param1: java.util.List<java.lang.Long>, param2: boolean): com.google.firebase.database.snapshot.Node;
public constructor(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.WriteTree);
public calcCompleteEventChildren(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public calcEventCacheAfterServerOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public calcCompleteEventCache(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public shadowingWrite(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public calcCompleteEventCache(param0: com.google.firebase.database.snapshot.Node, param1: java.util.List<java.lang.Long>): com.google.firebase.database.snapshot.Node;
public child(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.WriteTreeRef;
public calcCompleteChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.core.view.CacheNode): com.google.firebase.database.snapshot.Node;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export class ZombieEventManager extends com.google.firebase.database.core.EventRegistrationZombieListener {
public static class: java.lang.Class<com.google.firebase.database.core.ZombieEventManager>;
public recordEventRegistration(param0: com.google.firebase.database.core.EventRegistration): void;
public static getInstance(): com.google.firebase.database.core.ZombieEventManager;
public zombifyForRemove(param0: com.google.firebase.database.core.EventRegistration): void;
public onZombied(param0: com.google.firebase.database.core.EventRegistration): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export class AckUserWrite extends com.google.firebase.database.core.operation.Operation {
public static class: java.lang.Class<com.google.firebase.database.core.operation.AckUserWrite>;
public operationForChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.operation.Operation;
public constructor(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.utilities.ImmutableTree<java.lang.Boolean>, param2: boolean);
public isRevert(): boolean;
public toString(): string;
public constructor(param0: com.google.firebase.database.core.operation.Operation.OperationType, param1: com.google.firebase.database.core.operation.OperationSource, param2: com.google.firebase.database.core.Path);
public getAffectedTree(): com.google.firebase.database.core.utilities.ImmutableTree<java.lang.Boolean>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export class ListenComplete extends com.google.firebase.database.core.operation.Operation {
public static class: java.lang.Class<com.google.firebase.database.core.operation.ListenComplete>;
public operationForChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.operation.Operation;
public toString(): string;
public constructor(param0: com.google.firebase.database.core.operation.Operation.OperationType, param1: com.google.firebase.database.core.operation.OperationSource, param2: com.google.firebase.database.core.Path);
public constructor(param0: com.google.firebase.database.core.operation.OperationSource, param1: com.google.firebase.database.core.Path);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export class Merge extends com.google.firebase.database.core.operation.Operation {
public static class: java.lang.Class<com.google.firebase.database.core.operation.Merge>;
public operationForChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.operation.Operation;
public toString(): string;
public constructor(param0: com.google.firebase.database.core.operation.OperationSource, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.core.CompoundWrite);
public constructor(param0: com.google.firebase.database.core.operation.Operation.OperationType, param1: com.google.firebase.database.core.operation.OperationSource, param2: com.google.firebase.database.core.Path);
public getChildren(): com.google.firebase.database.core.CompoundWrite;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export abstract class Operation {
public static class: java.lang.Class<com.google.firebase.database.core.operation.Operation>;
public type: com.google.firebase.database.core.operation.Operation.OperationType;
public source: com.google.firebase.database.core.operation.OperationSource;
public path: com.google.firebase.database.core.Path;
public operationForChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.operation.Operation;
public getPath(): com.google.firebase.database.core.Path;
public constructor(param0: com.google.firebase.database.core.operation.Operation.OperationType, param1: com.google.firebase.database.core.operation.OperationSource, param2: com.google.firebase.database.core.Path);
public getSource(): com.google.firebase.database.core.operation.OperationSource;
public getType(): com.google.firebase.database.core.operation.Operation.OperationType;
}
export module Operation {
export class OperationType {
public static class: java.lang.Class<com.google.firebase.database.core.operation.Operation.OperationType>;
public static Overwrite: com.google.firebase.database.core.operation.Operation.OperationType;
public static Merge: com.google.firebase.database.core.operation.Operation.OperationType;
public static AckUserWrite: com.google.firebase.database.core.operation.Operation.OperationType;
public static ListenComplete: com.google.firebase.database.core.operation.Operation.OperationType;
public static values(): native.Array<com.google.firebase.database.core.operation.Operation.OperationType>;
public static valueOf(param0: string): com.google.firebase.database.core.operation.Operation.OperationType;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export class OperationSource {
public static class: java.lang.Class<com.google.firebase.database.core.operation.OperationSource>;
public static USER: com.google.firebase.database.core.operation.OperationSource;
public static SERVER: com.google.firebase.database.core.operation.OperationSource;
public constructor(param0: com.google.firebase.database.core.operation.OperationSource.Source, param1: com.google.firebase.database.core.view.QueryParams, param2: boolean);
public isFromUser(): boolean;
public getQueryParams(): com.google.firebase.database.core.view.QueryParams;
public toString(): string;
public static forServerTaggedQuery(param0: com.google.firebase.database.core.view.QueryParams): com.google.firebase.database.core.operation.OperationSource;
public isTagged(): boolean;
public isFromServer(): boolean;
}
export module OperationSource {
export class Source {
public static class: java.lang.Class<com.google.firebase.database.core.operation.OperationSource.Source>;
public static User: com.google.firebase.database.core.operation.OperationSource.Source;
public static Server: com.google.firebase.database.core.operation.OperationSource.Source;
public static values(): native.Array<com.google.firebase.database.core.operation.OperationSource.Source>;
public static valueOf(param0: string): com.google.firebase.database.core.operation.OperationSource.Source;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module operation {
export class Overwrite extends com.google.firebase.database.core.operation.Operation {
public static class: java.lang.Class<com.google.firebase.database.core.operation.Overwrite>;
public operationForChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.operation.Operation;
public constructor(param0: com.google.firebase.database.core.operation.OperationSource, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.snapshot.Node);
public toString(): string;
public getSnapshot(): com.google.firebase.database.snapshot.Node;
public constructor(param0: com.google.firebase.database.core.operation.Operation.OperationType, param1: com.google.firebase.database.core.operation.OperationSource, param2: com.google.firebase.database.core.Path);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class CachePolicy {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.CachePolicy>;
/**
* Constructs a new instance of the com.google.firebase.database.core.persistence.CachePolicy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
shouldPrune(param0: number, param1: number): boolean;
shouldCheckCacheSize(param0: number): boolean;
getPercentOfQueriesToPruneAtOnce(): number;
getMaxNumberOfQueriesToKeep(): number;
<clinit>(): void;
});
public constructor();
public static NONE: com.google.firebase.database.core.persistence.CachePolicy;
public shouldCheckCacheSize(param0: number): boolean;
public shouldPrune(param0: number, param1: number): boolean;
public getMaxNumberOfQueriesToKeep(): number;
public getPercentOfQueriesToPruneAtOnce(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class DefaultPersistenceManager extends com.google.firebase.database.core.persistence.PersistenceManager {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.DefaultPersistenceManager>;
public saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
public setQueryComplete(param0: com.google.firebase.database.core.view.QuerySpec): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public updateServerCache(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.snapshot.Node): void;
public setQueryActive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
public constructor(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.core.persistence.PersistenceStorageEngine, param2: com.google.firebase.database.core.persistence.CachePolicy);
public runInTransaction(param0: java.util.concurrent.Callable): any;
public removeAllUserWrites(): void;
public updateServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public setQueryInactive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public serverCache(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.CacheNode;
public constructor(param0: com.google.firebase.database.core.Context, param1: com.google.firebase.database.core.persistence.PersistenceStorageEngine, param2: com.google.firebase.database.core.persistence.CachePolicy, param3: com.google.firebase.database.core.utilities.Clock);
public setTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public removeUserWrite(param0: number): void;
public updateTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class LRUCachePolicy extends com.google.firebase.database.core.persistence.CachePolicy {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.LRUCachePolicy>;
public maxSizeBytes: number;
public shouldCheckCacheSize(param0: number): boolean;
public shouldPrune(param0: number, param1: number): boolean;
public getMaxNumberOfQueriesToKeep(): number;
public getPercentOfQueriesToPruneAtOnce(): number;
public constructor(param0: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class NoopPersistenceManager extends com.google.firebase.database.core.persistence.PersistenceManager {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.NoopPersistenceManager>;
public constructor();
public saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
public setQueryComplete(param0: com.google.firebase.database.core.view.QuerySpec): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public updateServerCache(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.snapshot.Node): void;
public setQueryActive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
public runInTransaction(param0: java.util.concurrent.Callable): any;
public removeAllUserWrites(): void;
public updateServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public setQueryInactive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public serverCache(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.CacheNode;
public setTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public removeUserWrite(param0: number): void;
public updateTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class PersistenceManager {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.PersistenceManager>;
/**
* Constructs a new instance of the com.google.firebase.database.core.persistence.PersistenceManager interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
removeUserWrite(param0: number): void;
removeAllUserWrites(): void;
applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
serverCache(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.CacheNode;
updateServerCache(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.snapshot.Node): void;
updateServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
setQueryActive(param0: com.google.firebase.database.core.view.QuerySpec): void;
setQueryInactive(param0: com.google.firebase.database.core.view.QuerySpec): void;
setQueryComplete(param0: com.google.firebase.database.core.view.QuerySpec): void;
setTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
updateTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
runInTransaction(param0: java.util.concurrent.Callable): any;
});
public constructor();
public saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
public setQueryComplete(param0: com.google.firebase.database.core.view.QuerySpec): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public applyUserWriteToServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public updateServerCache(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.snapshot.Node): void;
public setQueryActive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
public runInTransaction(param0: java.util.concurrent.Callable): any;
public removeAllUserWrites(): void;
public updateServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public setQueryInactive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public serverCache(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.view.CacheNode;
public setTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public removeUserWrite(param0: number): void;
public updateTrackedQueryKeys(param0: com.google.firebase.database.core.view.QuerySpec, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class PersistenceStorageEngine {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.PersistenceStorageEngine>;
/**
* Constructs a new instance of the com.google.firebase.database.core.persistence.PersistenceStorageEngine interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
removeUserWrite(param0: number): void;
loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
removeAllUserWrites(): void;
serverCache(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
overwriteServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
serverCacheEstimatedSizeInBytes(): number;
saveTrackedQuery(param0: com.google.firebase.database.core.persistence.TrackedQuery): void;
deleteTrackedQuery(param0: number): void;
loadTrackedQueries(): java.util.List<com.google.firebase.database.core.persistence.TrackedQuery>;
resetPreviouslyActiveTrackedQueries(param0: number): void;
saveTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
updateTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
loadTrackedQueryKeys(param0: number): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
loadTrackedQueryKeys(param0: java.util.Set<java.lang.Long>): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
pruneCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.persistence.PruneForest): void;
beginTransaction(): void;
endTransaction(): void;
setTransactionSuccessful(): void;
close(): void;
});
public constructor();
public close(): void;
public saveUserMerge(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite, param2: number): void;
public pruneCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.persistence.PruneForest): void;
public mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public resetPreviouslyActiveTrackedQueries(param0: number): void;
public loadUserWrites(): java.util.List<com.google.firebase.database.core.UserWriteRecord>;
public saveUserOverwrite(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node, param2: number): void;
public saveTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public serverCache(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public mergeIntoServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.CompoundWrite): void;
public loadTrackedQueryKeys(param0: number): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
public endTransaction(): void;
public removeAllUserWrites(): void;
public beginTransaction(): void;
public overwriteServerCache(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): void;
public updateTrackedQueryKeys(param0: number, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>, param2: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): void;
public loadTrackedQueries(): java.util.List<com.google.firebase.database.core.persistence.TrackedQuery>;
public loadTrackedQueryKeys(param0: java.util.Set<java.lang.Long>): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
public deleteTrackedQuery(param0: number): void;
public removeUserWrite(param0: number): void;
public serverCacheEstimatedSizeInBytes(): number;
public saveTrackedQuery(param0: com.google.firebase.database.core.persistence.TrackedQuery): void;
public setTransactionSuccessful(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class PruneForest {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.PruneForest>;
public constructor();
public hashCode(): number;
public child(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.persistence.PruneForest;
public prunesAnything(): boolean;
public shouldPruneUnkeptDescendants(param0: com.google.firebase.database.core.Path): boolean;
public child(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.persistence.PruneForest;
public keepAll(param0: com.google.firebase.database.core.Path, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): com.google.firebase.database.core.persistence.PruneForest;
public toString(): string;
public affectsPath(param0: com.google.firebase.database.core.Path): boolean;
public foldKeptNodes(param0: any, param1: com.google.firebase.database.core.utilities.ImmutableTree.TreeVisitor<any,any>): any;
public prune(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.persistence.PruneForest;
public shouldKeep(param0: com.google.firebase.database.core.Path): boolean;
public pruneAll(param0: com.google.firebase.database.core.Path, param1: java.util.Set<com.google.firebase.database.snapshot.ChildKey>): com.google.firebase.database.core.persistence.PruneForest;
public equals(param0: any): boolean;
public keep(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.persistence.PruneForest;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class TrackedQuery {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.TrackedQuery>;
public id: number;
public querySpec: com.google.firebase.database.core.view.QuerySpec;
public lastUse: number;
public complete: boolean;
public active: boolean;
public setComplete(): com.google.firebase.database.core.persistence.TrackedQuery;
public setActiveState(param0: boolean): com.google.firebase.database.core.persistence.TrackedQuery;
public hashCode(): number;
public toString(): string;
public constructor(param0: number, param1: com.google.firebase.database.core.view.QuerySpec, param2: number, param3: boolean, param4: boolean);
public updateLastUse(param0: number): com.google.firebase.database.core.persistence.TrackedQuery;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module persistence {
export class TrackedQueryManager {
public static class: java.lang.Class<com.google.firebase.database.core.persistence.TrackedQueryManager>;
public ensureCompleteTrackedQuery(param0: com.google.firebase.database.core.Path): void;
public constructor(param0: com.google.firebase.database.core.persistence.PersistenceStorageEngine, param1: com.google.firebase.database.logging.LogWrapper, param2: com.google.firebase.database.core.utilities.Clock);
public setQueryCompleteIfExists(param0: com.google.firebase.database.core.view.QuerySpec): void;
public setQueriesComplete(param0: com.google.firebase.database.core.Path): void;
public setQueryActive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public getKnownCompleteChildren(param0: com.google.firebase.database.core.Path): java.util.Set<com.google.firebase.database.snapshot.ChildKey>;
public setQueryInactive(param0: com.google.firebase.database.core.view.QuerySpec): void;
public hasActiveDefaultQuery(param0: com.google.firebase.database.core.Path): boolean;
public isQueryComplete(param0: com.google.firebase.database.core.view.QuerySpec): boolean;
public countOfPrunableQueries(): number;
public pruneOldQueries(param0: com.google.firebase.database.core.persistence.CachePolicy): com.google.firebase.database.core.persistence.PruneForest;
public removeTrackedQuery(param0: com.google.firebase.database.core.view.QuerySpec): void;
public findTrackedQuery(param0: com.google.firebase.database.core.view.QuerySpec): com.google.firebase.database.core.persistence.TrackedQuery;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Clock {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Clock>;
/**
* Constructs a new instance of the com.google.firebase.database.core.utilities.Clock interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
millis(): number;
});
public constructor();
public millis(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class DefaultClock extends com.google.firebase.database.core.utilities.Clock {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.DefaultClock>;
public constructor();
public millis(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export abstract class DefaultRunLoop extends com.google.firebase.database.core.RunLoop {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.DefaultRunLoop>;
public constructor();
public schedule(param0: java.lang.Runnable, param1: number): java.util.concurrent.ScheduledFuture;
public getThreadFactory(): java.util.concurrent.ThreadFactory;
public getThreadInitializer(): com.google.firebase.database.core.ThreadInitializer;
public static messageForException(param0: java.lang.Throwable): string;
public scheduleNow(param0: java.lang.Runnable): void;
public handleException(param0: java.lang.Throwable): void;
public getExecutorService(): java.util.concurrent.ScheduledExecutorService;
public restart(): void;
public shutdown(): void;
}
export module DefaultRunLoop {
export class FirebaseThreadFactory {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.DefaultRunLoop.FirebaseThreadFactory>;
public newThread(param0: java.lang.Runnable): java.lang.Thread;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class ImmutableTree<T> extends java.lang.Iterable<java.util.Map.Entry<com.google.firebase.database.core.Path,any>> {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.ImmutableTree<any>>;
public getValue(): any;
public findRootMostPathWithValue(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.Path;
public hashCode(): number;
public leafMostValue(param0: com.google.firebase.database.core.Path): any;
public toString(): string;
public getChildren(): com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.core.utilities.ImmutableTree<any>>;
public fold(param0: any, param1: com.google.firebase.database.core.utilities.ImmutableTree.TreeVisitor<any,any>): any;
public values(): java.util.Collection<any>;
public static emptyInstance(): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public foreach(param0: com.google.firebase.database.core.utilities.ImmutableTree.TreeVisitor<any,java.lang.Void>): void;
public findRootMostMatchingPath(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.utilities.Predicate<any>): com.google.firebase.database.core.Path;
public constructor(param0: any, param1: com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.core.utilities.ImmutableTree<any>>);
public get(param0: com.google.firebase.database.core.Path): any;
public getChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public iterator(): java.util.Iterator<java.util.Map.Entry<com.google.firebase.database.core.Path,any>>;
public containsMatchingValue(param0: com.google.firebase.database.core.utilities.Predicate<any>): boolean;
public leafMostValueMatching(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.utilities.Predicate<any>): any;
public remove(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public set(param0: com.google.firebase.database.core.Path, param1: any): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public subtree(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public setTree(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.utilities.ImmutableTree<any>): com.google.firebase.database.core.utilities.ImmutableTree<any>;
public rootMostValue(param0: com.google.firebase.database.core.Path): any;
public isEmpty(): boolean;
public equals(param0: any): boolean;
public constructor(param0: any);
public rootMostValueMatching(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.utilities.Predicate<any>): any;
}
export module ImmutableTree {
export class TreeVisitor<T, R> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.ImmutableTree.TreeVisitor<any,any>>;
/**
* Constructs a new instance of the com.google.firebase.database.core.utilities.ImmutableTree$TreeVisitor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onNodeValue(param0: com.google.firebase.database.core.Path, param1: T, param2: R): R;
});
public constructor();
public onNodeValue(param0: com.google.firebase.database.core.Path, param1: T, param2: R): R;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class NodeSizeEstimator {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.NodeSizeEstimator>;
public constructor();
public static estimateSerializedNodeSize(param0: com.google.firebase.database.snapshot.Node): number;
public static nodeCount(param0: com.google.firebase.database.snapshot.Node): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class OffsetClock extends com.google.firebase.database.core.utilities.Clock {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.OffsetClock>;
public setOffset(param0: number): void;
public constructor(param0: com.google.firebase.database.core.utilities.Clock, param1: number);
public millis(): number;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Pair<T, U> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Pair<any,any>>;
public constructor(param0: T, param1: U);
public hashCode(): number;
public toString(): string;
public getSecond(): U;
public equals(param0: any): boolean;
public getFirst(): T;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class ParsedUrl {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.ParsedUrl>;
public repoInfo: com.google.firebase.database.core.RepoInfo;
public path: com.google.firebase.database.core.Path;
public constructor();
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Predicate<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Predicate<any>>;
/**
* Constructs a new instance of the com.google.firebase.database.core.utilities.Predicate<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
evaluate(param0: T): boolean;
<clinit>(): void;
});
public constructor();
public static TRUE: com.google.firebase.database.core.utilities.Predicate<any>;
public evaluate(param0: T): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class PushIdGenerator {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.PushIdGenerator>;
public constructor();
public static generatePushChildName(param0: number): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Tree<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Tree<any>>;
public constructor();
public setValue(param0: T): void;
public constructor(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.core.utilities.Tree<T>, param2: com.google.firebase.database.core.utilities.TreeNode<T>);
public toString(): string;
public forEachDescendant(param0: com.google.firebase.database.core.utilities.Tree.TreeVisitor<T>): void;
public forEachAncestor(param0: com.google.firebase.database.core.utilities.Tree.TreeFilter<T>, param1: boolean): boolean;
public lastNodeOnPath(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.utilities.TreeNode<T>;
public getParent(): com.google.firebase.database.core.utilities.Tree<T>;
public forEachDescendant(param0: com.google.firebase.database.core.utilities.Tree.TreeVisitor<T>, param1: boolean, param2: boolean): void;
public subTree(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.utilities.Tree<T>;
public getValue(): T;
public getPath(): com.google.firebase.database.core.Path;
public forEachDescendant(param0: com.google.firebase.database.core.utilities.Tree.TreeVisitor<T>, param1: boolean): void;
public getName(): com.google.firebase.database.snapshot.ChildKey;
public hasChildren(): boolean;
public isEmpty(): boolean;
public forEachAncestor(param0: com.google.firebase.database.core.utilities.Tree.TreeFilter<T>): boolean;
public forEachChild(param0: com.google.firebase.database.core.utilities.Tree.TreeVisitor<T>): void;
}
export module Tree {
export class TreeFilter<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Tree.TreeFilter<any>>;
/**
* Constructs a new instance of the com.google.firebase.database.core.utilities.Tree$TreeFilter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
filterTreeNode(param0: com.google.firebase.database.core.utilities.Tree<T>): boolean;
});
public constructor();
public filterTreeNode(param0: com.google.firebase.database.core.utilities.Tree<T>): boolean;
}
export class TreeVisitor<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Tree.TreeVisitor<any>>;
/**
* Constructs a new instance of the com.google.firebase.database.core.utilities.Tree$TreeVisitor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
visitTree(param0: com.google.firebase.database.core.utilities.Tree<T>): void;
});
public constructor();
public visitTree(param0: com.google.firebase.database.core.utilities.Tree<T>): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class TreeNode<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.TreeNode<any>>;
public children: java.util.Map<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.core.utilities.TreeNode<T>>;
public value: T;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Utilities {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Utilities>;
public constructor();
public static hardAssert(param0: boolean): void;
public static wrapOnComplete(param0: com.google.firebase.database.DatabaseReference.CompletionListener): com.google.firebase.database.core.utilities.Pair<com.google.android.gms.tasks.Task<java.lang.Void>,com.google.firebase.database.DatabaseReference.CompletionListener>;
public static castOrNull(param0: any, param1: java.lang.Class): any;
public static sha1HexDigest(param0: string): string;
public static tryParseInt(param0: string): java.lang.Integer;
public static hardAssert(param0: boolean, param1: string): void;
public static stringHashV2Representation(param0: string): string;
public static doubleToHashString(param0: number): string;
public static compareInts(param0: number, param1: number): number;
public static compareLongs(param0: number, param1: number): number;
public static parseUrl(param0: string): com.google.firebase.database.core.utilities.ParsedUrl;
public static getOrNull(param0: any, param1: string, param2: java.lang.Class): any;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export class Validation {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.Validation>;
public constructor();
public static validateWritablePath(param0: com.google.firebase.database.core.Path): void;
public static validateNullableKey(param0: string): void;
public static validateWritableObject(param0: any): void;
public static validatePathString(param0: string): void;
public static validateWritableKey(param0: string): void;
public static parseAndValidateUpdate(param0: com.google.firebase.database.core.Path, param1: java.util.Map<string,any>): java.util.Map<com.google.firebase.database.core.Path,com.google.firebase.database.snapshot.Node>;
public static validateRootPathString(param0: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export module encoding {
export class CustomClassMapper {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.encoding.CustomClassMapper>;
public static convertToPlainJavaTypes(param0: java.util.Map<string,any>): java.util.Map<string,any>;
public static convertToCustomClass(param0: any, param1: com.google.firebase.database.GenericTypeIndicator<any>): any;
public constructor();
public static convertToCustomClass(param0: any, param1: java.lang.Class): any;
public static convertToPlainJavaTypes(param0: any): any;
}
export module CustomClassMapper {
export class BeanMapper<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.encoding.CustomClassMapper.BeanMapper<any>>;
public deserialize(param0: java.util.Map<string,any>, param1: java.util.Map<java.lang.reflect.TypeVariable<java.lang.Class<T>>,java.lang.reflect.Type>): T;
public constructor(param0: java.lang.Class<T>);
public serialize(param0: T): java.util.Map<string,any>;
public deserialize(param0: java.util.Map<string,any>): T;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export module tuple {
export class NameAndPriority extends java.lang.Comparable<com.google.firebase.database.core.utilities.tuple.NameAndPriority> {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.tuple.NameAndPriority>;
public getPriority(): com.google.firebase.database.snapshot.Node;
public compareTo(param0: com.google.firebase.database.core.utilities.tuple.NameAndPriority): number;
public constructor(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node);
public getName(): com.google.firebase.database.snapshot.ChildKey;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export module tuple {
export class NodeAndPath {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.tuple.NodeAndPath>;
public constructor(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.core.Path);
public getNode(): com.google.firebase.database.snapshot.Node;
public setNode(param0: com.google.firebase.database.snapshot.Node): void;
public getPath(): com.google.firebase.database.core.Path;
public setPath(param0: com.google.firebase.database.core.Path): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module utilities {
export module tuple {
export class PathAndId {
public static class: java.lang.Class<com.google.firebase.database.core.utilities.tuple.PathAndId>;
public getId(): number;
public constructor(param0: com.google.firebase.database.core.Path, param1: number);
public getPath(): com.google.firebase.database.core.Path;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class CacheNode {
public static class: java.lang.Class<com.google.firebase.database.core.view.CacheNode>;
public isCompleteForPath(param0: com.google.firebase.database.core.Path): boolean;
public isCompleteForChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public isFullyInitialized(): boolean;
public isFiltered(): boolean;
public constructor(param0: com.google.firebase.database.snapshot.IndexedNode, param1: boolean, param2: boolean);
public getIndexedNode(): com.google.firebase.database.snapshot.IndexedNode;
public getNode(): com.google.firebase.database.snapshot.Node;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class CancelEvent extends com.google.firebase.database.core.view.Event {
public static class: java.lang.Class<com.google.firebase.database.core.view.CancelEvent>;
public getPath(): com.google.firebase.database.core.Path;
public constructor(param0: com.google.firebase.database.core.EventRegistration, param1: com.google.firebase.database.DatabaseError, param2: com.google.firebase.database.core.Path);
public toString(): string;
public fire(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class Change {
public static class: java.lang.Class<com.google.firebase.database.core.view.Change>;
public static childRemovedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.core.view.Change;
public getOldIndexedNode(): com.google.firebase.database.snapshot.IndexedNode;
public getEventType(): com.google.firebase.database.core.view.Event.EventType;
public static childAddedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.Change;
public static childRemovedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.Change;
public changeWithPrevName(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.view.Change;
public static childChangedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.core.view.Change;
public getIndexedNode(): com.google.firebase.database.snapshot.IndexedNode;
public static childAddedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.core.view.Change;
public toString(): string;
public getPrevName(): com.google.firebase.database.snapshot.ChildKey;
public static childMovedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.Change;
public static valueChange(param0: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.core.view.Change;
public static childChangedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.Change;
public getChildKey(): com.google.firebase.database.snapshot.ChildKey;
public static childMovedChange(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.IndexedNode): com.google.firebase.database.core.view.Change;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class DataEvent extends com.google.firebase.database.core.view.Event {
public static class: java.lang.Class<com.google.firebase.database.core.view.DataEvent>;
public getPreviousName(): string;
public getEventType(): com.google.firebase.database.core.view.Event.EventType;
public getPath(): com.google.firebase.database.core.Path;
public getSnapshot(): com.google.firebase.database.DataSnapshot;
public toString(): string;
public constructor(param0: com.google.firebase.database.core.view.Event.EventType, param1: com.google.firebase.database.core.EventRegistration, param2: com.google.firebase.database.DataSnapshot, param3: string);
public fire(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class Event {
public static class: java.lang.Class<com.google.firebase.database.core.view.Event>;
/**
* Constructs a new instance of the com.google.firebase.database.core.view.Event interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getPath(): com.google.firebase.database.core.Path;
fire(): void;
toString(): string;
});
public constructor();
public getPath(): com.google.firebase.database.core.Path;
public toString(): string;
public fire(): void;
}
export module Event {
export class EventType {
public static class: java.lang.Class<com.google.firebase.database.core.view.Event.EventType>;
public static CHILD_REMOVED: com.google.firebase.database.core.view.Event.EventType;
public static CHILD_ADDED: com.google.firebase.database.core.view.Event.EventType;
public static CHILD_MOVED: com.google.firebase.database.core.view.Event.EventType;
public static CHILD_CHANGED: com.google.firebase.database.core.view.Event.EventType;
public static VALUE: com.google.firebase.database.core.view.Event.EventType;
public static values(): native.Array<com.google.firebase.database.core.view.Event.EventType>;
public static valueOf(param0: string): com.google.firebase.database.core.view.Event.EventType;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class EventGenerator {
public static class: java.lang.Class<com.google.firebase.database.core.view.EventGenerator>;
public constructor(param0: com.google.firebase.database.core.view.QuerySpec);
public generateEventsForChanges(param0: java.util.List<com.google.firebase.database.core.view.Change>, param1: com.google.firebase.database.snapshot.IndexedNode, param2: java.util.List<com.google.firebase.database.core.EventRegistration>): java.util.List<com.google.firebase.database.core.view.DataEvent>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class EventRaiser {
public static class: java.lang.Class<com.google.firebase.database.core.view.EventRaiser>;
public raiseEvents(param0: java.util.List<any>): void;
public constructor(param0: com.google.firebase.database.core.Context);
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class QueryParams {
public static class: java.lang.Class<com.google.firebase.database.core.view.QueryParams>;
public static DEFAULT_PARAMS: com.google.firebase.database.core.view.QueryParams;
public limitToFirst(param0: number): com.google.firebase.database.core.view.QueryParams;
public hashCode(): number;
public getIndexEndName(): com.google.firebase.database.snapshot.ChildKey;
public getIndex(): com.google.firebase.database.snapshot.Index;
public hasEnd(): boolean;
public toString(): string;
public getIndexStartValue(): com.google.firebase.database.snapshot.Node;
public isValid(): boolean;
public endAt(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.view.QueryParams;
public hasAnchoredLimit(): boolean;
public constructor();
public getIndexStartName(): com.google.firebase.database.snapshot.ChildKey;
public isDefault(): boolean;
public getIndexEndValue(): com.google.firebase.database.snapshot.Node;
public orderBy(param0: com.google.firebase.database.snapshot.Index): com.google.firebase.database.core.view.QueryParams;
public hasLimit(): boolean;
public limitToLast(param0: number): com.google.firebase.database.core.view.QueryParams;
public isViewFromLeft(): boolean;
public hasStart(): boolean;
public loadsAllData(): boolean;
public getNodeFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
public getWireProtocolParams(): java.util.Map<string,any>;
public startAt(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.core.view.QueryParams;
public toJSON(): string;
public static fromQueryObject(param0: java.util.Map<string,any>): com.google.firebase.database.core.view.QueryParams;
public equals(param0: any): boolean;
public getLimit(): number;
}
export module QueryParams {
export class ViewFrom {
public static class: java.lang.Class<com.google.firebase.database.core.view.QueryParams.ViewFrom>;
public static LEFT: com.google.firebase.database.core.view.QueryParams.ViewFrom;
public static RIGHT: com.google.firebase.database.core.view.QueryParams.ViewFrom;
public static values(): native.Array<com.google.firebase.database.core.view.QueryParams.ViewFrom>;
public static valueOf(param0: string): com.google.firebase.database.core.view.QueryParams.ViewFrom;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class QuerySpec {
public static class: java.lang.Class<com.google.firebase.database.core.view.QuerySpec>;
public isDefault(): boolean;
public loadsAllData(): boolean;
public constructor(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.view.QueryParams);
public getPath(): com.google.firebase.database.core.Path;
public hashCode(): number;
public getParams(): com.google.firebase.database.core.view.QueryParams;
public static fromPathAndQueryObject(param0: com.google.firebase.database.core.Path, param1: java.util.Map<string,any>): com.google.firebase.database.core.view.QuerySpec;
public getIndex(): com.google.firebase.database.snapshot.Index;
public toString(): string;
public static defaultQueryAtPath(param0: com.google.firebase.database.core.Path): com.google.firebase.database.core.view.QuerySpec;
public equals(param0: any): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class View {
public static class: java.lang.Class<com.google.firebase.database.core.view.View>;
public addEventRegistration(param0: com.google.firebase.database.core.EventRegistration): void;
public removeEventRegistration(param0: com.google.firebase.database.core.EventRegistration, param1: com.google.firebase.database.DatabaseError): java.util.List<com.google.firebase.database.core.view.Event>;
public getCompleteNode(): com.google.firebase.database.snapshot.Node;
public applyOperation(param0: com.google.firebase.database.core.operation.Operation, param1: com.google.firebase.database.core.WriteTreeRef, param2: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.View.OperationResult;
public getQuery(): com.google.firebase.database.core.view.QuerySpec;
public constructor(param0: com.google.firebase.database.core.view.QuerySpec, param1: com.google.firebase.database.core.view.ViewCache);
public getCompleteServerCache(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getInitialEvents(param0: com.google.firebase.database.core.EventRegistration): java.util.List<com.google.firebase.database.core.view.DataEvent>;
public getServerCache(): com.google.firebase.database.snapshot.Node;
public getEventCache(): com.google.firebase.database.snapshot.Node;
}
export module View {
export class OperationResult {
public static class: java.lang.Class<com.google.firebase.database.core.view.View.OperationResult>;
public events: java.util.List<com.google.firebase.database.core.view.DataEvent>;
public changes: java.util.List<com.google.firebase.database.core.view.Change>;
public constructor(param0: java.util.List<com.google.firebase.database.core.view.DataEvent>, param1: java.util.List<com.google.firebase.database.core.view.Change>);
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class ViewCache {
public static class: java.lang.Class<com.google.firebase.database.core.view.ViewCache>;
public getEventCache(): com.google.firebase.database.core.view.CacheNode;
public updateEventSnap(param0: com.google.firebase.database.snapshot.IndexedNode, param1: boolean, param2: boolean): com.google.firebase.database.core.view.ViewCache;
public getCompleteServerSnap(): com.google.firebase.database.snapshot.Node;
public getCompleteEventSnap(): com.google.firebase.database.snapshot.Node;
public getServerCache(): com.google.firebase.database.core.view.CacheNode;
public constructor(param0: com.google.firebase.database.core.view.CacheNode, param1: com.google.firebase.database.core.view.CacheNode);
public updateServerSnap(param0: com.google.firebase.database.snapshot.IndexedNode, param1: boolean, param2: boolean): com.google.firebase.database.core.view.ViewCache;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export class ViewProcessor {
public static class: java.lang.Class<com.google.firebase.database.core.view.ViewProcessor>;
public constructor(param0: com.google.firebase.database.core.view.filter.NodeFilter);
public revertUserWrite(param0: com.google.firebase.database.core.view.ViewCache, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.core.WriteTreeRef, param3: com.google.firebase.database.snapshot.Node, param4: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.core.view.ViewCache;
public applyOperation(param0: com.google.firebase.database.core.view.ViewCache, param1: com.google.firebase.database.core.operation.Operation, param2: com.google.firebase.database.core.WriteTreeRef, param3: com.google.firebase.database.snapshot.Node): com.google.firebase.database.core.view.ViewProcessor.ProcessorResult;
}
export module ViewProcessor {
export class ProcessorResult {
public static class: java.lang.Class<com.google.firebase.database.core.view.ViewProcessor.ProcessorResult>;
public viewCache: com.google.firebase.database.core.view.ViewCache;
public changes: java.util.List<com.google.firebase.database.core.view.Change>;
public constructor(param0: com.google.firebase.database.core.view.ViewCache, param1: java.util.List<com.google.firebase.database.core.view.Change>);
}
export class WriteTreeCompleteChildSource extends com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource {
public static class: java.lang.Class<com.google.firebase.database.core.view.ViewProcessor.WriteTreeCompleteChildSource>;
public constructor(param0: com.google.firebase.database.core.WriteTreeRef, param1: com.google.firebase.database.core.view.ViewCache, param2: com.google.firebase.database.snapshot.Node);
public getCompleteChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public getChildAfterChild(param0: com.google.firebase.database.snapshot.Index, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): com.google.firebase.database.snapshot.NamedNode;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export module filter {
export class ChildChangeAccumulator {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.ChildChangeAccumulator>;
public getChanges(): java.util.List<com.google.firebase.database.core.view.Change>;
public constructor();
public trackChildChange(param0: com.google.firebase.database.core.view.Change): void;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export module filter {
export class IndexedFilter extends com.google.firebase.database.core.view.filter.NodeFilter {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.IndexedFilter>;
public constructor(param0: com.google.firebase.database.snapshot.Index);
public getIndexedFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
public getIndex(): com.google.firebase.database.snapshot.Index;
public updateChild(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.core.Path, param4: com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource, param5: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
public updatePriority(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public filtersNodes(): boolean;
public updateFullNode(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export module filter {
export class LimitedFilter extends com.google.firebase.database.core.view.filter.NodeFilter {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.LimitedFilter>;
public getIndexedFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
public getIndex(): com.google.firebase.database.snapshot.Index;
public updateChild(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.core.Path, param4: com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource, param5: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
public updatePriority(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public filtersNodes(): boolean;
public constructor(param0: com.google.firebase.database.core.view.QueryParams);
public updateFullNode(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export module filter {
export class NodeFilter {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.NodeFilter>;
/**
* Constructs a new instance of the com.google.firebase.database.core.view.filter.NodeFilter interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
updateChild(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.core.Path, param4: com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource, param5: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
updateFullNode(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
updatePriority(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
filtersNodes(): boolean;
getIndexedFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
getIndex(): com.google.firebase.database.snapshot.Index;
});
public constructor();
public getIndexedFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
public getIndex(): com.google.firebase.database.snapshot.Index;
public updateChild(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.core.Path, param4: com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource, param5: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
public updatePriority(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public filtersNodes(): boolean;
public updateFullNode(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
}
export module NodeFilter {
export class CompleteChildSource {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource>;
/**
* Constructs a new instance of the com.google.firebase.database.core.view.filter.NodeFilter$CompleteChildSource interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
getCompleteChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
getChildAfterChild(param0: com.google.firebase.database.snapshot.Index, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): com.google.firebase.database.snapshot.NamedNode;
});
public constructor();
public getChildAfterChild(param0: com.google.firebase.database.snapshot.Index, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): com.google.firebase.database.snapshot.NamedNode;
public getCompleteChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
}
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module core {
export module view {
export module filter {
export class RangedFilter extends com.google.firebase.database.core.view.filter.NodeFilter {
public static class: java.lang.Class<com.google.firebase.database.core.view.filter.RangedFilter>;
public getIndexedFilter(): com.google.firebase.database.core.view.filter.NodeFilter;
public getEndPost(): com.google.firebase.database.snapshot.NamedNode;
public matches(param0: com.google.firebase.database.snapshot.NamedNode): boolean;
public getStartPost(): com.google.firebase.database.snapshot.NamedNode;
public getIndex(): com.google.firebase.database.snapshot.Index;
public updateChild(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.ChildKey, param2: com.google.firebase.database.snapshot.Node, param3: com.google.firebase.database.core.Path, param4: com.google.firebase.database.core.view.filter.NodeFilter.CompleteChildSource, param5: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
public updatePriority(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public filtersNodes(): boolean;
public constructor(param0: com.google.firebase.database.core.view.QueryParams);
public updateFullNode(param0: com.google.firebase.database.snapshot.IndexedNode, param1: com.google.firebase.database.snapshot.IndexedNode, param2: com.google.firebase.database.core.view.filter.ChildChangeAccumulator): com.google.firebase.database.snapshot.IndexedNode;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module logging {
export class AndroidLogger extends com.google.firebase.database.logging.DefaultLogger {
public static class: java.lang.Class<com.google.firebase.database.logging.AndroidLogger>;
public warn(param0: string, param1: string): void;
public buildLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): string;
public info(param0: string, param1: string): void;
public constructor(param0: com.google.firebase.database.logging.Logger.Level, param1: java.util.List<string>);
public onLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): void;
public error(param0: string, param1: string): void;
public debug(param0: string, param1: string): void;
public getLogLevel(): com.google.firebase.database.logging.Logger.Level;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module logging {
export class DefaultLogger extends com.google.firebase.database.logging.Logger {
public static class: java.lang.Class<com.google.firebase.database.logging.DefaultLogger>;
public warn(param0: string, param1: string): void;
public buildLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): string;
public shouldLog(param0: com.google.firebase.database.logging.Logger.Level, param1: string): boolean;
public info(param0: string, param1: string): void;
public constructor(param0: com.google.firebase.database.logging.Logger.Level, param1: java.util.List<string>);
public onLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): void;
public error(param0: string, param1: string): void;
public debug(param0: string, param1: string): void;
public getLogLevel(): com.google.firebase.database.logging.Logger.Level;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module logging {
export class LogWrapper {
public static class: java.lang.Class<com.google.firebase.database.logging.LogWrapper>;
public constructor(param0: com.google.firebase.database.logging.Logger, param1: string);
public debug(param0: string, param1: native.Array<any>): void;
public debug(param0: string, param1: java.lang.Throwable, param2: native.Array<any>): void;
public warn(param0: string): void;
public info(param0: string): void;
public logsDebug(): boolean;
public warn(param0: string, param1: java.lang.Throwable): void;
public constructor(param0: com.google.firebase.database.logging.Logger, param1: string, param2: string);
public error(param0: string, param1: java.lang.Throwable): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module logging {
export class Logger {
public static class: java.lang.Class<com.google.firebase.database.logging.Logger>;
/**
* Constructs a new instance of the com.google.firebase.database.logging.Logger interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): void;
getLogLevel(): com.google.firebase.database.logging.Logger.Level;
});
public constructor();
public onLogMessage(param0: com.google.firebase.database.logging.Logger.Level, param1: string, param2: string, param3: number): void;
public getLogLevel(): com.google.firebase.database.logging.Logger.Level;
}
export module Logger {
export class Level {
public static class: java.lang.Class<com.google.firebase.database.logging.Logger.Level>;
public static DEBUG: com.google.firebase.database.logging.Logger.Level;
public static INFO: com.google.firebase.database.logging.Logger.Level;
public static WARN: com.google.firebase.database.logging.Logger.Level;
public static ERROR: com.google.firebase.database.logging.Logger.Level;
public static NONE: com.google.firebase.database.logging.Logger.Level;
public static valueOf(param0: string): com.google.firebase.database.logging.Logger.Level;
public static values(): native.Array<com.google.firebase.database.logging.Logger.Level>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class BooleanNode extends com.google.firebase.database.snapshot.LeafNode<com.google.firebase.database.snapshot.BooleanNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.BooleanNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.BooleanNode;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareLeafValues(param0: any): number;
public getValue(param0: boolean): any;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public compareLeafValues(param0: com.google.firebase.database.snapshot.BooleanNode): number;
public constructor(param0: java.lang.Boolean, param1: com.google.firebase.database.snapshot.Node);
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class ChildKey extends java.lang.Comparable<com.google.firebase.database.snapshot.ChildKey> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ChildKey>;
public static getMaxName(): com.google.firebase.database.snapshot.ChildKey;
public static getPriorityKey(): com.google.firebase.database.snapshot.ChildKey;
public hashCode(): number;
public equals(param0: any): boolean;
public intValue(): number;
public toString(): string;
public isPriorityChildName(): boolean;
public static getInfoKey(): com.google.firebase.database.snapshot.ChildKey;
public asString(): string;
public static fromString(param0: string): com.google.firebase.database.snapshot.ChildKey;
public isInt(): boolean;
public static getMinName(): com.google.firebase.database.snapshot.ChildKey;
public compareTo(param0: com.google.firebase.database.snapshot.ChildKey): number;
}
export module ChildKey {
export class IntegerChildKey extends com.google.firebase.database.snapshot.ChildKey {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ChildKey.IntegerChildKey>;
public isInt(): boolean;
public intValue(): number;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class ChildrenNode extends com.google.firebase.database.snapshot.Node {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ChildrenNode>;
public static NAME_ONLY_COMPARATOR: java.util.Comparator<com.google.firebase.database.snapshot.ChildKey>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public getValue(): any;
public equals(param0: any): boolean;
public hashCode(): number;
public getValue(param0: boolean): any;
public constructor(param0: com.google.firebase.database.collection.ImmutableSortedMap<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.snapshot.Node>, param1: com.google.firebase.database.snapshot.Node);
public iterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public isEmpty(): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getLastChildKey(): com.google.firebase.database.snapshot.ChildKey;
public forEachChild(param0: com.google.firebase.database.snapshot.ChildrenNode.ChildVisitor): void;
public getHash(): string;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public constructor();
public forEachChild(param0: com.google.firebase.database.snapshot.ChildrenNode.ChildVisitor, param1: boolean): void;
public getChildCount(): number;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareTo(param0: com.google.firebase.database.snapshot.Node): number;
public getFirstChildKey(): com.google.firebase.database.snapshot.ChildKey;
public toString(): string;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
}
export module ChildrenNode {
export abstract class ChildVisitor extends com.google.firebase.database.collection.LLRBNode.NodeVisitor<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.snapshot.Node> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ChildrenNode.ChildVisitor>;
public constructor();
public visitChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): void;
public visitEntry(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): void;
}
export class NamedNodeIterator extends java.util.Iterator<com.google.firebase.database.snapshot.NamedNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ChildrenNode.NamedNodeIterator>;
public constructor(param0: java.util.Iterator<java.util.Map.Entry<com.google.firebase.database.snapshot.ChildKey,com.google.firebase.database.snapshot.Node>>);
public hasNext(): boolean;
public remove(): void;
public next(): com.google.firebase.database.snapshot.NamedNode;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class CompoundHash {
public static class: java.lang.Class<com.google.firebase.database.snapshot.CompoundHash>;
public getPosts(): java.util.List<com.google.firebase.database.core.Path>;
public static fromNode(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.CompoundHash.SplitStrategy): com.google.firebase.database.snapshot.CompoundHash;
public static fromNode(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.CompoundHash;
public getHashes(): java.util.List<string>;
}
export module CompoundHash {
export class CompoundHashBuilder {
public static class: java.lang.Class<com.google.firebase.database.snapshot.CompoundHash.CompoundHashBuilder>;
public currentPath(): com.google.firebase.database.core.Path;
public constructor(param0: com.google.firebase.database.snapshot.CompoundHash.SplitStrategy);
public currentHashLength(): number;
public buildingRange(): boolean;
}
export class SimpleSizeSplitStrategy extends com.google.firebase.database.snapshot.CompoundHash.SplitStrategy {
public static class: java.lang.Class<com.google.firebase.database.snapshot.CompoundHash.SimpleSizeSplitStrategy>;
public shouldSplit(param0: com.google.firebase.database.snapshot.CompoundHash.CompoundHashBuilder): boolean;
public constructor(param0: com.google.firebase.database.snapshot.Node);
}
export class SplitStrategy {
public static class: java.lang.Class<com.google.firebase.database.snapshot.CompoundHash.SplitStrategy>;
/**
* Constructs a new instance of the com.google.firebase.database.snapshot.CompoundHash$SplitStrategy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
shouldSplit(param0: com.google.firebase.database.snapshot.CompoundHash.CompoundHashBuilder): boolean;
});
public constructor();
public shouldSplit(param0: com.google.firebase.database.snapshot.CompoundHash.CompoundHashBuilder): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class DeferredValueNode extends com.google.firebase.database.snapshot.LeafNode<com.google.firebase.database.snapshot.DeferredValueNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.DeferredValueNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public constructor(param0: java.util.Map<any,any>, param1: com.google.firebase.database.snapshot.Node);
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareLeafValues(param0: any): number;
public getValue(param0: boolean): any;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.DeferredValueNode;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public compareLeafValues(param0: com.google.firebase.database.snapshot.DeferredValueNode): number;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class DoubleNode extends com.google.firebase.database.snapshot.LeafNode<com.google.firebase.database.snapshot.DoubleNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.DoubleNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareLeafValues(param0: any): number;
public getValue(param0: boolean): any;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.DoubleNode;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public constructor(param0: java.lang.Double, param1: com.google.firebase.database.snapshot.Node);
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public compareLeafValues(param0: com.google.firebase.database.snapshot.DoubleNode): number;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class EmptyNode extends com.google.firebase.database.snapshot.ChildrenNode implements com.google.firebase.database.snapshot.Node {
public static class: java.lang.Class<com.google.firebase.database.snapshot.EmptyNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public static Empty(): com.google.firebase.database.snapshot.EmptyNode;
public compareTo(param0: com.google.firebase.database.snapshot.Node): number;
public getValue(param0: boolean): any;
public toString(): string;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public iterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.EmptyNode;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export abstract class Index extends java.util.Comparator<com.google.firebase.database.snapshot.NamedNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.Index>;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): number;
public constructor();
public isDefinedOn(param0: com.google.firebase.database.snapshot.Node): boolean;
public maxPost(): com.google.firebase.database.snapshot.NamedNode;
public static fromQueryDefinition(param0: string): com.google.firebase.database.snapshot.Index;
public makePost(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.NamedNode;
public minPost(): com.google.firebase.database.snapshot.NamedNode;
public getQueryDefinition(): string;
public indexedValueChanged(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.Node): boolean;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class IndexedNode extends java.lang.Iterable<com.google.firebase.database.snapshot.NamedNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.IndexedNode>;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public hasIndex(param0: com.google.firebase.database.snapshot.Index): boolean;
public iterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public updateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public static from(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.IndexedNode;
public static from(param0: com.google.firebase.database.snapshot.Node, param1: com.google.firebase.database.snapshot.Index): com.google.firebase.database.snapshot.IndexedNode;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public getLastChild(): com.google.firebase.database.snapshot.NamedNode;
public getNode(): com.google.firebase.database.snapshot.Node;
public getFirstChild(): com.google.firebase.database.snapshot.NamedNode;
public getPredecessorChildName(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.Index): com.google.firebase.database.snapshot.ChildKey;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class KeyIndex extends com.google.firebase.database.snapshot.Index {
public static class: java.lang.Class<com.google.firebase.database.snapshot.KeyIndex>;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): number;
public isDefinedOn(param0: com.google.firebase.database.snapshot.Node): boolean;
public maxPost(): com.google.firebase.database.snapshot.NamedNode;
public makePost(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.NamedNode;
public getQueryDefinition(): string;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode): number;
public equals(param0: any): boolean;
public hashCode(): number;
public static getInstance(): com.google.firebase.database.snapshot.KeyIndex;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export abstract class LeafNode<T> extends com.google.firebase.database.snapshot.Node {
public static class: java.lang.Class<com.google.firebase.database.snapshot.LeafNode<any>>;
public priority: com.google.firebase.database.snapshot.Node;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public getValue(): any;
public equals(param0: any): boolean;
public hashCode(): number;
public getPriorityHash(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public compareLeafValues(param0: any): number;
public leafCompare(param0: com.google.firebase.database.snapshot.LeafNode<any>): number;
public getValue(param0: boolean): any;
public iterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getHash(): string;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getChildCount(): number;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareTo(param0: com.google.firebase.database.snapshot.Node): number;
public toString(): string;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
export module LeafNode {
export class LeafType {
public static class: java.lang.Class<com.google.firebase.database.snapshot.LeafNode.LeafType>;
public static DeferredValue: com.google.firebase.database.snapshot.LeafNode.LeafType;
public static Boolean: com.google.firebase.database.snapshot.LeafNode.LeafType;
public static Number: com.google.firebase.database.snapshot.LeafNode.LeafType;
public static String: com.google.firebase.database.snapshot.LeafNode.LeafType;
public static valueOf(param0: string): com.google.firebase.database.snapshot.LeafNode.LeafType;
public static values(): native.Array<com.google.firebase.database.snapshot.LeafNode.LeafType>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class LongNode extends com.google.firebase.database.snapshot.LeafNode<com.google.firebase.database.snapshot.LongNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.LongNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareLeafValues(param0: any): number;
public getValue(param0: boolean): any;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public constructor(param0: java.lang.Long, param1: com.google.firebase.database.snapshot.Node);
public compareLeafValues(param0: com.google.firebase.database.snapshot.LongNode): number;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.LongNode;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class NamedNode {
public static class: java.lang.Class<com.google.firebase.database.snapshot.NamedNode>;
public static getMaxNode(): com.google.firebase.database.snapshot.NamedNode;
public getName(): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public static getMinNode(): com.google.firebase.database.snapshot.NamedNode;
public constructor(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node);
public getNode(): com.google.firebase.database.snapshot.Node;
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class Node extends java.lang.Object {
public static class: java.lang.Class<com.google.firebase.database.snapshot.Node>;
/**
* Constructs a new instance of the com.google.firebase.database.snapshot.Node interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
isLeafNode(): boolean;
getPriority(): com.google.firebase.database.snapshot.Node;
getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
isEmpty(): boolean;
getChildCount(): number;
getValue(): any;
getValue(param0: boolean): any;
getHash(): string;
getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
<clinit>(): void;
});
public constructor();
public static MAX_NODE: com.google.firebase.database.snapshot.ChildrenNode;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public getValue(param0: boolean): any;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
}
export module Node {
export class HashVersion {
public static class: java.lang.Class<com.google.firebase.database.snapshot.Node.HashVersion>;
public static V1: com.google.firebase.database.snapshot.Node.HashVersion;
public static V2: com.google.firebase.database.snapshot.Node.HashVersion;
public static values(): native.Array<com.google.firebase.database.snapshot.Node.HashVersion>;
public static valueOf(param0: string): com.google.firebase.database.snapshot.Node.HashVersion;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class NodeUtilities {
public static class: java.lang.Class<com.google.firebase.database.snapshot.NodeUtilities>;
public constructor();
public static NodeFromJSON(param0: any): com.google.firebase.database.snapshot.Node;
public static NodeFromJSON(param0: any, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public static nameAndPriorityCompare(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node, param2: com.google.firebase.database.snapshot.ChildKey, param3: com.google.firebase.database.snapshot.Node): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class PathIndex extends com.google.firebase.database.snapshot.Index {
public static class: java.lang.Class<com.google.firebase.database.snapshot.PathIndex>;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): number;
public constructor();
public isDefinedOn(param0: com.google.firebase.database.snapshot.Node): boolean;
public maxPost(): com.google.firebase.database.snapshot.NamedNode;
public makePost(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.NamedNode;
public constructor(param0: com.google.firebase.database.core.Path);
public getQueryDefinition(): string;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode): number;
public equals(param0: any): boolean;
public hashCode(): number;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class PriorityIndex extends com.google.firebase.database.snapshot.Index {
public static class: java.lang.Class<com.google.firebase.database.snapshot.PriorityIndex>;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): number;
public isDefinedOn(param0: com.google.firebase.database.snapshot.Node): boolean;
public maxPost(): com.google.firebase.database.snapshot.NamedNode;
public makePost(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.NamedNode;
public getQueryDefinition(): string;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode): number;
public equals(param0: any): boolean;
public hashCode(): number;
public toString(): string;
public static getInstance(): com.google.firebase.database.snapshot.PriorityIndex;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class PriorityUtilities {
public static class: java.lang.Class<com.google.firebase.database.snapshot.PriorityUtilities>;
public static NullPriority(): com.google.firebase.database.snapshot.Node;
public constructor();
public static parsePriority(param0: any): com.google.firebase.database.snapshot.Node;
public static isValidPriority(param0: com.google.firebase.database.snapshot.Node): boolean;
public static parsePriority(param0: com.google.firebase.database.core.Path, param1: any): com.google.firebase.database.snapshot.Node;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class RangeMerge {
public static class: java.lang.Class<com.google.firebase.database.snapshot.RangeMerge>;
public constructor(param0: com.google.firebase.database.connection.RangeMerge);
public applyTo(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public constructor(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.core.Path, param2: com.google.firebase.database.snapshot.Node);
public toString(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class StringNode extends com.google.firebase.database.snapshot.LeafNode<com.google.firebase.database.snapshot.StringNode> {
public static class: java.lang.Class<com.google.firebase.database.snapshot.StringNode>;
public getImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.Node;
public compareLeafValues(param0: com.google.firebase.database.snapshot.StringNode): number;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public getHash(): string;
public getChildCount(): number;
public updatePriority(param0: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.StringNode;
public getValue(): any;
public getSuccessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public equals(param0: any): boolean;
public hashCode(): number;
public getPredecessorChildKey(param0: com.google.firebase.database.snapshot.ChildKey): com.google.firebase.database.snapshot.ChildKey;
public reverseIterator(): java.util.Iterator<com.google.firebase.database.snapshot.NamedNode>;
public compareLeafValues(param0: any): number;
public getValue(param0: boolean): any;
public getChild(param0: com.google.firebase.database.core.Path): com.google.firebase.database.snapshot.Node;
public isLeafNode(): boolean;
public getPriority(): com.google.firebase.database.snapshot.Node;
public updateImmediateChild(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public constructor(param0: string, param1: com.google.firebase.database.snapshot.Node);
public hasChild(param0: com.google.firebase.database.snapshot.ChildKey): boolean;
public updateChild(param0: com.google.firebase.database.core.Path, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.Node;
public isEmpty(): boolean;
public getHashRepresentation(param0: com.google.firebase.database.snapshot.Node.HashVersion): string;
public getLeafType(): com.google.firebase.database.snapshot.LeafNode.LeafType;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module snapshot {
export class ValueIndex extends com.google.firebase.database.snapshot.Index {
public static class: java.lang.Class<com.google.firebase.database.snapshot.ValueIndex>;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode, param2: boolean): number;
public isDefinedOn(param0: com.google.firebase.database.snapshot.Node): boolean;
public maxPost(): com.google.firebase.database.snapshot.NamedNode;
public makePost(param0: com.google.firebase.database.snapshot.ChildKey, param1: com.google.firebase.database.snapshot.Node): com.google.firebase.database.snapshot.NamedNode;
public getQueryDefinition(): string;
public compare(param0: com.google.firebase.database.snapshot.NamedNode, param1: com.google.firebase.database.snapshot.NamedNode): number;
public hashCode(): number;
public equals(param0: any): boolean;
public toString(): string;
public static getInstance(): com.google.firebase.database.snapshot.ValueIndex;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class MessageBuilderFactory {
public static class: java.lang.Class<com.google.firebase.database.tubesock.MessageBuilderFactory>;
}
export module MessageBuilderFactory {
export class BinaryBuilder extends com.google.firebase.database.tubesock.MessageBuilderFactory.Builder {
public static class: java.lang.Class<com.google.firebase.database.tubesock.MessageBuilderFactory.BinaryBuilder>;
public appendBytes(param0: native.Array<number>): boolean;
public toMessage(): com.google.firebase.database.tubesock.WebSocketMessage;
}
export class Builder {
public static class: java.lang.Class<com.google.firebase.database.tubesock.MessageBuilderFactory.Builder>;
/**
* Constructs a new instance of the com.google.firebase.database.tubesock.MessageBuilderFactory$Builder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
appendBytes(param0: native.Array<number>): boolean;
toMessage(): com.google.firebase.database.tubesock.WebSocketMessage;
});
public constructor();
public appendBytes(param0: native.Array<number>): boolean;
public toMessage(): com.google.firebase.database.tubesock.WebSocketMessage;
}
export class TextBuilder extends com.google.firebase.database.tubesock.MessageBuilderFactory.Builder {
public static class: java.lang.Class<com.google.firebase.database.tubesock.MessageBuilderFactory.TextBuilder>;
public appendBytes(param0: native.Array<number>): boolean;
public toMessage(): com.google.firebase.database.tubesock.WebSocketMessage;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class ThreadInitializer {
public static class: java.lang.Class<com.google.firebase.database.tubesock.ThreadInitializer>;
/**
* Constructs a new instance of the com.google.firebase.database.tubesock.ThreadInitializer interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
setName(param0: java.lang.Thread, param1: string): void;
});
public constructor();
public setName(param0: java.lang.Thread, param1: string): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocket {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocket>;
public static setThreadFactory(param0: java.util.concurrent.ThreadFactory, param1: com.google.firebase.database.tubesock.ThreadInitializer): void;
public blockClose(): void;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: java.net.URI);
public close(): void;
public setEventHandler(param0: com.google.firebase.database.tubesock.WebSocketEventHandler): void;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: java.net.URI, param2: string, param3: java.util.Map<string,string>);
public connect(): void;
public constructor(param0: com.google.firebase.database.connection.ConnectionContext, param1: java.net.URI, param2: string);
public send(param0: string): void;
public send(param0: native.Array<number>): void;
}
export module WebSocket {
export class State {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocket.State>;
public static NONE: com.google.firebase.database.tubesock.WebSocket.State;
public static CONNECTING: com.google.firebase.database.tubesock.WebSocket.State;
public static CONNECTED: com.google.firebase.database.tubesock.WebSocket.State;
public static DISCONNECTING: com.google.firebase.database.tubesock.WebSocket.State;
public static DISCONNECTED: com.google.firebase.database.tubesock.WebSocket.State;
public static values(): native.Array<com.google.firebase.database.tubesock.WebSocket.State>;
public static valueOf(param0: string): com.google.firebase.database.tubesock.WebSocket.State;
}
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketEventHandler {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketEventHandler>;
/**
* Constructs a new instance of the com.google.firebase.database.tubesock.WebSocketEventHandler interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onOpen(): void;
onMessage(param0: com.google.firebase.database.tubesock.WebSocketMessage): void;
onClose(): void;
onError(param0: com.google.firebase.database.tubesock.WebSocketException): void;
onLogMessage(param0: string): void;
});
public constructor();
public onOpen(): void;
public onMessage(param0: com.google.firebase.database.tubesock.WebSocketMessage): void;
public onError(param0: com.google.firebase.database.tubesock.WebSocketException): void;
public onLogMessage(param0: string): void;
public onClose(): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketException {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketException>;
public constructor(param0: string, param1: java.lang.Throwable);
public constructor(param0: string);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketHandshake {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketHandshake>;
public constructor(param0: java.net.URI, param1: string, param2: java.util.Map<string,string>);
public verifyServerHandshakeHeaders(param0: java.util.HashMap<string,string>): void;
public getHandshake(): native.Array<number>;
public verifyServerStatusLine(param0: string): void;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketMessage {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketMessage>;
public constructor(param0: native.Array<number>);
public isBinary(): boolean;
public getBytes(): native.Array<number>;
public isText(): boolean;
public getText(): string;
public constructor(param0: string);
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketReceiver {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketReceiver>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module tubesock {
export class WebSocketWriter {
public static class: java.lang.Class<com.google.firebase.database.tubesock.WebSocketWriter>;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module util {
export class GAuthToken {
public static class: java.lang.Class<com.google.firebase.database.util.GAuthToken>;
public static tryParseFromString(param0: string): com.google.firebase.database.util.GAuthToken;
public serializeToString(): string;
public constructor(param0: string, param1: java.util.Map<string,any>);
public getAuth(): java.util.Map<string,any>;
public getToken(): string;
}
}
}
}
}
}
declare module com {
export module google {
export module firebase {
export module database {
export module util {
export class JsonMapper {
public static class: java.lang.Class<com.google.firebase.database.util.JsonMapper>;
public static serializeJson(param0: java.util.Map<string,any>): string;
public constructor();
public static serializeJsonValue(param0: any): string;
public static parseJson(param0: string): java.util.Map<string,any>;
public static parseJsonValue(param0: string): any;
}
}
}
}
}
}
//Generics information:
//com.google.firebase.database.GenericTypeIndicator:1
//com.google.firebase.database.core.utilities.ImmutableTree:1
//com.google.firebase.database.core.utilities.ImmutableTree.TreeVisitor:2
//com.google.firebase.database.core.utilities.Pair:2
//com.google.firebase.database.core.utilities.Predicate:1
//com.google.firebase.database.core.utilities.Tree:1
//com.google.firebase.database.core.utilities.Tree.TreeFilter:1
//com.google.firebase.database.core.utilities.Tree.TreeVisitor:1
//com.google.firebase.database.core.utilities.TreeNode:1
//com.google.firebase.database.core.utilities.encoding.CustomClassMapper.BeanMapper:1
//com.google.firebase.database.snapshot.LeafNode:1 | the_stack |
import { DiagnosticSeverity } from 'vscode-languageserver-types';
import { Document, Node, Pair, Scalar, YAMLMap, YAMLSeq } from 'yaml';
import { JSONSchema, JSONSchemaRef } from '../jsonSchema';
import { formats, ProblemType, ProblemTypeMessages, ValidationResult } from './jsonParser07';
import { URI } from 'vscode-uri';
import * as nls from 'vscode-nls';
import { equals, isBoolean, isDefined, isIterable, isNumber, isString } from '../utils/objects';
import { getSchemaTypeName } from '../utils/schemaUtils';
import { isMap, isPair, isScalar, isSeq } from 'yaml';
import { toOffsetLength } from './ast-converter';
import { getParent } from '../utils/astUtils';
const localize = nls.loadMessageBundle();
export const YAML_SOURCE = 'YAML';
const YAML_SCHEMA_PREFIX = 'yaml-schema: ';
/**
* Error codes used by diagnostics
*/
export enum ErrorCode {
Undefined = 0,
EnumValueMismatch = 1,
Deprecated = 2,
UnexpectedEndOfComment = 257,
UnexpectedEndOfString = 258,
UnexpectedEndOfNumber = 259,
InvalidUnicode = 260,
InvalidEscapeCharacter = 261,
InvalidCharacter = 262,
PropertyExpected = 513,
CommaExpected = 514,
ColonExpected = 515,
ValueExpected = 516,
CommaOrCloseBacketExpected = 517,
CommaOrCloseBraceExpected = 518,
TrailingComma = 519,
DuplicateKey = 520,
CommentNotPermitted = 521,
SchemaResolveError = 768,
}
// const jsonToTypeMap = {
// object: MAP,
// array: SEQ,
// property: PAIR,
// string: SCALAR,
// number: SCALAR,
// boolean: SCALAR,
// null: SCALAR,
// };
function getNodeType(node: Node): string {
if (isMap(node)) {
return 'object';
}
if (isSeq(node)) {
return 'array';
}
if (isPair(node)) {
return 'property';
}
if (isScalar(node)) {
return typeof (node as Scalar).value;
}
}
export interface ApplicableSchema {
node: Node;
inverted?: boolean;
schema: JSONSchema;
}
export interface SchemaCollector {
schemas: ApplicableSchema[];
add(schema: ApplicableSchema): void;
merge(other: SchemaCollector): void;
include(node: Node): boolean;
newSub(): SchemaCollector;
}
export class SchemaCollectorImpl implements SchemaCollector {
schemas: ApplicableSchema[] = [];
constructor(private focusOffset = -1, private exclude: Node = null) {}
add(schema: ApplicableSchema): void {
this.schemas.push(schema);
}
merge(other: SchemaCollector): void {
this.schemas.push(...other.schemas);
}
include(node: Node): boolean {
return (this.focusOffset === -1 || contains(node, this.focusOffset)) && node !== this.exclude;
}
newSub(): SchemaCollector {
return new SchemaCollectorImpl(-1, this.exclude);
}
}
class NoOpSchemaCollector implements SchemaCollector {
private constructor() {
// ignore
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
get schemas(): any[] {
return [];
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
add(schema: ApplicableSchema): void {
// ignore
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
merge(other: SchemaCollector): void {
// ignore
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
include(node: Node): boolean {
return true;
}
newSub(): SchemaCollector {
return this;
}
static instance = new NoOpSchemaCollector();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getNodeValue(node: Node): any {
if (isSeq(node)) {
return node.items.map(getNodeValue);
}
if (isMap(node)) {
const obj = Object.create(null);
for (const pair of node.items) {
const valueNode = pair.value;
if (valueNode && isScalar(pair.key)) {
//TODO: fix this
obj[pair.key.value as string] = getNodeValue(valueNode as Node);
}
}
return obj;
}
if (isScalar(node)) {
return node.value;
}
return undefined;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function contains(node: Node, offset: number, includeRightBound = false): boolean {
// return (
// (offset >= node.range && offset <= node.offset + node.length) || (includeRightBound && offset === node.offset + node.length)
// );
throw new Error('Implement me!!!');
}
export interface Options {
isKubernetes: boolean;
disableAdditionalProperties: boolean;
}
export function validate(
node: Node,
document: Document,
schema: JSONSchema,
originalSchema: JSONSchema,
validationResult: ValidationResult,
matchingSchemas: SchemaCollector,
options: Options
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): any {
const { isKubernetes } = options;
if (!node || !matchingSchemas.include(node)) {
return;
}
if (!schema.url) {
schema.url = originalSchema.url;
}
if (!schema.title) {
schema.title = originalSchema.title;
}
if (isMap(node)) {
_validateObjectNode(node, schema, validationResult, matchingSchemas);
} else if (isSeq(node)) {
_validateArrayNode(node as YAMLSeq, schema, validationResult, matchingSchemas);
} else if (isScalar(node)) {
switch (typeof (node as Scalar).value) {
case 'string':
_validateStringNode(node as Scalar<string>, schema, validationResult);
break;
case 'number':
_validateNumberNode(node as Scalar<number>, schema, validationResult);
break;
}
} else if (isPair(node)) {
return validate((node as Pair).value as Node, document, schema, schema, validationResult, matchingSchemas, options);
}
_validateNode();
matchingSchemas.add({ node: node, schema: schema });
function _validateNode(): void {
function matchesType(type: string): boolean {
return (
getNodeType(node) === type ||
(type === 'integer' && isScalar(node) && typeof node.value === 'number' && Number.isInteger(node.value))
);
}
if (Array.isArray(schema.type)) {
if (!schema.type.some(matchesType)) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message:
schema.errorMessage ||
localize('typeArrayMismatchWarning', 'Incorrect type. Expected one of {0}.', (<string[]>schema.type).join(', ')),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
} else if (schema.type) {
if (!matchesType(schema.type)) {
//get more specific name than just object
const schemaType = schema.type === 'object' ? getSchemaTypeName(schema) : schema.type;
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || getWarningMessage(ProblemType.typeMismatchWarning, [schemaType]),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
problemType: ProblemType.typeMismatchWarning,
problemArgs: [schemaType],
});
}
}
if (Array.isArray(schema.allOf)) {
for (const subSchemaRef of schema.allOf) {
validate(node, document, asSchema(subSchemaRef), schema, validationResult, matchingSchemas, options);
}
}
const notSchema = asSchema(schema.not);
if (notSchema) {
const subValidationResult = new ValidationResult(isKubernetes);
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, document, notSchema, schema, subValidationResult, subMatchingSchemas, options);
if (!subValidationResult.hasProblems()) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('notSchemaWarning', 'Matches a schema that is not allowed.'),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
for (const ms of subMatchingSchemas.schemas) {
ms.inverted = !ms.inverted;
matchingSchemas.add(ms);
}
}
const testAlternatives = (alternatives: JSONSchemaRef[], maxOneMatch: boolean): number => {
const matches = [];
// remember the best match that is used for error messages
let bestMatch: {
schema: JSONSchema;
validationResult: ValidationResult;
matchingSchemas: SchemaCollector;
} = null;
for (const subSchemaRef of alternatives) {
const subSchema = asSchema(subSchemaRef);
const subValidationResult = new ValidationResult(isKubernetes);
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, document, subSchema, schema, subValidationResult, subMatchingSchemas, options);
if (!subValidationResult.hasProblems()) {
matches.push(subSchema);
}
if (!bestMatch) {
bestMatch = {
schema: subSchema,
validationResult: subValidationResult,
matchingSchemas: subMatchingSchemas,
};
} else if (isKubernetes) {
bestMatch = alternativeComparison(subValidationResult, bestMatch, subSchema, subMatchingSchemas);
} else {
bestMatch = genericComparison(maxOneMatch, subValidationResult, bestMatch, subSchema, subMatchingSchemas);
}
}
if (matches.length > 1 && maxOneMatch) {
const [offset] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length: 1 },
severity: DiagnosticSeverity.Warning,
message: localize('oneOfWarning', 'Matches multiple schemas when only one must validate.'),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
if (bestMatch !== null) {
validationResult.merge(bestMatch.validationResult);
validationResult.propertiesMatches += bestMatch.validationResult.propertiesMatches;
validationResult.propertiesValueMatches += bestMatch.validationResult.propertiesValueMatches;
matchingSchemas.merge(bestMatch.matchingSchemas);
}
return matches.length;
};
if (Array.isArray(schema.anyOf)) {
testAlternatives(schema.anyOf, false);
}
if (Array.isArray(schema.oneOf)) {
testAlternatives(schema.oneOf, true);
}
const testBranch = (schema: JSONSchemaRef, originalSchema: JSONSchema): void => {
const subValidationResult = new ValidationResult(isKubernetes);
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, document, asSchema(schema), originalSchema, subValidationResult, subMatchingSchemas, options);
validationResult.merge(subValidationResult);
validationResult.propertiesMatches += subValidationResult.propertiesMatches;
validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
matchingSchemas.merge(subMatchingSchemas);
};
const testCondition = (
ifSchema: JSONSchemaRef,
originalSchema: JSONSchema,
thenSchema?: JSONSchemaRef,
elseSchema?: JSONSchemaRef
): void => {
const subSchema = asSchema(ifSchema);
const subValidationResult = new ValidationResult(isKubernetes);
const subMatchingSchemas = matchingSchemas.newSub();
validate(node, document, subSchema, originalSchema, subValidationResult, subMatchingSchemas, options);
matchingSchemas.merge(subMatchingSchemas);
if (!subValidationResult.hasProblems()) {
if (thenSchema) {
testBranch(thenSchema, originalSchema);
}
} else if (elseSchema) {
testBranch(elseSchema, originalSchema);
}
};
const ifSchema = asSchema(schema.if);
if (ifSchema) {
testCondition(ifSchema, schema, asSchema(schema.then), asSchema(schema.else));
}
if (Array.isArray(schema.enum)) {
const val = getNodeValue(node);
let enumValueMatch = false;
for (const e of schema.enum) {
if (equals(val, e)) {
enumValueMatch = true;
break;
}
}
validationResult.enumValues = schema.enum;
validationResult.enumValueMatch = enumValueMatch;
if (!enumValueMatch) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
code: ErrorCode.EnumValueMismatch,
message:
schema.errorMessage ||
localize(
'enumWarning',
'Value is not accepted. Valid values: {0}.',
schema.enum
.map((v) => {
return JSON.stringify(v);
})
.join(', ')
),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
if (isDefined(schema.const)) {
const val = getNodeValue(node);
if (!equals(val, schema.const)) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
code: ErrorCode.EnumValueMismatch,
problemType: ProblemType.constWarning,
message: schema.errorMessage || getWarningMessage(ProblemType.constWarning, [JSON.stringify(schema.const)]),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
problemArgs: [JSON.stringify(schema.const)],
});
validationResult.enumValueMatch = false;
} else {
validationResult.enumValueMatch = true;
}
validationResult.enumValues = [schema.const];
}
const parent = getParent(document, node);
if (schema.deprecationMessage && parent) {
const [offset, length] = toOffsetLength(parent.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: schema.deprecationMessage,
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
function _validateNumberNode(node: Scalar<number>, schema: JSONSchema, validationResult: ValidationResult): void {
const val = node.value;
if (isNumber(schema.multipleOf)) {
if (val % schema.multipleOf !== 0) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('multipleOfWarning', 'Value is not divisible by {0}.', schema.multipleOf),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
function getExclusiveLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (isNumber(exclusive)) {
return exclusive;
}
if (isBoolean(exclusive) && exclusive) {
return limit;
}
return undefined;
}
function getLimit(limit: number | undefined, exclusive: boolean | number | undefined): number | undefined {
if (!isBoolean(exclusive) || !exclusive) {
return limit;
}
return undefined;
}
const exclusiveMinimum = getExclusiveLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(exclusiveMinimum) && val <= exclusiveMinimum) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('exclusiveMinimumWarning', 'Value is below the exclusive minimum of {0}.', exclusiveMinimum),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
const exclusiveMaximum = getExclusiveLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(exclusiveMaximum) && val >= exclusiveMaximum) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('exclusiveMaximumWarning', 'Value is above the exclusive maximum of {0}.', exclusiveMaximum),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
const minimum = getLimit(schema.minimum, schema.exclusiveMinimum);
if (isNumber(minimum) && val < minimum) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('minimumWarning', 'Value is below the minimum of {0}.', minimum),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
const maximum = getLimit(schema.maximum, schema.exclusiveMaximum);
if (isNumber(maximum) && val > maximum) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('maximumWarning', 'Value is above the maximum of {0}.', maximum),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
function _validateStringNode(node: Scalar<string>, schema: JSONSchema, validationResult: ValidationResult): void {
if (isNumber(schema.minLength) && node.value.length < schema.minLength) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('minLengthWarning', 'String is shorter than the minimum length of {0}.', schema.minLength),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
if (isNumber(schema.maxLength) && node.value.length > schema.maxLength) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('maxLengthWarning', 'String is longer than the maximum length of {0}.', schema.maxLength),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
if (isString(schema.pattern)) {
const regex = new RegExp(schema.pattern, 'u');
if (!regex.test(node.value)) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message:
schema.patternErrorMessage ||
schema.errorMessage ||
localize('patternWarning', 'String does not match the pattern of "{0}".', schema.pattern),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
if (schema.format) {
switch (schema.format) {
case 'uri':
case 'uri-reference':
{
let errorMessage;
if (!node.value) {
errorMessage = localize('uriEmpty', 'URI expected.');
} else {
try {
const uri = URI.parse(node.value);
if (!uri.scheme && schema.format === 'uri') {
errorMessage = localize('uriSchemeMissing', 'URI with a scheme is expected.');
}
} catch (e) {
errorMessage = e.message;
}
}
if (errorMessage) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message:
schema.patternErrorMessage ||
schema.errorMessage ||
localize('uriFormatWarning', 'String is not a URI: {0}', errorMessage),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
break;
case 'color-hex':
case 'date-time':
case 'date':
case 'time':
case 'email':
{
const format = formats[schema.format];
if (!node.value || !format.pattern.exec(node.value)) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: schema.patternErrorMessage || schema.errorMessage || format.errorMessage,
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
break;
default:
}
}
}
function _validateArrayNode(
node: YAMLSeq,
schema: JSONSchema,
validationResult: ValidationResult,
matchingSchemas: SchemaCollector
): void {
if (Array.isArray(schema.items)) {
const subSchemas = schema.items;
for (let index = 0; index < subSchemas.length; index++) {
const subSchemaRef = subSchemas[index];
const subSchema = asSchema(subSchemaRef);
const itemValidationResult = new ValidationResult(isKubernetes);
const item = node.items[index];
if (item) {
validate(item as Node, document, subSchema, schema, itemValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(itemValidationResult);
validationResult.mergeEnumValues(itemValidationResult);
} else if (node.items.length >= subSchemas.length) {
validationResult.propertiesValueMatches++;
}
}
if (node.items.length > subSchemas.length) {
if (typeof schema.additionalItems === 'object') {
for (let i = subSchemas.length; i < node.items.length; i++) {
const itemValidationResult = new ValidationResult(isKubernetes);
validate(
node.items[i] as Node,
document,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
<any>schema.additionalItems,
schema,
itemValidationResult,
matchingSchemas,
options
);
validationResult.mergePropertyMatch(itemValidationResult);
validationResult.mergeEnumValues(itemValidationResult);
}
} else if (schema.additionalItems === false) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize(
'additionalItemsWarning',
'Array has too many items according to schema. Expected {0} or fewer.',
subSchemas.length
),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
} else {
const itemSchema = asSchema(schema.items);
if (itemSchema) {
for (const item of node.items) {
const itemValidationResult = new ValidationResult(isKubernetes);
validate(item as Node, document, itemSchema, schema, itemValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(itemValidationResult);
validationResult.mergeEnumValues(itemValidationResult);
}
}
}
const containsSchema = asSchema(schema.contains);
if (containsSchema) {
const doesContain = node.items.some((item) => {
const itemValidationResult = new ValidationResult(isKubernetes);
validate(item as Node, document, containsSchema, schema, itemValidationResult, NoOpSchemaCollector.instance, options);
return !itemValidationResult.hasProblems();
});
if (!doesContain) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: schema.errorMessage || localize('requiredItemMissingWarning', 'Array does not contain required item.'),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
if (isNumber(schema.minItems) && node.items.length < schema.minItems) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('minItemsWarning', 'Array has too few items. Expected {0} or more.', schema.minItems),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
if (isNumber(schema.maxItems) && node.items.length > schema.maxItems) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('maxItemsWarning', 'Array has too many items. Expected {0} or fewer.', schema.maxItems),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
if (schema.uniqueItems === true) {
const values = getNodeValue(node);
const duplicates = values.some((value, index) => {
return index !== values.lastIndexOf(value);
});
if (duplicates) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('uniqueItemsWarning', 'Array has duplicate items.'),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
}
function _validateObjectNode(
node: YAMLMap,
schema: JSONSchema,
validationResult: ValidationResult,
matchingSchemas: SchemaCollector
): void {
const seenKeys: { [key: string]: Node } = Object.create(null);
const unprocessedProperties: string[] = [];
const unprocessedNodes: Pair[] = [...node.items];
while (unprocessedNodes.length > 0) {
const propertyNode = unprocessedNodes.pop();
if (!isScalar(propertyNode.key)) {
continue;
}
const key = propertyNode.key.value.toString();
//Replace the merge key with the actual values of what the node value points to in seen keys
if (key === '<<' && propertyNode.value) {
if (isMap(propertyNode.value)) {
unprocessedNodes.push(...propertyNode.value.items);
} else if (isSeq(propertyNode.value)) {
propertyNode.value.items.forEach((sequenceNode) => {
if (sequenceNode && isIterable(sequenceNode['items'])) {
unprocessedNodes.push(...sequenceNode['items']);
}
});
}
} else {
seenKeys[key] = propertyNode.value as Node;
unprocessedProperties.push(key);
}
}
if (Array.isArray(schema.required)) {
for (const propertyName of schema.required) {
if (!seenKeys[propertyName]) {
const parent = getParent(document, node);
const keyNode = parent && isPair(parent) && (parent.key as Node);
const [offset, length] = toOffsetLength(node.range);
const location = keyNode ? { offset, length } : { offset, length: 1 };
validationResult.problems.push({
location: location,
severity: DiagnosticSeverity.Warning,
message: getWarningMessage(ProblemType.missingRequiredPropWarning, [propertyName]),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
problemArgs: [propertyName],
problemType: ProblemType.missingRequiredPropWarning,
});
}
}
}
const propertyProcessed = (prop: string): void => {
let index = unprocessedProperties.indexOf(prop);
while (index >= 0) {
unprocessedProperties.splice(index, 1);
index = unprocessedProperties.indexOf(prop);
}
};
if (schema.properties) {
for (const propertyName of Object.keys(schema.properties)) {
propertyProcessed(propertyName);
const propertySchema = schema.properties[propertyName];
const child = seenKeys[propertyName];
if (child) {
if (isBoolean(propertySchema)) {
if (!propertySchema) {
const propertyNode = getParent(document, child) as Pair;
const [offset, length] = toOffsetLength((propertyNode.key as Node).range);
validationResult.problems.push({
location: {
offset,
length,
},
severity: DiagnosticSeverity.Warning,
message:
schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
propertySchema.url = schema.url ?? originalSchema.url;
const propertyValidationResult = new ValidationResult(isKubernetes);
validate(child, document, propertySchema, schema, propertyValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(propertyValidationResult);
validationResult.mergeEnumValues(propertyValidationResult);
}
}
}
}
if (schema.patternProperties) {
for (const propertyPattern of Object.keys(schema.patternProperties)) {
const regex = new RegExp(propertyPattern, 'u');
for (const propertyName of unprocessedProperties.slice(0)) {
if (regex.test(propertyName)) {
propertyProcessed(propertyName);
const child = seenKeys[propertyName];
if (child) {
const propertySchema = schema.patternProperties[propertyPattern];
if (isBoolean(propertySchema)) {
if (!propertySchema) {
const propertyNode = getParent(document, child) as Pair;
const [offset, length] = toOffsetLength((propertyNode.key as Node).range);
validationResult.problems.push({
location: {
offset,
length,
},
severity: DiagnosticSeverity.Warning,
message:
schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
} else {
validationResult.propertiesMatches++;
validationResult.propertiesValueMatches++;
}
} else {
const propertyValidationResult = new ValidationResult(isKubernetes);
validate(child, document, propertySchema, schema, propertyValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(propertyValidationResult);
validationResult.mergeEnumValues(propertyValidationResult);
}
}
}
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const propertyName of unprocessedProperties) {
const child = seenKeys[propertyName];
if (child) {
const propertyValidationResult = new ValidationResult(isKubernetes);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validate(child, document, <any>schema.additionalProperties, schema, propertyValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(propertyValidationResult);
validationResult.mergeEnumValues(propertyValidationResult);
}
}
} else if (
schema.additionalProperties === false ||
(schema.type === 'object' && schema.additionalProperties === undefined && options.disableAdditionalProperties === true)
) {
if (unprocessedProperties.length > 0) {
for (const propertyName of unprocessedProperties) {
const child = seenKeys[propertyName];
if (child) {
let propertyNode: Node = null;
if (!isPair(child)) {
propertyNode = getParent(document, child) as Node;
if (isMap(propertyNode)) {
propertyNode = propertyNode.items[0];
}
} else {
propertyNode = child;
}
const [offset, length] = toOffsetLength(((propertyNode as Pair).key as Node).range);
validationResult.problems.push({
location: {
offset,
length,
},
severity: DiagnosticSeverity.Warning,
message:
schema.errorMessage || localize('DisallowedExtraPropWarning', 'Property {0} is not allowed.', propertyName),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
}
}
if (isNumber(schema.maxProperties)) {
if (node.items.length > schema.maxProperties) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize('MaxPropWarning', 'Object has more properties than limit of {0}.', schema.maxProperties),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
if (isNumber(schema.minProperties)) {
if (node.items.length < schema.minProperties) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize(
'MinPropWarning',
'Object has fewer properties than the required number of {0}',
schema.minProperties
),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
}
}
if (schema.dependencies) {
for (const key of Object.keys(schema.dependencies)) {
const prop = seenKeys[key];
if (prop) {
const propertyDep = schema.dependencies[key];
if (Array.isArray(propertyDep)) {
for (const requiredProp of propertyDep) {
if (!seenKeys[requiredProp]) {
const [offset, length] = toOffsetLength(node.range);
validationResult.problems.push({
location: { offset, length },
severity: DiagnosticSeverity.Warning,
message: localize(
'RequiredDependentPropWarning',
'Object is missing property {0} required by property {1}.',
requiredProp,
key
),
source: getSchemaSource(schema, originalSchema),
schemaUri: getSchemaUri(schema, originalSchema),
});
} else {
validationResult.propertiesValueMatches++;
}
}
} else {
const propertySchema = asSchema(propertyDep);
if (propertySchema) {
const propertyValidationResult = new ValidationResult(isKubernetes);
validate(node, document, propertySchema, schema, propertyValidationResult, matchingSchemas, options);
validationResult.mergePropertyMatch(propertyValidationResult);
validationResult.mergeEnumValues(propertyValidationResult);
}
}
}
}
}
const propertyNames = asSchema(schema.propertyNames);
if (propertyNames) {
for (const f of node.items) {
const key = f.key;
if (key) {
validate(key as Node, document, propertyNames, schema, validationResult, NoOpSchemaCollector.instance, options);
}
}
}
}
//Alternative comparison is specifically used by the kubernetes/openshift schema but may lead to better results then genericComparison depending on the schema
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function alternativeComparison(subValidationResult, bestMatch, subSchema, subMatchingSchemas): any {
const compareResult = subValidationResult.compareKubernetes(bestMatch.validationResult);
if (compareResult > 0) {
// our node is the best matching so far
bestMatch = {
schema: subSchema,
validationResult: subValidationResult,
matchingSchemas: subMatchingSchemas,
};
} else if (compareResult === 0) {
// there's already a best matching but we are as good
bestMatch.matchingSchemas.merge(subMatchingSchemas);
bestMatch.validationResult.mergeEnumValues(subValidationResult);
}
return bestMatch;
}
//genericComparison tries to find the best matching schema using a generic comparison
function genericComparison(
maxOneMatch,
subValidationResult: ValidationResult,
bestMatch: {
schema: JSONSchema;
validationResult: ValidationResult;
matchingSchemas: SchemaCollector;
},
subSchema,
subMatchingSchemas
): {
schema: JSONSchema;
validationResult: ValidationResult;
matchingSchemas: SchemaCollector;
} {
if (!maxOneMatch && !subValidationResult.hasProblems() && !bestMatch.validationResult.hasProblems()) {
// no errors, both are equally good matches
bestMatch.matchingSchemas.merge(subMatchingSchemas);
bestMatch.validationResult.propertiesMatches += subValidationResult.propertiesMatches;
bestMatch.validationResult.propertiesValueMatches += subValidationResult.propertiesValueMatches;
} else {
const compareResult = subValidationResult.compareGeneric(bestMatch.validationResult);
if (compareResult > 0) {
// our node is the best matching so far
bestMatch = {
schema: subSchema,
validationResult: subValidationResult,
matchingSchemas: subMatchingSchemas,
};
} else if (compareResult === 0) {
// there's already a best matching but we are as good
bestMatch.matchingSchemas.merge(subMatchingSchemas);
bestMatch.validationResult.mergeEnumValues(subValidationResult);
bestMatch.validationResult.mergeWarningGeneric(subValidationResult, [
ProblemType.missingRequiredPropWarning,
ProblemType.typeMismatchWarning,
ProblemType.constWarning,
]);
}
}
return bestMatch;
}
}
export function asSchema(schema: JSONSchemaRef): JSONSchema {
if (isBoolean(schema)) {
return schema ? {} : { not: {} };
}
return schema;
}
function getSchemaSource(schema: JSONSchema, originalSchema: JSONSchema): string | undefined {
if (schema) {
let label: string;
if (schema.title) {
label = schema.title;
} else if (originalSchema.title) {
label = originalSchema.title;
} else {
const uriString = schema.url ?? originalSchema.url;
if (uriString) {
const url = URI.parse(uriString);
if (url.scheme === 'file') {
label = url.fsPath;
}
label = url.toString();
}
}
if (label) {
return `${YAML_SCHEMA_PREFIX}${label}`;
}
}
return YAML_SOURCE;
}
function getSchemaUri(schema: JSONSchema, originalSchema: JSONSchema): string[] {
const uriString = schema.url ?? originalSchema.url;
return uriString ? [uriString] : [];
}
function getWarningMessage(problemType: ProblemType, args: string[]): string {
return localize(problemType, ProblemTypeMessages[problemType], args.join(' | '));
} | 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 jQuery UI plugin that wraps Google Maps.
*/
namespace VRS
{
/*
* Global options
*/
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.mapGoogleMapHttpUrl = VRS.globalOptions.mapGoogleMapHttpUrl || 'http://maps.google.com/maps/api/js'; // The HTTP URL for Google Maps
VRS.globalOptions.mapGoogleMapHttpsUrl = VRS.globalOptions.mapGoogleMapHttpsUrl || 'https://maps.google.com/maps/api/js'; // The HTTPS URL for Google Maps
VRS.globalOptions.mapGoogleMapTimeout = VRS.globalOptions.mapGoogleMapTimeout || 30000; // The number of milliseconds to wait before giving up and assuming that the maps aren't going to load.
VRS.globalOptions.mapGoogleMapUseHttps = VRS.globalOptions.mapGoogleMapUseHttps !== undefined ? VRS.globalOptions.mapGoogleMapUseHttps : true; // True to load the HTTPS version, false to load the HTTP. Note that Chrome on iOS fails if it's not HTTPS!
VRS.globalOptions.mapShowStreetView = VRS.globalOptions.mapShowStreetView !== undefined ? VRS.globalOptions.mapShowStreetView : false; // True if the StreetView control is to be shown on Google Maps.
VRS.globalOptions.mapScrollWheelActive = VRS.globalOptions.mapScrollWheelActive !== undefined ? VRS.globalOptions.mapScrollWheelActive : true; // True if the scroll wheel zooms the map.
VRS.globalOptions.mapDraggable = VRS.globalOptions.mapDraggable !== undefined ? VRS.globalOptions.mapDraggable : true; // True if the user can move the map.
VRS.globalOptions.mapShowPointsOfInterest = VRS.globalOptions.mapShowPointsOfInterest !== undefined ? VRS.globalOptions.mapShowPointsOfInterest : false; // True if points of interest are to be shown on Google Maps.
VRS.globalOptions.mapShowScaleControl = VRS.globalOptions.mapShowScaleControl !== undefined ? VRS.globalOptions.mapShowScaleControl : true; // True if the map should display a scale on it.
VRS.globalOptions.mapShowHighContrastStyle = VRS.globalOptions.mapShowHighContrastStyle !== undefined ? VRS.globalOptions.mapShowHighContrastStyle : true; // True if the high-contrast map style is to be shown.
VRS.globalOptions.mapHighContrastMapStyle = VRS.globalOptions.mapHighContrastMapStyle !== undefined ? VRS.globalOptions.mapHighContrastMapStyle : <google.maps.MapTypeStyle[]>[ // The Google map styles to use for the high contrast map.
{
featureType: 'poi',
stylers: [
{ visibility: 'off' }
]
},{
featureType: 'landscape',
stylers: [
{ saturation: -70 },
{ lightness: -30 },
{ gamma: 0.80 }
]
},{
featureType: 'road',
stylers: [
{ visibility: 'simplified' },
{ weight: 0.4 },
{ saturation: -70 },
{ lightness: -30 },
{ gamma: 0.80 }
]
},{
featureType: 'road',
elementType: 'labels',
stylers: [
{ visibility: 'simplified' },
{ saturation: -46 },
{ gamma: 1.82 }
]
},{
featureType: 'administrative',
stylers: [
{ weight: 1 }
]
},{
featureType: 'administrative',
elementType: 'labels',
stylers: [
{ saturation: -100 },
{ weight: 0.1 },
{ lightness: -60 },
{ gamma: 2.0 }
]
},{
featureType: 'water',
stylers: [
{ saturation: -72 },
{ lightness: -25 }
]
},{
featureType: 'administrative.locality',
stylers: [
{ weight: 0.1 }
]
},{
featureType: 'administrative.province',
stylers: [
{ lightness: -43 }
]
},{
"featureType": "transit.line",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "transit.station.bus",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "transit.station.rail",
"stylers": [
{ "visibility": "off" }
]
}
];
/**
* An object that can convert to and from VRS map objects and Google map object.
*/
export class GoogleMapUtilities
{
/**
* The ID *and* the label of the high contrast map type. We cannot refer to the VRS.$$ identifier directly when
* translating map types because we need to use the one that Google knows about, not the one for the currently
* selected language. The first time the map type gets translated this gets filled in with VRS.$$.HighContrastMap.
*/
private _HighContrastMapTypeName: string = null;
/**
* Converts from a Google latLng object to a VRS latLng object.
*/
fromGoogleLatLng(latLng: google.maps.LatLng) : ILatLng
{
return latLng ? { lat: latLng.lat(), lng: latLng.lng() } : undefined;
}
/**
* Converts from a VRS latLng to a Google latLng.
*/
toGoogleLatLng(latLng: ILatLng) : google.maps.LatLng
{
return latLng ? new google.maps.LatLng(latLng.lat, latLng.lng) : undefined;
}
/**
* Converts from a Google point to a VRS point.
*/
fromGooglePoint(point: google.maps.Point) : IPoint
{
return point ? { x: point.x, y: point.y } : undefined;
}
/**
* Converts from a VRS point to a Google point
*/
toGooglePoint(point: IPoint) : google.maps.Point
{
return point ? new google.maps.Point(point.x, point.y) : undefined;
}
/**
* Converts from a Google Size to a VRS size.
*/
fromGoogleSize(size: google.maps.Size) : ISize
{
return size ? { width: size.width, height: size.height } : undefined;
}
/**
* Converts from a VRS size to a Google size.
*/
toGoogleSize(size: ISize) : google.maps.Size
{
return size ? new google.maps.Size(size.width, size.height) : undefined;
}
/**
* Converts from a Google latLngBounds to a VRS bounds.
*/
fromGoogleLatLngBounds(latLngBounds: google.maps.LatLngBounds) : IBounds
{
if(!latLngBounds) return null;
var northEast = latLngBounds.getNorthEast();
var southWest = latLngBounds.getSouthWest();
return {
tlLat: northEast.lat(),
tlLng: southWest.lng(),
brLat: southWest.lat(),
brLng: northEast.lng()
};
}
/**
* Converts from a VRS bounds to a Google LatLngBounds.
*/
toGoogleLatLngBounds(bounds: IBounds) : google.maps.LatLngBounds
{
return bounds ? new google.maps.LatLngBounds(
new google.maps.LatLng(bounds.brLat, bounds.tlLng),
new google.maps.LatLng(bounds.tlLat, bounds.brLng)
) : null;
}
/**
* Converts from a Google map control style to a VRS one.
*/
fromGoogleMapControlStyle(mapControlStyle: google.maps.MapTypeControlStyle) : VRS.MapControlStyleEnum
{
if(!mapControlStyle) return null;
switch(mapControlStyle) {
case google.maps.MapTypeControlStyle.DEFAULT: return VRS.MapControlStyle.Default;
case google.maps.MapTypeControlStyle.DROPDOWN_MENU: return VRS.MapControlStyle.DropdownMenu;
case google.maps.MapTypeControlStyle.HORIZONTAL_BAR: return VRS.MapControlStyle.HorizontalBar;
default: throw 'Not implemented';
}
}
/**
* Converts from a VRS map type control style to a Google one.
*/
toGoogleMapControlStyle(mapControlStyle: VRS.MapControlStyleEnum) : google.maps.MapTypeControlStyle
{
if(!mapControlStyle) return null;
switch(mapControlStyle) {
case VRS.MapControlStyle.Default: return google.maps.MapTypeControlStyle.DEFAULT;
case VRS.MapControlStyle.DropdownMenu: return google.maps.MapTypeControlStyle.DROPDOWN_MENU;
case VRS.MapControlStyle.HorizontalBar: return google.maps.MapTypeControlStyle.HORIZONTAL_BAR;
default: throw 'Not implemented';
}
}
/**
* Converts from a Google map type to a VRS map type.
*/
fromGoogleMapType(mapType: google.maps.MapTypeId | string) : VRS.MapTypeEnum
{
if(!mapType) return null;
if(!this._HighContrastMapTypeName) this._HighContrastMapTypeName = VRS.$$.HighContrastMap;
switch(mapType) {
case google.maps.MapTypeId.HYBRID: return VRS.MapType.Hybrid;
case google.maps.MapTypeId.ROADMAP: return VRS.MapType.RoadMap;
case google.maps.MapTypeId.SATELLITE: return VRS.MapType.Satellite;
case google.maps.MapTypeId.TERRAIN: return VRS.MapType.Terrain;
case this._HighContrastMapTypeName: return VRS.MapType.HighContrast;
default: throw 'Not implemented';
}
}
/**
* Converts from a VRS map type to a Google map type.
*/
toGoogleMapType(mapType: VRS.MapTypeEnum, suppressException: boolean = false) : google.maps.MapTypeId | string
{
if(!mapType) return null;
if(!this._HighContrastMapTypeName) this._HighContrastMapTypeName = VRS.$$.HighContrastMap;
switch(mapType) {
case VRS.MapType.Hybrid: return google.maps.MapTypeId.HYBRID;
case VRS.MapType.RoadMap: return google.maps.MapTypeId.ROADMAP;
case VRS.MapType.Satellite: return google.maps.MapTypeId.SATELLITE;
case VRS.MapType.Terrain: return google.maps.MapTypeId.TERRAIN;
case VRS.MapType.HighContrast: return this._HighContrastMapTypeName;
default:
if(suppressException) return null;
throw 'Not implemented';
}
}
/**
* Converts from a Google icon to a VRS map icon.
*/
fromGoogleIcon(icon: google.maps.Icon) : IMapIcon
{
if(!icon) return null;
else return new MapIcon(
icon.url,
this.fromGoogleSize(icon.size),
this.fromGooglePoint(icon.anchor),
this.fromGooglePoint(icon.origin),
this.fromGoogleSize(icon.scaledSize)
);
}
/**
* Converts from a VRS map icon to a Google icon.
*/
toGoogleIcon(icon: IMapIcon | string) : google.maps.Icon
{
if(!icon) return null;
if(!(<IMapIcon>icon).url) return <any>icon;
var result: google.maps.Icon = {};
if((<IMapIcon>icon).anchor) result.anchor = this.toGooglePoint((<IMapIcon>icon).anchor);
if((<IMapIcon>icon).origin) result.origin = this.toGooglePoint((<IMapIcon>icon).origin);
if((<IMapIcon>icon).scaledSize) result.scaledSize = this.toGoogleSize((<IMapIcon>icon).scaledSize);
if((<IMapIcon>icon).size) result.size = this.toGoogleSize((<IMapIcon>icon).size);
if((<IMapIcon>icon).url) result.url = (<IMapIcon>icon).url;
return result;
}
/**
* Converts from a Google LatLngMVCArray to an VRS array of latLng objects.
*/
fromGoogleLatLngMVCArray(latLngMVCArray: google.maps.MVCArray) : ILatLng[]
{
if(!latLngMVCArray) return null;
var result: ILatLng[] = [];
var length = latLngMVCArray.getLength();
for(var i = 0;i < length;++i) {
result.push(this.fromGoogleLatLng(latLngMVCArray.getAt(i)));
}
return result;
}
/**
* Converts from a VRS array of latLng objects to a Google LatLngMVCArray.
*/
toGoogleLatLngMVCArray(latLngArray: ILatLng[]) : google.maps.MVCArray
{
if(!latLngArray) return null;
var googleLatLngArray: google.maps.LatLng[] = [];
var length = latLngArray.length;
for(var i = 0;i < length;++i) {
googleLatLngArray.push(this.toGoogleLatLng(latLngArray[i]));
}
return new google.maps.MVCArray(googleLatLngArray);
}
/**
* Converts from a Google MVCArray of Google LatLngMVCArrays to an array of
* an array of VRS latLng objects.
*/
fromGoogleLatLngMVCArrayArray(latLngMVCArrayArray: google.maps.MVCArray) : ILatLng[][]
{
if(!latLngMVCArrayArray) return null;
var result: ILatLng[][] = [];
var length = latLngMVCArrayArray.getLength();
for(var i = 0;i < length;++i) {
result.push(this.fromGoogleLatLngMVCArray(latLngMVCArrayArray[i]));
}
return result;
}
/**
* Converts from an array of an array of VRS_LAT_LNG objects to a Google MVCArray
* of a Google MVCArray of Google latLng objects.
*/
toGoogleLatLngMVCArrayArray(latLngArrayArray: ILatLng[][]) : google.maps.MVCArray
{
if(!latLngArrayArray) return null;
var result: google.maps.MVCArray[] = [];
var length = latLngArrayArray.length;
for(var i = 0;i < length;++i) {
result.push(this.toGoogleLatLngMVCArray(latLngArrayArray[i]));
}
return new google.maps.MVCArray(result);
}
/**
* Converts from a Google control position to a VRS.MapPosition.
*/
fromGoogleControlPosition(controlPosition: google.maps.ControlPosition) : MapPositionEnum
{
switch(controlPosition) {
case google.maps.ControlPosition.BOTTOM_CENTER: return VRS.MapPosition.BottomCentre;
case google.maps.ControlPosition.BOTTOM_LEFT: return VRS.MapPosition.BottomLeft;
case google.maps.ControlPosition.BOTTOM_RIGHT: return VRS.MapPosition.BottomRight;
case google.maps.ControlPosition.LEFT_BOTTOM: return VRS.MapPosition.LeftBottom;
case google.maps.ControlPosition.LEFT_CENTER: return VRS.MapPosition.LeftCentre;
case google.maps.ControlPosition.LEFT_TOP: return VRS.MapPosition.LeftTop;
case google.maps.ControlPosition.RIGHT_BOTTOM: return VRS.MapPosition.RightBottom;
case google.maps.ControlPosition.RIGHT_CENTER: return VRS.MapPosition.RightCentre;
case google.maps.ControlPosition.RIGHT_TOP: return VRS.MapPosition.RightTop;
case google.maps.ControlPosition.TOP_CENTER: return VRS.MapPosition.TopCentre;
case google.maps.ControlPosition.TOP_LEFT: return VRS.MapPosition.TopLeft;
case google.maps.ControlPosition.TOP_RIGHT: return VRS.MapPosition.TopRight;
default: throw 'Unknown control position ' + controlPosition;
}
}
/**
* Converts from a VRS.MapPosition to a Google control position.
*/
toGoogleControlPosition(mapPosition: MapPositionEnum) : google.maps.ControlPosition
{
switch(mapPosition) {
case VRS.MapPosition.BottomCentre: return google.maps.ControlPosition.BOTTOM_CENTER;
case VRS.MapPosition.BottomLeft: return google.maps.ControlPosition.BOTTOM_LEFT;
case VRS.MapPosition.BottomRight: return google.maps.ControlPosition.BOTTOM_RIGHT;
case VRS.MapPosition.LeftBottom: return google.maps.ControlPosition.LEFT_BOTTOM;
case VRS.MapPosition.LeftCentre: return google.maps.ControlPosition.LEFT_CENTER;
case VRS.MapPosition.LeftTop: return google.maps.ControlPosition.LEFT_TOP;
case VRS.MapPosition.RightBottom: return google.maps.ControlPosition.RIGHT_BOTTOM;
case VRS.MapPosition.RightCentre: return google.maps.ControlPosition.RIGHT_CENTER;
case VRS.MapPosition.RightTop: return google.maps.ControlPosition.RIGHT_TOP;
case VRS.MapPosition.TopCentre: return google.maps.ControlPosition.TOP_CENTER;
case VRS.MapPosition.TopLeft: return google.maps.ControlPosition.TOP_LEFT;
case VRS.MapPosition.TopRight: return google.maps.ControlPosition.TOP_RIGHT;
default: throw 'Unknown map position ' + mapPosition;
}
}
}
export var googleMapUtilities = new VRS.GoogleMapUtilities();
/**
* An abstracted wrapper around an object that represents a map's native marker.
*/
class MapMarker implements IMapMarker
{
/**
* The identifier of the marker. Left as a field to speed things up a bit.
*/
id: string|number;
/**
* The native marker object. Leave this alone.
*/
marker: google.maps.Marker;
/**
* True if the native marker is a Google Maps MarkerWithLabel.
*/
isMarkerWithLabel: boolean;
/**
* The object that the marker has been tagged with. Not used by the plugin.
*/
tag: any;
/**
* An array of objects describing the events that have been hooked on the marker.
*/
nativeListeners: google.maps.MapsEventListener[] = [];
/**
* Creates a new object.
* @param {string|number} id The identifier of the marker
* @param {google.maps.Marker} nativeMarker The native map marker handle to wrap.
* @param {boolean} isMarkerWithLabel Indicates that the native marker is a Google Maps MarkerWithLabel.
* @param {*} tag An object to carry around with the marker. No meaning is attached to the tag.
*/
constructor(id: string|number, nativeMarker: google.maps.Marker, isMarkerWithLabel: boolean, tag: any)
{
this.id = id;
this.marker = nativeMarker;
this.isMarkerWithLabel = isMarkerWithLabel;
this.tag = tag;
}
/**
* Returns true if the marker can be dragged.
*/
getDraggable() : boolean
{
return this.marker.getDraggable();
}
/**
* Sets a value indicating whether the marker can be dragged.
*/
setDraggable(draggable: boolean)
{
this.marker.setDraggable(draggable);
}
/**
* Returns the icon for the marker.
*/
getIcon() : IMapIcon
{
return VRS.googleMapUtilities.fromGoogleIcon(this.marker.getIcon());
}
/**
* Sets the icon for the marker.
*/
setIcon(icon: IMapIcon)
{
this.marker.setIcon(VRS.googleMapUtilities.toGoogleIcon(icon));
}
/**
* Gets the coordinates of the marker.
*/
getPosition() : ILatLng
{
return VRS.googleMapUtilities.fromGoogleLatLng(this.marker.getPosition());
}
/**
* Sets the coordinates for the marker.
*/
setPosition(position: ILatLng)
{
this.marker.setPosition(VRS.googleMapUtilities.toGoogleLatLng(position));
}
/**
* Gets the tooltip for the marker.
*/
getTooltip() : string
{
return this.marker.getTitle();
}
/**
* Sets the tooltip for the marker.
*/
setTooltip(tooltip: string)
{
this.marker.setTitle(tooltip);
}
/**
* Gets a value indicating that the marker is visible.
*/
getVisible() : boolean
{
return this.marker.getVisible();
}
/**
* Sets a value indicating whether the marker is visible.
*/
setVisible(visible: boolean)
{
this.marker.setVisible(visible);
}
/**
* Gets the z-index of the marker.
*/
getZIndex() : number
{
return this.marker.getZIndex();
}
/**
* Sets the z-index of the marker.
*/
setZIndex(zIndex: number)
{
this.marker.setZIndex(zIndex);
}
/**
* Returns true if the marker was created with useMarkerWithLabel and the label is visible.
* Note that this is not a part of the marker interface.
*/
getLabelVisible() : boolean
{
return this.isMarkerWithLabel ? this.marker.get('labelVisible') : false;
}
/**
* Sets the visibility of a marker's label. Only works on markers that have been created with useMarkerWithLabel.
* Note that this is not a part of the marker interface.
*/
setLabelVisible(visible: boolean)
{
if(this.isMarkerWithLabel) this.marker.set('labelVisible', visible);
}
/**
* Sets the label content. Only works on markers that have been created with useMarkerWithLabel.
*/
getLabelContent()
{
return this.isMarkerWithLabel ? this.marker.get('labelContent') : null;
}
/**
* Sets the content of a marker's label. Only works on markers that have been created with useMarkerWithLabel.
* Note that this is not a part of the marker interface.
*/
setLabelContent(content: string)
{
if(this.isMarkerWithLabel) this.marker.set('labelContent', content);
}
/**
* Gets the label anchor. Only works on markers that have been created with useMarkerWithLabel.
*/
getLabelAnchor()
{
return this.isMarkerWithLabel ? VRS.googleMapUtilities.fromGooglePoint(this.marker.get('labelAnchor')) : null;
}
/**
* Sets the anchor for a marker's label. Only works on markers that have been created with useMarkerWithLabel.
* Note that this is not a part of the marker interface.
*/
setLabelAnchor(anchor: IPoint)
{
if(this.isMarkerWithLabel) this.marker.set('labelAnchor', VRS.googleMapUtilities.toGooglePoint(anchor));
}
}
/**
* An object that can cluster map markers together.
*/
class MapMarkerClusterer implements IMapMarkerClusterer
{
constructor(private map: MapPlugin, private nativeMarkerClusterer: MarkerClusterer)
{
}
getNative()
{
return this.nativeMarkerClusterer;
}
getNativeType()
{
return 'GoogleMaps';
}
getMaxZoom()
{
return this.nativeMarkerClusterer.getMaxZoom();
}
setMaxZoom(maxZoom: number)
{
this.nativeMarkerClusterer.setMaxZoom(maxZoom);
}
addMarker(marker: IMapMarker, noRepaint?: boolean)
{
this.nativeMarkerClusterer.addMarker((<MapMarker>marker).marker, noRepaint);
}
addMarkers(markers: IMapMarker[], noRepaint?: boolean)
{
this.nativeMarkerClusterer.addMarkers(this.castArrayOfMarkers(markers), noRepaint);
}
removeMarker(marker: IMapMarker, noRepaint?: boolean)
{
this.nativeMarkerClusterer.removeMarker((<MapMarker>marker).marker, noRepaint, true);
}
removeMarkers(markers: IMapMarker[], noRepaint?: boolean)
{
this.nativeMarkerClusterer.removeMarkers(this.castArrayOfMarkers(markers), noRepaint, true);
}
repaint()
{
this.nativeMarkerClusterer.repaint();
}
private castArrayOfMarkers(markers: IMapMarker[]) : google.maps.Marker[]
{
var result: google.maps.Marker[] = [];
var length = markers ? markers.length : 0;
for(var i = 0;i < length;++i) {
result.push((<MapMarker>markers[i]).marker);
}
return result;
}
}
/**
* Describes a polygon on a map.
*/
class MapPolygon implements IMapPolygon
{
/**
* The VRS ID for the polygon.
*/
id: string | number;
/**
* The native polygon.
*/
polygon: google.maps.Polygon;
/**
* The application's tag attached to the polygon.
*/
tag: any;
constructor(id: string | number, nativePolygon: google.maps.Polygon, tag: any, options: IMapPolygonSettings)
{
this.id = id;
this.polygon = nativePolygon;
this.tag = tag;
this._Clickable = options.clickable;
this._FillColour = options.fillColour;
this._FillOpacity = options.fillOpacity;
this._StrokeColour = options.strokeColour;
this._StrokeOpacity = options.strokeOpacity;
this._StrokeWeight = options.strokeWeight;
this._ZIndex = options.zIndex;
}
/**
* Gets a value indicating that the polygon is draggable.
*/
getDraggable() : boolean
{
return this.polygon.getDraggable();
}
/**
* Sets a value indicating whether the polygon is draggable.
*/
setDraggable(draggable: boolean)
{
this.polygon.setDraggable(draggable);
}
/**
* Gets a value indicating whether the polygon can be changed by the user.
*/
getEditable() : boolean
{
return this.polygon.getEditable();
}
/**
* Sets a value indicating whether the user can change the polygon.
*/
setEditable(editable: boolean)
{
this.polygon.setEditable(editable);
}
/**
* Gets a value indicating that the polygon is visible.
*/
getVisible() : boolean
{
return this.polygon.getVisible();
}
/**
* Sets a value indicating whether the polygon is visible.
*/
setVisible(visible: boolean)
{
this.polygon.setVisible(visible);
}
/**
* Gets the first path.
*/
getFirstPath() : ILatLng[]
{
return VRS.googleMapUtilities.fromGoogleLatLngMVCArray(this.polygon.getPath());
}
/**
* Sets the first path.
*/
setFirstPath(path: ILatLng[])
{
this.polygon.setPath(VRS.googleMapUtilities.toGoogleLatLngMVCArray(path));
}
/**
* Gets an array of every path array.
*/
getPaths() : ILatLng[][]
{
return VRS.googleMapUtilities.fromGoogleLatLngMVCArrayArray(this.polygon.getPaths());
}
/**
* Sets an array of every path array.
*/
setPaths(paths: ILatLng[][])
{
this.polygon.setPaths(VRS.googleMapUtilities.toGoogleLatLngMVCArrayArray(paths));
}
private _Clickable: boolean;
/**
* Gets a value indicating whether the polygon handles mouse events.
*/
getClickable() : boolean
{
return this._Clickable;
}
/**
* Sets a value that indicates whether the polygon handles mouse events.
*/
setClickable(value: boolean)
{
if(value !== this._Clickable) {
this._Clickable = value;
this.polygon.setOptions({ clickable: value });
}
}
private _FillColour: string;
/**
* Gets the CSS colour of the fill area.
*/
getFillColour() : string
{
return this._FillColour;
}
/**
* Sets the CSS colour of the fill area.
*/
setFillColour(value: string)
{
if(value !== this._FillColour) {
this._FillColour = value;
this.polygon.setOptions({ fillColor: value });
}
}
private _FillOpacity: number;
/**
* Gets the opacity of the fill area.
*/
getFillOpacity() : number
{
return this._FillOpacity;
}
/**
* Sets the opacity of the fill area (between 0 and 1).
*/
setFillOpacity(value: number)
{
if(value !== this._FillOpacity) {
this._FillOpacity = value;
this.polygon.setOptions({ fillOpacity: value });
}
}
private _StrokeColour: string;
/**
* Gets the CSS colour of the stroke line.
*/
getStrokeColour() : string
{
return this._StrokeColour;
}
/**
* Sets the CSS colour of the stroke line.
*/
setStrokeColour(value: string)
{
if(value !== this._StrokeColour) {
this._StrokeColour = value;
this.polygon.setOptions({ strokeColor: value });
}
}
private _StrokeOpacity: number;
/**
* Gets the opacity of the stroke line.
*/
getStrokeOpacity() : number
{
return this._StrokeOpacity;
}
/**
* Sets the opacity of the stroke line (between 0 and 1).
*/
setStrokeOpacity(value: number)
{
if(value !== this._StrokeOpacity) {
this._StrokeOpacity = value;
this.polygon.setOptions({ strokeOpacity: value });
}
}
private _StrokeWeight: number;
/**
* Gets the weight of the stroke line in pixels.
*/
getStrokeWeight() : number
{
return this._StrokeWeight;
}
/**
* Sets the weight of the stroke line in pixels.
*/
setStrokeWeight(value: number)
{
if(value !== this._StrokeWeight) {
this._StrokeWeight = value;
this.polygon.setOptions({ strokeWeight: value });
}
}
private _ZIndex: number;
/**
* Gets the z-index of the polygon.
*/
getZIndex() : number
{
return this._ZIndex;
}
/**
* Sets the z-index of the polygon.
*/
setZIndex(value: number)
{
if(value !== this._ZIndex) {
this._ZIndex = value;
this.polygon.setOptions({ zIndex: value });
}
}
}
/**
* An object that wraps a map's native polyline object.
*/
class MapPolyline implements IMapPolyline
{
id: string | number;
polyline: google.maps.Polyline;
tag: any;
constructor(id: string | number, nativePolyline: google.maps.Polyline, tag: any, options: IMapPolylineSettings)
{
this.id = id;
this.polyline = nativePolyline;
this.tag = tag;
this._StrokeColour = options.strokeColour;
this._StrokeOpacity = options.strokeOpacity;
this._StrokeWeight = options.strokeWeight;
}
/**
* Gets a value indicating that the line is draggable.
*/
getDraggable() : boolean
{
return this.polyline.getDraggable();
}
/**
* Sets a value indicating whether the line is draggable.
*/
setDraggable(draggable: boolean)
{
this.polyline.setDraggable(draggable);
}
/**
* Gets a value indicating whether the line can be changed by the user.
*/
getEditable() : boolean
{
return this.polyline.getEditable();
}
/**
* Sets a value indicating whether the user can change the line.
*/
setEditable(editable: boolean)
{
this.polyline.setEditable(editable);
}
/**
* Gets a value indicating whether the line is visible.
*/
getVisible() : boolean
{
return this.polyline.getVisible();
}
/**
* Sets a value indicating whether the line is visible.
*/
setVisible(visible: boolean)
{
this.polyline.setVisible(visible);
}
private _StrokeColour: string;
/**
* Gets the CSS colour of the line.
*/
getStrokeColour() : string
{
return this._StrokeColour;
}
/**
* Sets the CSS colour of the line.
*/
setStrokeColour(value: string)
{
if(value !== this._StrokeColour) {
this._StrokeColour = value;
this.polyline.setOptions({ strokeColor: value });
}
}
private _StrokeOpacity: number;
/**
* Gets the opacity of the line.
*/
getStrokeOpacity() : number
{
return this._StrokeOpacity;
}
/**
* Sets the opacity of the line (between 0 and 1).
*/
setStrokeOpacity(value: number)
{
if(value !== this._StrokeOpacity) {
this._StrokeOpacity = value;
this.polyline.setOptions({ strokeOpacity: value });
}
}
private _StrokeWeight: number;
/**
* Gets the weight of the line in pixels.
*/
getStrokeWeight() : number
{
return this._StrokeWeight;
}
/**
* Sets the weight of the line in pixels.
*/
setStrokeWeight(value: number)
{
if(value !== this._StrokeWeight) {
this._StrokeWeight = value;
this.polyline.setOptions({ strokeWeight: value });
}
}
/**
* Gets the path for the polyline.
*/
getPath() : ILatLng[]
{
var result = VRS.googleMapUtilities.fromGoogleLatLngMVCArray(this.polyline.getPath());
return result || [];
}
/**
* Sets the path for the polyline.
*/
setPath(path: ILatLng[])
{
var nativePath = VRS.googleMapUtilities.toGoogleLatLngMVCArray(path);
this.polyline.setPath(nativePath);
}
/**
* Returns the first point on the path or null if the path is empty.
*/
getFirstLatLng() : ILatLng
{
var result = null;
var nativePath = this.polyline.getPath();
if(nativePath.getLength()) result = VRS.googleMapUtilities.fromGoogleLatLng(nativePath.getAt(0));
return result;
}
/**
* Returns the last point on the path or null if the path is empty.
*/
getLastLatLng() : ILatLng
{
var result = null;
var nativePath = this.polyline.getPath();
var length = nativePath.getLength();
if(length) result = VRS.googleMapUtilities.fromGoogleLatLng(nativePath.getAt(length - 1));
return result;
}
}
/**
* An object that wraps a map's native circle object.
* @constructor
*/
class MapCircle implements IMapCircle
{
id: string | number;
circle: google.maps.Circle;
tag: any;
/**
* Creates a new object.
* @param {string|number} id The unique identifier of the circle object.
* @param {google.maps.Circle} nativeCircle The native object that is being wrapped.
* @param {*} tag An object attached to the circle.
* @param {IMapCircleSettings} options The options used when the circle was created.
*/
constructor(id: string | number, nativeCircle: google.maps.Circle, tag: any, options: IMapCircleSettings)
{
this.id = id;
this.circle = nativeCircle;
this.tag = tag;
this._FillOpacity = options.fillOpacity;
this._FillColour = options.fillColor;
this._StrokeOpacity = options.strokeOpacity;
this._StrokeColour = options.strokeColor;
this._StrokeWeight = options.strokeWeight;
this._ZIndex = options.zIndex;
}
getBounds() : IBounds
{
return VRS.googleMapUtilities.fromGoogleLatLngBounds(this.circle.getBounds());
}
getCenter() : ILatLng
{
return VRS.googleMapUtilities.fromGoogleLatLng(this.circle.getCenter());
}
setCenter(value: ILatLng)
{
this.circle.setCenter(VRS.googleMapUtilities.toGoogleLatLng(value));
}
getDraggable() : boolean
{
return this.circle.getDraggable();
}
setDraggable(value: boolean)
{
this.circle.setDraggable(value);
}
getEditable() : boolean
{
return this.circle.getEditable();
}
setEditable(value: boolean)
{
this.circle.setEditable(value);
}
getRadius() : number
{
return this.circle.getRadius();
}
setRadius(value: number)
{
this.circle.setRadius(value);
}
getVisible() : boolean
{
return this.circle.getVisible();
}
setVisible(value: boolean)
{
this.circle.setVisible(value);
}
private _FillColour: string;
getFillColor() : string
{
return this._FillColour;
}
setFillColor(value: string)
{
if(this._FillColour !== value) {
this._FillColour = value;
this.circle.setOptions({ fillColor: value });
}
}
private _FillOpacity: number;
getFillOpacity() : number
{
return this._FillOpacity;
}
setFillOpacity(value: number)
{
if(this._FillOpacity !== value) {
this._FillOpacity = value;
this.circle.setOptions({ fillOpacity: value });
}
}
private _StrokeColour: string;
getStrokeColor() : string
{
return this._StrokeColour;
}
setStrokeColor(value: string)
{
if(this._StrokeColour !== value) {
this._StrokeColour = value;
this.circle.setOptions({ strokeColor: value });
}
}
private _StrokeOpacity: number;
getStrokeOpacity() : number
{
return this._StrokeOpacity;
}
setStrokeOpacity(value: number)
{
if(this._StrokeOpacity !== value) {
this._StrokeOpacity = value;
this.circle.setOptions({ strokeOpacity: value });
}
}
private _StrokeWeight: number;
getStrokeWeight() : number
{
return this._StrokeWeight;
}
setStrokeWeight(value: number)
{
if(this._StrokeWeight !== value) {
this._StrokeWeight = value;
this.circle.setOptions({ strokeWeight: value });
}
}
private _ZIndex: number;
getZIndex() : number
{
return this._ZIndex;
}
setZIndex(value: number)
{
if(this._ZIndex !== value) {
this._ZIndex = value;
this.circle.setOptions({ zIndex: value });
}
}
}
/**
* A wrapper around a map's native info window.
*/
class MapInfoWindow implements IMapInfoWindow
{
id: string | number;
infoWindow: google.maps.InfoWindow;
tag: any;
isOpen: boolean;
/**
* Creates a new object.
* @param {string|number} id The unique identifier of the info window
* @param {google.maps.InfoWindow} nativeInfoWindow The map's native info window object that this wraps.
* @param {*} tag An abstract object that is associated with the info window.
* @param {IMapInfoWindowSettings} options The options used to create the info window.
*/
constructor(id: string | number, nativeInfoWindow: google.maps.InfoWindow, tag: any, options: IMapInfoWindowSettings)
{
this.id = id;
this.infoWindow = nativeInfoWindow;
this.tag = tag;
this.isOpen = false;
this._DisableAutoPan = options.disableAutoPan;
this._MaxWidth = options.maxWidth;
this._PixelOffset = options.pixelOffset;
}
/**
* An array of objects describing the events that have been hooked on the info window.
*/
nativeListeners: google.maps.MapsEventListener[] = [];
getContent() : Element
{
return <Element>this.infoWindow.getContent();
}
setContent(value: Element)
{
this.infoWindow.setContent(value);
}
private _DisableAutoPan: boolean;
getDisableAutoPan() : boolean
{
return this._DisableAutoPan;
}
setDisableAutoPan(value: boolean)
{
if(this._DisableAutoPan !== value) {
this._DisableAutoPan = value;
this.infoWindow.setOptions({ disableAutoPan: value });
}
}
private _MaxWidth: number;
getMaxWidth() : number
{
return this._MaxWidth;
}
setMaxWidth(value: number)
{
if(this._MaxWidth !== value) {
this._MaxWidth = value;
this.infoWindow.setOptions({ maxWidth: value });
}
}
private _PixelOffset: ISize;
getPixelOffset() : ISize
{
return this._PixelOffset;
}
setPixelOffset(value: ISize)
{
if(this._PixelOffset !== value) {
this._PixelOffset = value;
this.infoWindow.setOptions({ pixelOffset: VRS.googleMapUtilities.toGoogleSize(value) });
}
}
getPosition() : ILatLng
{
return VRS.googleMapUtilities.fromGoogleLatLng(this.infoWindow.getPosition());
}
setPosition(value: ILatLng)
{
this.infoWindow.setPosition(VRS.googleMapUtilities.toGoogleLatLng(value));
}
getZIndex() : number
{
return this.infoWindow.getZIndex();
}
setZIndex(value: number)
{
this.infoWindow.setZIndex(value);
}
}
/**
* The state held for every map plugin object.
*/
class MapPluginState
{
/**
* The map that the plugin wraps.
*/
map: google.maps.Map = undefined;
/**
* The map's container.
*/
mapContainer: JQuery = undefined;
/**
* An associative array of marker IDs to markers.
*/
markers: { [markerId: string]: MapMarker } = {};
/**
* An associative array of polyline IDs to polylines.
*/
polylines: { [polylineId: string]: MapPolyline } = {};
/**
* An associative array of polygon IDs to polygons.
*/
polygons: { [polygonId: string]: MapPolygon } = {};
/**
* An associative array of circle IDs to circles.
*/
circles: { [circleId: string]: MapCircle } = {};
/**
* An associative array of info window IDs to info windows.
*/
infoWindows: { [infoWindowId: string]: MapInfoWindow } = {};
/**
* An array of Google Maps listener objects that we can use to unhook ourselves from the map when the plugin
* is destroyed.
*/
nativeHooks: google.maps.MapsEventListener[] = [];
}
/*
* jQueryUIHelper
*/
export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {};
jQueryUIHelper.getMapPlugin = (jQueryElement: JQuery) : IMap =>
{
return <IMap>jQueryElement.data('vrsVrsMap');
}
jQueryUIHelper.getMapOptions = (overrides: IMapOptions) : IMapOptions =>
{
return $.extend({
// Google Map load options - THESE ONLY HAVE ANY EFFECT ON THE FIRST MAP LOADED ON A PAGE
key: null, // If supplied then the Google Maps script is loaded with this API key. API keys are no longer optional for public servers but remain optional for LAN and local loopback servers.
version: '3.42', // The version of Google Maps to load.
sensor: false, // True if the location-aware stuff is to be turned on.
libraries: [], // The optional libraries to load.
loadMarkerWithLabel:false, // Loads the marker-with-labels library after loading Google Maps.
loadMarkerCluster: false, // Loads the marker cluster library after loading Google Maps.
// Google map open options
openOnCreate: true, // Open the map when the widget is created, if false then the code that creates the map has to call open() itself.
waitUntilReady: true, // If true then the widget does not call afterOpen until after the map has completely loaded. If this is false then calling getBounds (and perhaps other calls) may fail until the map has loaded.
zoom: 12, // The zoom level to open with
center: { lat: 51.5, lng: -0.125 }, // The location to centre the map on
showMapTypeControl: true, // True to show the map type control, false to hide it.
mapTypeId: VRS.MapType.Hybrid, // The map type to start with
streetViewControl: VRS.globalOptions.mapShowStreetView, // Whether to show Street View or not
scrollwheel: VRS.globalOptions.mapScrollWheelActive, // Whether the scrollwheel zooms the map
scaleControl: VRS.globalOptions.mapShowScaleControl, // Whether to show the scale control or not.
draggable: VRS.globalOptions.mapDraggable, // Whether the map is draggable
controlStyle: VRS.MapControlStyle.Default, // The style of map control to display
controlPosition: undefined, // Where the map control should be placed
pointsOfInterest: VRS.globalOptions.mapShowPointsOfInterest, // Whether to show Google Maps' points of interest
showHighContrast: VRS.globalOptions.mapShowHighContrastStyle, // Whether to show the custom high-contrast map style or not.
// Custom map open options
mapControls: [], // Controls to add to the map after it has been opened.
// Callbacks
afterCreate: null, // Called after the map has been created but before it has been opened
afterOpen: null, // Called after the map has been opened
// Persistence options
name: 'default', // The name to use to distinguish the state settings from those of other maps
useStateOnOpen: false, // Load and apply state when opening the map
autoSaveState: false, // Automatically save state whenever any state variable is changed by the user
useServerDefaults: false, // Always use the server-supplied configuration settings rather than those in options.
__nop: null
}, overrides);
}
/**
* A jQuery UI plugin that wraps the Google Maps map.
*/
class MapPlugin extends JQueryUICustomWidget implements IMap
{
options: IMapOptions;
private _EventPluginName = 'vrsMap';
constructor()
{
super();
this.options = VRS.jQueryUIHelper.getMapOptions();
}
private _getState() : MapPluginState
{
var result = this.element.data('mapPluginState');
if(result === undefined) {
result = new MapPluginState();
this.element.data('mapPluginState', result);
}
return result;
}
_create()
{
var self = this;
if(this.options.useServerDefaults && VRS.serverConfig) {
var config = VRS.serverConfig.get();
if(config) {
this.options.center = { lat: config.InitialLatitude, lng: config.InitialLongitude };
this.options.mapTypeId = config.InitialMapType;
this.options.zoom = config.InitialZoom;
}
}
this._loadGoogleMapsScript(function() {
var state = self._getState();
state.mapContainer = $('<div />')
.addClass('vrsMap')
.appendTo(self.element);
if(self.options.afterCreate) {
self.options.afterCreate(this);
}
if(self.options.openOnCreate) {
self.open();
}
if(VRS.refreshManager) VRS.refreshManager.registerTarget(self.element, self._targetResized, self);
}, function(jqXHR, textStatus, errorThrown) {
var state = self._getState();
state.mapContainer = $('<div />')
.addClass('vrsMap notOnline')
.appendTo(self.element);
$('<p/>')
.text(VRS.$$.GoogleMapsCouldNotBeLoaded + ': ' + textStatus)
.appendTo(state.mapContainer);
if(self.options.afterCreate) {
self.options.afterCreate(this);
}
if(self.options.openOnCreate && self.options.afterOpen) {
self.options.afterOpen(self);
}
});
}
_destroy()
{
var state = this._getState();
if(VRS.refreshManager) VRS.refreshManager.unregisterTarget(this.element);
$.each(state.nativeHooks, function(idx, hookResult) {
google.maps.event.removeListener(hookResult);
});
state.nativeHooks = [];
if(state.mapContainer) state.mapContainer.remove();
}
/*
* MAP INITIALISATION
*/
/**
* Loads Google Maps. Note that only the first call to this on a page will actually do anything.
*/
_loadGoogleMapsScript(successCallback: () => void, failureCallback: (jqXHR: JQueryXHR, status: string, error: string) => void)
{
var url = VRS.globalOptions.mapGoogleMapUseHttps ? VRS.globalOptions.mapGoogleMapHttpsUrl : VRS.globalOptions.mapGoogleMapHttpUrl;
var params = <any>{
// Note that Google Maps no longer requires the sensor flag and will report a warning if it is used
v: this.options.version
};
var googleMapsApiKey = this.options.key;
if(!googleMapsApiKey && VRS.serverConfig) {
var config = VRS.serverConfig.get();
if(config && config.GoogleMapsApiKey) {
googleMapsApiKey = config.GoogleMapsApiKey;
}
}
if(googleMapsApiKey) {
params.key = googleMapsApiKey;
}
if(this.options.libraries.length > 0) {
params.libraries = this.options.libraries.join(',');
}
if(VRS.browserHelper && VRS.browserHelper.notOnline()) {
failureCallback(null, VRS.$$.WorkingInOfflineMode, VRS.$$.WorkingInOfflineMode);
} else {
var callback = successCallback;
if(this.options.loadMarkerWithLabel) {
var chainCallbackMarkerWithLabel = callback;
callback = function() {
VRS.scriptManager.loadScript({
key: 'markerWithLabel',
url: 'script/markerWithLabel.js',
queue: true,
success: chainCallbackMarkerWithLabel
});
};
}
if(this.options.loadMarkerCluster) {
var chainCallbackMarkerCluster = callback;
callback = function() {
VRS.scriptManager.loadScript({
key: 'markerCluster',
url: 'script/markercluster.js',
queue: true,
success: chainCallbackMarkerCluster
});
};
}
if(window['google'] && window['google']['maps']) {
callback();
} else {
VRS.scriptManager.loadScript({
key: VRS.scriptKey.GoogleMaps,
url: url,
params: params,
queue: true,
success: callback,
error: failureCallback || null,
timeout: VRS.globalOptions.mapGoogleMapTimeout
});
}
}
}
/*
* PROPERTIES
*/
/**
* Gets the native map object.
*/
getNative(): any
{
return this._getState().map;
}
/**
* Returns a string indicating what kind of map object is returned by getNative().
*/
getNativeType() : string
{
return 'GoogleMaps';
}
/**
* Gets a value indicating that the map was successfully opened.
*/
isOpen() : boolean
{
return !!this._getState().map;
}
/**
* Gets a value indicating that the map has initialised and is ready for use.
*/
isReady() : boolean
{
var state = this._getState();
return !!state.map && !!state.map.getBounds();
}
/**
* Gets the rectangle of coordinates that the map is displaying.
*/
getBounds() : IBounds
{
return this._getBounds(this._getState());
}
private _getBounds(state: MapPluginState)
{
return state.map ? VRS.googleMapUtilities.fromGoogleLatLngBounds(state.map.getBounds()) : { tlLat: 0, tlLng: 0, brLat: 0, brLng: 0};
}
/**
* Gets the coordinate at the centre of the map.
*/
getCenter() : ILatLng
{
return this._getCenter(this._getState());
}
private _getCenter(state: MapPluginState)
{
return state.map ? VRS.googleMapUtilities.fromGoogleLatLng(state.map.getCenter()) : this.options.center;
}
/**
* Moves the map so that the coordinate passed across is the centre of the map.
*/
setCenter(latLng: ILatLng)
{
this._setCenter(this._getState(), latLng);
}
private _setCenter(state: MapPluginState, latLng: ILatLng)
{
if(state.map) state.map.setCenter(VRS.googleMapUtilities.toGoogleLatLng(latLng));
else this.options.center = latLng;
}
/**
* Returns true if the map is draggable, false if it is not.
*/
getDraggable() : boolean
{
return this.options.draggable;
}
/**
* Returns the currently selected map type.
*/
getMapType() : MapTypeEnum
{
return this._getMapType(this._getState());
}
private _getMapType(state: MapPluginState) : MapTypeEnum
{
return state.map ? VRS.googleMapUtilities.fromGoogleMapType(state.map.getMapTypeId()) : this.options.mapTypeId;
}
/**
* Sets the currently selected map type.
*/
setMapType(mapType: MapTypeEnum)
{
this._setMapType(this._getState(), mapType);
}
private _setMapType(state: MapPluginState, mapType: MapTypeEnum)
{
if(!state.map) {
this.options.mapTypeId = mapType;
} else {
var currentMapType = this.getMapType();
if(currentMapType !== mapType) state.map.setMapTypeId(VRS.googleMapUtilities.toGoogleMapType(mapType));
}
}
/**
* Gets a value indicating whether the scroll wheel zooms the map.
*/
getScrollWheel() : boolean
{
return this.options.scrollwheel;
}
/**
* Gets a value indicating whether Google StreetView is enabled for the map.
*/
getStreetView() : boolean
{
return this.options.streetViewControl;
}
/**
* Gets the current zoom level.
*/
getZoom() : number
{
return this._getZoom(this._getState());
}
private _getZoom(state: MapPluginState) : number
{
return state.map ? state.map.getZoom() : this.options.zoom;
}
/**
* Sets the current zoom level.
*/
setZoom(zoom: number)
{
this._setZoom(this._getState(), zoom);
}
private _setZoom(state: MapPluginState, zoom: number)
{
if(state.map) state.map.setZoom(zoom);
else this.options.zoom = zoom;
}
/*
* MAP EVENTS EXPOSED
*/
/**
* Unhooks any event hooked on this plugin.
*/
unhook(hookResult: IEventHandleJQueryUI)
{
VRS.globalDispatch.unhookJQueryUIPluginEvent(this.element, hookResult);
}
/**
* Raised when the map's boundaries change.
*/
hookBoundsChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'boundsChanged', callback, forceThis);
}
private _raiseBoundsChanged()
{
this._trigger('boundsChanged');
}
/**
* Unused - brightness is not supported on Google Maps.
*/
hookBrightnessChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
// Hook something so that the caller doesn't need to deal with null. It's just that the map plugin will not raise this event itself.
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'brightnessChanged', callback, forceThis);
}
/**
* Raised when the map is moved.
*/
hookCenterChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'centerChanged', callback, forceThis);
}
private _raiseCenterChanged()
{
this._trigger('centerChanged');
}
/**
* Raised when the map is clicked.
*/
hookClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'clicked', callback, forceThis);
}
private _raiseClicked(mouseEvent: Event)
{
this._trigger('clicked', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent });
}
/**
* Raised when the map is double-clicked.
*/
hookDoubleClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'doubleClicked', callback, forceThis);
}
private _raiseDoubleClicked(mouseEvent: Event)
{
this._trigger('doubleClicked', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent });
}
/**
* Raised after the user has stopped moving, zooming or otherwise changing the map's properties.
*/
hookIdle(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'idle', callback, forceThis);
}
private _raiseIdle()
{
this._trigger('idle');
}
/**
* Raised after the user changes the map type.
*/
hookMapTypeChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'mapTypeChanged', callback, forceThis);
}
private _raiseMapTypeChanged()
{
this._trigger('mapTypeChanged');
}
/**
* Raised when the user right-clcks the map.
*/
hookRightClicked(callback: (event?: Event, data?: IMapMouseEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'mouseEvent', callback, forceThis);
}
private _raiseRightClicked(mouseEvent: Event)
{
this._trigger('mouseEvent', null, <IMapMouseEventArgs>{ mouseEvent: mouseEvent });
}
/**
* Raised after the map's images have been displayed or changed.
*/
hookTilesLoaded(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'tilesLoaded', callback, forceThis);
}
private _raiseTilesLoaded()
{
this._trigger('tilesLoaded');
}
/**
* Raised after the map has been zoomed.
*/
hookZoomChanged(callback: (event?: Event) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'zoomChanged', callback, forceThis);
}
private _raiseZoomChanged()
{
this._trigger('zoomChanged');
}
/*
* CHILD OBJECT EVENTS EXPOSED
*/
/**
* Raised when a map marker is clicked.
*/
hookMarkerClicked(callback: (event?: Event, data?: IMapMarkerEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'markerClicked', callback, forceThis);
}
private _raiseMarkerClicked(id: string | number)
{
this._trigger('markerClicked', null, <IMapMarkerEventArgs>{ id: id });
}
/**
* Raised when a map marker is dragged.
*/
hookMarkerDragged(callback: (event?: Event, data?: IMapMarkerEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, this._EventPluginName, 'markerDragged', callback, forceThis);
}
private _raiseMarkerDragged(id: string | number)
{
this._trigger('markerDragged', null, <IMapMarkerEventArgs>{ id: id });
}
/**
* Raised after the user closes an InfoWindow.
*/
hookInfoWindowClosedByUser(callback: (event?: Event, data?: IMapInfoWindowEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI
{
return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, 'vrsMap', 'infoWindowClosedByUser', callback, forceThis);
}
private _raiseInfoWindowClosedByUser(id: string | number)
{
this._trigger('infoWindowClosedByUser', null, <IMapInfoWindowEventArgs>{ id: id });
}
//
// MAP EVENT HANDLERS
//
/**
* Called when the map becomes idle.
*/
private _onIdle()
{
if(this.options.autoSaveState) this.saveState();
this._raiseIdle();
}
/**
* Called after the map type has changed.
*/
private _onMapTypeChanged()
{
if(this.options.autoSaveState) this.saveState();
this._raiseMapTypeChanged();
}
//
// BASIC MAP OPERATIONS
//
/**
* Opens the map. If you configure the options so that the map is not opened when the widget is created then the
* Google Maps javascript might still be loading when you call this, in which case the call will fail. The rule
* is that you either auto-open the map using the options or you use a script tag and wait until the document
* is ready before you call this method.
*/
open(userOptions?: IMapOpenOptions)
{
var self = this;
var mapOptions: IMapOptions = $.extend(<IMapOptions>{}, userOptions, {
zoom: this.options.zoom,
center: this.options.center,
mapTypeControl: this.options.showMapTypeControl,
mapTypeId: this.options.mapTypeId,
streetViewControl: this.options.streetViewControl,
scrollwheel: this.options.scrollwheel,
scaleControl: this.options.scaleControl,
draggable: this.options.draggable,
showHighContrast: this.options.showHighContrast,
controlStyle: this.options.controlStyle,
controlPosition: this.options.controlPosition,
mapControls: this.options.mapControls
});
if(this.options.useStateOnOpen) {
var settings = this.loadState();
mapOptions.zoom = settings.zoom;
mapOptions.center = settings.center;
mapOptions.mapTypeId = settings.mapTypeId;
}
var googleMapOptions: google.maps.MapOptions = {
zoom: mapOptions.zoom,
center: VRS.googleMapUtilities.toGoogleLatLng(mapOptions.center),
streetViewControl: mapOptions.streetViewControl,
scrollwheel: mapOptions.scrollwheel,
draggable: mapOptions.draggable,
scaleControl: mapOptions.scaleControl,
mapTypeControlOptions: {
style: VRS.googleMapUtilities.toGoogleMapControlStyle(mapOptions.controlStyle)
}
};
if(mapOptions.controlPosition) {
googleMapOptions.mapTypeControlOptions.position = VRS.googleMapUtilities.toGoogleControlPosition(mapOptions.controlPosition);
}
if(!mapOptions.pointsOfInterest) {
googleMapOptions.styles = [
{
featureType: 'poi',
elementType: 'labels',
stylers: [{ visibility: 'off' }]
}
];
}
var highContrastMap: google.maps.MapType;
var highContrastMapName = <string>VRS.googleMapUtilities.toGoogleMapType(VRS.MapType.HighContrast);
if(mapOptions.showHighContrast && VRS.globalOptions.mapHighContrastMapStyle && VRS.globalOptions.mapHighContrastMapStyle.length) {
var googleMapTypeIds = [];
$.each(VRS.MapType, function(idx, mapType: MapTypeEnum) {
var googleMapType = VRS.googleMapUtilities.toGoogleMapType(mapType);
if(googleMapType) googleMapTypeIds.push(googleMapType);
});
googleMapOptions.mapTypeControlOptions.mapTypeIds = googleMapTypeIds;
var highContrastMapStyle: google.maps.MapTypeStyle[] = VRS.globalOptions.mapHighContrastMapStyle;
highContrastMap = new google.maps.StyledMapType(highContrastMapStyle, { name: highContrastMapName });
}
var state = this._getState();
state.map = new google.maps.Map(state.mapContainer[0], googleMapOptions);
if(highContrastMap) {
state.map.mapTypes.set(highContrastMapName, highContrastMap);
} else if(mapOptions.mapTypeId === VRS.MapType.HighContrast) {
mapOptions.mapTypeId = VRS.MapType.RoadMap;
}
state.map.setMapTypeId(VRS.googleMapUtilities.toGoogleMapType(mapOptions.mapTypeId));
if(mapOptions.mapControls && mapOptions.mapControls.length) {
$.each(mapOptions.mapControls, function(idx, mapControl) {
self.addControl(mapControl.control, mapControl.position);
});
}
this._hookEvents(state);
var waitUntilReady = function() {
if(self.options.waitUntilReady && !self.isReady()) {
setTimeout(waitUntilReady, 100);
} else {
if(self.options.afterOpen) self.options.afterOpen(self);
}
};
waitUntilReady();
}
/**
* Hooks the events we care about on the Google map.
*/
private _hookEvents(state: MapPluginState)
{
var self = this;
var map = state.map;
var hooks = state.nativeHooks;
hooks.push(google.maps.event.addListener(map, 'bounds_changed', function() { self._raiseBoundsChanged(); }));
hooks.push(google.maps.event.addListener(map, 'center_changed', function() { self._raiseCenterChanged(); }));
hooks.push(google.maps.event.addListener(map, 'click', function(mouseEvent: Event) { self._userNotIdle(); self._raiseClicked(mouseEvent); }));
hooks.push(google.maps.event.addListener(map, 'dblclick', function(mouseEvent: Event) { self._userNotIdle(); self._raiseDoubleClicked(mouseEvent); }));
hooks.push(google.maps.event.addListener(map, 'idle', function() { self._onIdle(); }));
hooks.push(google.maps.event.addListener(map, 'maptypeid_changed', function() { self._userNotIdle(); self._onMapTypeChanged(); }));
hooks.push(google.maps.event.addListener(map, 'rightclick', function(mouseEvent: Event) { self._userNotIdle(); self._raiseRightClicked(mouseEvent); }));
hooks.push(google.maps.event.addListener(map, 'tilesloaded', function() { self._raiseTilesLoaded(); }));
hooks.push(google.maps.event.addListener(map, 'zoom_changed', function() { self._userNotIdle(); self._raiseZoomChanged(); }));
}
/**
* Records the fact that the user did something.
*/
private _userNotIdle()
{
if(VRS.timeoutManager) VRS.timeoutManager.resetTimer();
}
/**
* Refreshes the map, typically after it has been resized.
*/
refreshMap()
{
var state = this._getState();
if(state.map) google.maps.event.trigger(state.map, 'resize');
}
/**
* Moves the map to a new map centre.
*/
panTo(mapCenter: ILatLng)
{
this._panTo(mapCenter, this._getState());
}
private _panTo(mapCenter: ILatLng, state: MapPluginState)
{
if(state.map) state.map.panTo(VRS.googleMapUtilities.toGoogleLatLng(mapCenter));
else this.options.center = mapCenter;
}
/**
* Moves the map so that the bounds specified are shown. This does nothing if the map has not been opened.
*/
fitBounds(bounds: IBounds)
{
var state = this._getState();
if(state.map) {
state.map.fitBounds(VRS.googleMapUtilities.toGoogleLatLngBounds(bounds));
}
}
//
// STATE PERSISTENCE
//
/**
* Saves the current state of the map.
*/
saveState()
{
var settings = this._createSettings();
VRS.configStorage.save(this._persistenceKey(), settings);
}
/**
* Returns a previously saved state or returns the current state if no state was previously saved.
*/
loadState() : IMapSaveState
{
var savedSettings = VRS.configStorage.load(this._persistenceKey(), {});
return $.extend(this._createSettings(), savedSettings);
}
/**
* Applies a previously saved state.
*/
applyState(config: IMapSaveState)
{
config = config || <IMapSaveState>{};
var state = this._getState();
if(config.center) this._setCenter(state, config.center);
if(config.zoom || config.zoom === 0) this._setZoom(state, config.zoom);
if(config.mapTypeId) this._setMapType(state, config.mapTypeId);
};
/**
* Loads and applies a previously saved state.
*/
loadAndApplyState()
{
this.applyState(this.loadState());
}
/**
* Returns the key against which the state will be saved.
*/
private _persistenceKey() : string
{
return 'vrsMapState-' + (this.options.name || 'default');
}
/**
* Returns the current state of the object.
*/
private _createSettings() : IMapSaveState
{
var state = this._getState();
var zoom = this._getZoom(state);
var mapTypeId = this._getMapType(state);
var center = this._getCenter(state);
return {
zoom: zoom,
mapTypeId: mapTypeId,
center: center,
brightnessMapName: 'google',
brightness: 100
};
}
//
// MAP MARKER METHODS
//
/**
* Adds a marker to the map. Behaviour is undefined if the map has not been opened.
*/
addMarker(id: string | number, userOptions: IMapMarkerSettings) : IMapMarker
{
var self = this;
var result: MapMarker;
var state = this._getState();
if(state.map) {
var googleOptions: MarkerWithLabelOptions = {
map: state.map,
position: undefined,
clickable: userOptions.clickable !== undefined ? userOptions.clickable : true,
draggable: userOptions.draggable !== undefined ? userOptions.draggable : false,
//flat: userOptions.flat !== undefined ? userOptions.flat : false, // Google Maps no longer supports shadows on map markers
optimized: userOptions.optimized !== undefined ? userOptions.optimized : false,
raiseOnDrag: userOptions.raiseOnDrag !== undefined ? userOptions.raiseOnDrag : true,
visible: userOptions.visible !== undefined ? userOptions.visible : true
};
if(userOptions.animateAdd) googleOptions.animation = google.maps.Animation.DROP;
if(userOptions.position) googleOptions.position = VRS.googleMapUtilities.toGoogleLatLng(userOptions.position);
else googleOptions.position = state.map.getCenter();
if(userOptions.icon) googleOptions.icon = VRS.googleMapUtilities.toGoogleIcon(userOptions.icon);
if(userOptions.tooltip) googleOptions.title = userOptions.tooltip;
if(userOptions.zIndex || userOptions.zIndex === 0) googleOptions.zIndex = userOptions.zIndex;
if(userOptions.useMarkerWithLabel) {
if(userOptions.mwlLabelInBackground !== undefined) googleOptions.labelInBackground = userOptions.mwlLabelInBackground;
if(userOptions.mwlLabelClass) googleOptions.labelClass = userOptions.mwlLabelClass;
}
this.destroyMarker(id);
var marker: google.maps.Marker;
if(!userOptions.useMarkerWithLabel) marker = new google.maps.Marker(googleOptions);
else marker = new MarkerWithLabel(googleOptions);
result = new MapMarker(id, marker, !!userOptions.useMarkerWithLabel, userOptions.tag);
state.markers[id] = result;
result.nativeListeners.push(google.maps.event.addListener(marker, 'click', function() { self._raiseMarkerClicked.call(self, id); }));
result.nativeListeners.push(google.maps.event.addListener(marker, 'dragend', function() { self._raiseMarkerDragged.call(self, id); }));
}
return result;
}
/**
* Gets a VRS.MapMarker by its ID or, if passed a marker, returns the same marker.
*/
getMarker(idOrMarker: string | number | IMapMarker) : IMapMarker
{
if(idOrMarker instanceof MapMarker) return idOrMarker;
var state = this._getState();
return state.markers[<string | number>idOrMarker];
}
/**
* Destroys the map marker passed across.
*/
destroyMarker(idOrMarker: string | number | IMapMarker)
{
var state = this._getState();
var marker = <MapMarker>this.getMarker(idOrMarker);
if(marker) {
$.each(marker.nativeListeners, function(idx, listener) {
google.maps.event.removeListener(listener);
});
marker.nativeListeners = [];
marker.marker.setMap(null);
marker.marker = null;
marker.tag = null;
delete state.markers[marker.id];
marker.id = null;
}
}
/**
* Centres the map on the marker passed across.
*/
centerOnMarker(idOrMarker: string | number | IMapMarker)
{
var state = this._getState();
var marker = <MapMarker>this.getMarker(idOrMarker);
if(marker) {
state.map.setCenter(marker.marker.getPosition());
}
}
//
// MAP CLUSTERER METHODS
//
createMapMarkerClusterer(settings?: IMapMarkerClustererSettings) : IMapMarkerClusterer
{
var result: MapMarkerClusterer = null;
if(typeof(MarkerClusterer) == 'function') {
var state = this._getState();
if(state.map) {
settings = $.extend({}, settings);
var clusterer = new MarkerClusterer(state.map, [], settings);
result = new MapMarkerClusterer(this, clusterer);
}
}
return result;
}
//
// POLYLINE METHODS
//
/**
* Adds a line to the map. The behaviour is undefined if the map has not already been opened.
*/
addPolyline(id: string | number, userOptions: IMapPolylineSettings) : IMapPolyline
{
var result: MapPolyline;
var state = this._getState();
if(state.map) {
var googleOptions: google.maps.PolylineOptions = {
map: state.map,
clickable: userOptions.clickable !== undefined ? userOptions.clickable : false,
draggable: userOptions.draggable !== undefined ? userOptions.draggable : false,
editable: userOptions.editable !== undefined ? userOptions.editable : false,
geodesic: userOptions.geodesic !== undefined ? userOptions.geodesic : false,
strokeColor: userOptions.strokeColour || '#000000',
visible: userOptions.visible !== undefined ? userOptions.visible : true
};
if(userOptions.path) googleOptions.path = VRS.googleMapUtilities.toGoogleLatLngMVCArray(userOptions.path);
if(userOptions.strokeOpacity || userOptions.strokeOpacity === 0) googleOptions.strokeOpacity = userOptions.strokeOpacity;
if(userOptions.strokeWeight || userOptions.strokeWeight === 0) googleOptions.strokeWeight = userOptions.strokeWeight;
if(userOptions.zIndex || userOptions.zIndex === 0) googleOptions.zIndex = userOptions.zIndex;
this.destroyPolyline(id);
var polyline = new google.maps.Polyline(googleOptions);
result = new MapPolyline(id, polyline, userOptions.tag, {
strokeColour: userOptions.strokeColour,
strokeOpacity: userOptions.strokeOpacity,
strokeWeight: userOptions.strokeWeight
});
state.polylines[id] = result;
}
return result;
}
/**
* Returns the VRS.MapPolyline associated with the ID.
*/
getPolyline(idOrPolyline: string | number | IMapPolyline) : IMapPolyline
{
if(idOrPolyline instanceof MapPolyline) return idOrPolyline;
var state = this._getState();
return state.polylines[<string | number>idOrPolyline];
}
/**
* Destroys the line passed across.
*/
destroyPolyline(idOrPolyline: string | number | IMapPolyline)
{
var state = this._getState();
var polyline = <MapPolyline>this.getPolyline(idOrPolyline);
if(polyline) {
polyline.polyline.setMap(null);
polyline.polyline = null;
polyline.tag = null;
delete state.polylines[polyline.id];
polyline.id = null;
}
}
/**
* Removes a number of points from the start or end of the line.
*/
trimPolyline(idOrPolyline: string | number | IMapPolyline, countPoints: number, fromStart: boolean) : IMapTrimPolylineResult
{
var emptied = false;
var countRemoved = 0;
if(countPoints > 0) {
var polyline = <MapPolyline>this.getPolyline(idOrPolyline);
var points = polyline.polyline.getPath();
var length = points.getLength();
if(length < countPoints) countPoints = length;
if(countPoints > 0) {
countRemoved = countPoints;
emptied = countPoints === length;
if(emptied) {
points.clear();
} else {
var end = length - 1;
for(;countPoints > 0;--countPoints) {
points.removeAt(fromStart ? 0 : end--);
}
}
}
}
return { emptied: emptied, countRemoved: countRemoved };
};
/**
* Remove a single point from the line's path.
*/
removePolylinePointAt(idOrPolyline: string | number | IMapPolyline, index: number)
{
var polyline = <MapPolyline>this.getPolyline(idOrPolyline);
var points = polyline.polyline.getPath();
points.removeAt(index);
}
/**
* Appends points to a line's path.
* @param {string|number|VRS.MapPolyline} idOrPolyline The line to change.
* @param {{lat:number, lng:number}[]} path The points to add to the path.
* @param {bool} toStart True to add the points to the start of the path, false to add them to the end.
*/
appendToPolyline(idOrPolyline: string | number | IMapPolyline, path: ILatLng[], toStart: boolean)
{
var length = !path ? 0 : path.length;
if(length > 0) {
var polyline = <MapPolyline>this.getPolyline(idOrPolyline);
var points = polyline.polyline.getPath();
var insertAt = toStart ? 0 : -1;
for(var i = 0;i < length;++i) {
var googlePoint = VRS.googleMapUtilities.toGoogleLatLng(path[i]);
if(toStart) points.insertAt(insertAt++, googlePoint);
else points.push(googlePoint);
}
}
}
/**
* Replaces an existing point along a line's path.
*/
replacePolylinePointAt(idOrPolyline: string | number | IMapPolyline, index: number, point: ILatLng)
{
var polyline = <MapPolyline>this.getPolyline(idOrPolyline);
var points = polyline.polyline.getPath();
var length = points.getLength();
if(index === -1) index = length - 1;
if(index >= 0 && index < length) points.setAt(index, VRS.googleMapUtilities.toGoogleLatLng(point));
}
//
// POLYGON METHODS
//
/**
* Adds a polygon to the map. The behaviour is undefined if the map has not already been opened.
*/
addPolygon(id: string | number, userOptions: IMapPolygonSettings) : IMapPolygon
{
var result: MapPolygon;
var state = this._getState();
if(state.map) {
var googleOptions: google.maps.PolygonOptions = {
map: state.map,
clickable: userOptions.clickable !== undefined ? userOptions.clickable : false,
draggable: userOptions.draggable !== undefined ? userOptions.draggable : false,
editable: userOptions.editable !== undefined ? userOptions.editable : false,
geodesic: userOptions.geodesic !== undefined ? userOptions.geodesic : false,
fillColor: userOptions.fillColour,
fillOpacity: userOptions.fillOpacity,
paths: <any[]>(<any>(VRS.googleMapUtilities.toGoogleLatLngMVCArrayArray(userOptions.paths) || undefined)),
strokeColor: userOptions.strokeColour || '#000000',
strokeWeight: userOptions.strokeWeight,
strokeOpacity: userOptions.strokeOpacity,
visible: userOptions.visible !== undefined ? userOptions.visible : true,
zIndex: userOptions.zIndex
};
this.destroyPolygon(id);
var polygon = new google.maps.Polygon(googleOptions);
result = new MapPolygon(id, polygon, userOptions.tag, userOptions);
state.polygons[id] = result;
}
return result;
}
/**
* Returns the VRS.MapPolygon associated with the ID.
*/
getPolygon(idOrPolygon: string | number | IMapPolygon) : IMapPolygon
{
if(idOrPolygon instanceof MapPolygon) return idOrPolygon;
var state = this._getState();
return state.polygons[<string | number>idOrPolygon];
}
/**
* Destroys the polygon passed across.
*/
destroyPolygon(idOrPolygon: string | number | IMapPolygon)
{
var state = this._getState();
var polygon = <MapPolygon>this.getPolygon(idOrPolygon);
if(polygon) {
polygon.polygon.setMap(null);
polygon.polygon = null;
polygon.tag = null;
delete state.polygons[polygon.id];
polygon.id = null;
}
}
//
// CIRCLE METHODS
//
/**
* Adds a circle to the map.
*/
addCircle(id: string | number, userOptions: IMapCircleSettings) : IMapCircle
{
var result: MapCircle = null;
var state = this._getState();
if(state.map) {
var googleOptions: google.maps.CircleOptions = $.extend({
clickable: false,
draggable: false,
editable: false,
fillColor: '#000',
fillOpacity: 0,
strokeColor: '#000',
strokeOpacity: 1,
strokeWeight: 1,
visible: true
}, userOptions);
googleOptions.center = VRS.googleMapUtilities.toGoogleLatLng(userOptions.center);
googleOptions.map = state.map;
this.destroyCircle(id);
var circle = new google.maps.Circle(googleOptions);
result = new MapCircle(id, circle, userOptions.tag, userOptions || {});
state.circles[id] = result;
}
return result;
}
/**
* Returns the VRS.MapCircle associated with the ID.
*/
getCircle(idOrCircle: string | number | IMapCircle) : IMapCircle
{
if(idOrCircle instanceof MapCircle) return idOrCircle;
var state = this._getState();
return state.circles[<string | number>idOrCircle];
}
/**
* Destroys the circle passed across.
*/
destroyCircle(idOrCircle: string | number | IMapCircle)
{
var state = this._getState();
var circle = <MapCircle>this.getCircle(idOrCircle);
if(circle) {
circle.circle.setMap(null);
circle.circle = null;
circle.tag = null;
delete state.circles[circle.id];
circle.id = null;
}
}
//
// INFOWINDOW METHODS
//
/**
* Returns an Info Window ID that is guaranteed to not be in current use.
*/
getUnusedInfoWindowId() : string
{
var result;
var state = this._getState();
for(var i = 1;i > 0;++i) {
result = 'autoID' + i;
if(!state.infoWindows[result]) break;
}
return result;
}
/**
* Creates a new info window for the map.
*/
addInfoWindow(id: string | number, userOptions: IMapInfoWindowSettings) : IMapInfoWindow
{
var result: MapInfoWindow = null;
var state = this._getState();
if(state.map) {
var googleOptions: google.maps.InfoWindowOptions = $.extend({
}, userOptions);
if(userOptions.position) googleOptions.position = VRS.googleMapUtilities.toGoogleLatLng(userOptions.position);
this.destroyInfoWindow(id);
var infoWindow = new google.maps.InfoWindow(googleOptions);
result = new MapInfoWindow(id, infoWindow, userOptions.tag, userOptions || {});
state.infoWindows[id] = result;
var self = this;
result.nativeListeners.push(google.maps.event.addListener(infoWindow, 'closeclick', function() {
result.isOpen = false;
self._raiseInfoWindowClosedByUser(id);
}));
}
return result;
}
/**
* If passed the ID of an info window then the associated info window is returned. If passed an info window
* then it is just returned.
*/
getInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow) : IMapInfoWindow
{
if(idOrInfoWindow instanceof MapInfoWindow) return idOrInfoWindow;
var state = this._getState();
return state.infoWindows[<string | number>idOrInfoWindow];
}
/**
* Destroys the info window passed across. Note that Google do not supply a method to dispose of an info window.
*/
destroyInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow)
{
var state = this._getState();
var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow);
if(infoWindow) {
$.each(infoWindow.nativeListeners, function(idx, listener) {
google.maps.event.removeListener(listener);
});
this.closeInfoWindow(infoWindow);
infoWindow.infoWindow.setContent('');
infoWindow.tag = null;
infoWindow.infoWindow = null;
delete state.infoWindows[infoWindow.id];
infoWindow.id = null;
}
}
/**
* Opens the info window at the position specified on the window, optionally with an anchor to specify the
* location of the tip of the info window. Does nothing if it's already open.
*/
openInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow, mapMarker?: IMapMarker)
{
var state = this._getState();
var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow);
if(infoWindow && state.map && !infoWindow.isOpen) {
infoWindow.infoWindow.open(state.map, mapMarker ? (<MapMarker>mapMarker).marker : undefined);
infoWindow.isOpen = true;
}
}
/**
* Closes an info window if it's open. Does nothing if it's already closed.
*/
closeInfoWindow(idOrInfoWindow: string | number | IMapInfoWindow)
{
var infoWindow = <MapInfoWindow>this.getInfoWindow(idOrInfoWindow);
if(infoWindow && infoWindow.isOpen) {
infoWindow.infoWindow.close();
infoWindow.isOpen = false;
}
}
//
// MAP CONTROL METHODS
//
/**
* Adds a control to the map.
*/
addControl(element: JQuery | HTMLElement, mapPosition: MapPositionEnum)
{
var state = this._getState();
if(state.map) {
var controlsArray = state.map.controls[VRS.googleMapUtilities.toGoogleControlPosition(mapPosition)];
if(!(element instanceof jQuery)) controlsArray.push(element);
else $.each(element, function() { controlsArray.push(this); });
}
}
//
// MAP LAYER METHODS
//
// The Google Maps version of the plugin does not support layers.
addLayer(layerTileSettings: ITileServerSettings, opacity: number)
{
}
destroyLayer(layerName: string)
{
}
hasLayer(layerName: string) : boolean
{
return false;
}
getLayerOpacity(layerName: string) : number
{
return undefined;
}
setLayerOpacity(layerName: string, opacity: number)
{
}
//
// BRIGHTNESS METHODS
//
// The Google Maps version of the plugin does not support configurable brightness.
getCanSetMapBrightness() : boolean
{
return false;
}
getDefaultMapBrightness() : number
{
return 100;
}
getMapBrightness() : number
{
return 100;
}
setMapBrightness(value: number)
{
}
//
// VRS EVENTS SUBSCRIBED
//
/**
* Called when the refresh manager indicates that one of our parents has resized, or done something that we need
* to refresh for.
*/
private _targetResized()
{
var state = this._getState();
var center = this._getCenter(state);
this.refreshMap();
this._setCenter(state, center);
}
}
$.widget('vrs.vrsMap', new MapPlugin());
}
declare interface JQuery
{
vrsMap();
vrsMap(options: VRS.IMapOptions);
vrsMap(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any);
} | the_stack |
import Point from "@mapbox/point-geometry";
// @ts-ignore
import { VectorTile } from "@mapbox/vector-tile";
// @ts-ignore
import Protobuf from "pbf";
// @ts-ignore
import { PMTiles } from "pmtiles";
export type JsonValue =
| boolean
| number
| string
| null
| JsonArray
| JsonObject;
export interface JsonObject {
[key: string]: JsonValue;
}
export interface JsonArray extends Array<JsonValue> {}
export enum GeomType {
Point = 1,
Line = 2,
Polygon = 3,
}
export interface Bbox {
minX: number;
minY: number;
maxX: number;
maxY: number;
}
export interface Feature {
readonly props: JsonObject;
readonly bbox: Bbox;
readonly geomType: GeomType;
readonly geom: Point[][];
readonly numVertices: number;
}
export interface Zxy {
readonly z: number;
readonly x: number;
readonly y: number;
}
export function toIndex(c: Zxy): string {
return c.x + ":" + c.y + ":" + c.z;
}
export interface TileSource {
get(c: Zxy, tileSize: number): Promise<Map<string, Feature[]>>;
}
// reimplement loadGeometry with a scalefactor
// so the general tile rendering case does not need rescaling.
const loadGeomAndBbox = (pbf: any, geometry: number, scale: number) => {
pbf.pos = geometry;
var end = pbf.readVarint() + pbf.pos,
cmd = 1,
length = 0,
x = 0,
y = 0,
x1 = Infinity,
x2 = -Infinity,
y1 = Infinity,
y2 = -Infinity;
var lines: number[][] = [];
var line: any;
while (pbf.pos < end) {
if (length <= 0) {
var cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
length = cmdLen >> 3;
}
length--;
if (cmd === 1 || cmd === 2) {
x += pbf.readSVarint() * scale;
y += pbf.readSVarint() * scale;
if (x < x1) x1 = x;
if (x > x2) x2 = x;
if (y < y1) y1 = y;
if (y > y2) y2 = y;
if (cmd === 1) {
if (line) lines.push(line);
line = [];
}
line.push(new Point(x, y));
} else if (cmd === 7) {
if (line) line.push(line[0].clone());
} else throw new Error("unknown command " + cmd);
}
if (line) lines.push(line);
return { geom: lines, bbox: { minX: x1, minY: y1, maxX: x2, maxY: y2 } };
};
function parseTile(
buffer: ArrayBuffer,
tileSize: number
): Map<string, Feature[]> {
let v = new VectorTile(new Protobuf(buffer));
let result = new Map<string, Feature[]>();
for (let [key, value] of Object.entries(v.layers)) {
let features = [];
let layer = value as any;
for (let i = 0; i < layer.length; i++) {
let result = loadGeomAndBbox(
layer.feature(i)._pbf,
layer.feature(i)._geometry,
tileSize / layer.extent
);
let numVertices = 0;
for (let part of result.geom) numVertices += part.length;
features.push({
id: layer.feature(i).id,
geomType: layer.feature(i).type,
geom: result.geom,
numVertices: numVertices,
bbox: result.bbox,
props: layer.feature(i).properties,
});
}
result.set(key, features);
}
return result;
}
export class PmtilesSource implements TileSource {
p: PMTiles;
controllers: any[];
shouldCancelZooms: boolean;
constructor(url: any, shouldCancelZooms: boolean) {
if (url.url) {
this.p = url;
} else {
this.p = new PMTiles(url);
}
this.controllers = [];
this.shouldCancelZooms = shouldCancelZooms;
}
public async get(c: Zxy, tileSize: number): Promise<Map<string, Feature[]>> {
if (this.shouldCancelZooms) {
this.controllers = this.controllers.filter((cont) => {
if (cont[0] != c.z) {
cont[1].abort();
return false;
}
return true;
});
}
let result = await this.p.getZxy(c.z, c.x, c.y);
if (!result)
throw new Error(`Tile ${c.z} ${c.x} ${c.y} not found in archive`);
const controller = new AbortController();
this.controllers.push([c.z, controller]);
const signal = controller.signal;
return new Promise((resolve, reject) => {
fetch(this.p.url, {
headers: {
Range: "bytes=" + result[0] + "-" + (result[0] + result[1] - 1),
},
signal: signal,
})
.then((resp) => {
return resp.arrayBuffer();
})
.then((buffer) => {
let result = parseTile(buffer, tileSize);
resolve(result);
})
.catch((e) => {
reject(e);
});
});
}
}
export class ZxySource implements TileSource {
url: string;
controllers: any[];
shouldCancelZooms: boolean;
constructor(url: string, shouldCancelZooms: boolean) {
this.url = url;
this.controllers = [];
this.shouldCancelZooms = shouldCancelZooms;
}
public async get(c: Zxy, tileSize: number): Promise<Map<string, Feature[]>> {
if (this.shouldCancelZooms) {
this.controllers = this.controllers.filter((cont) => {
if (cont[0] != c.z) {
cont[1].abort();
return false;
}
return true;
});
}
let url = this.url
.replace("{z}", c.z.toString())
.replace("{x}", c.x.toString())
.replace("{y}", c.y.toString());
const controller = new AbortController();
this.controllers.push([c.z, controller]);
const signal = controller.signal;
return new Promise((resolve, reject) => {
fetch(url, { signal: signal })
.then((resp) => {
return resp.arrayBuffer();
})
.then((buffer) => {
let result = parseTile(buffer, tileSize);
resolve(result);
})
.catch((e) => {
reject(e);
});
});
}
}
export interface CacheEntry {
used: number;
data: Map<string, Feature[]>;
}
let R = 6378137;
let MAX_LATITUDE = 85.0511287798;
let MAXCOORD = R * Math.PI;
let project = (latlng: number[]) => {
let d = Math.PI / 180;
let constrained_lat = Math.max(
Math.min(MAX_LATITUDE, latlng[0]),
-MAX_LATITUDE
);
let sin = Math.sin(constrained_lat * d);
return new Point(
R * latlng[1] * d,
(R * Math.log((1 + sin) / (1 - sin))) / 2
);
};
function sqr(x: number) {
return x * x;
}
function dist2(v: Point, w: Point) {
return sqr(v.x - w.x) + sqr(v.y - w.y);
}
function distToSegmentSquared(p: Point, v: Point, w: Point) {
var l2 = dist2(v, w);
if (l2 === 0) return dist2(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
t = Math.max(0, Math.min(1, t));
return dist2(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });
}
export function isInRing(point: Point, ring: Point[]): boolean {
var inside = false;
for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
var xi = ring[i].x,
yi = ring[i].y;
var xj = ring[j].x,
yj = ring[j].y;
var intersect =
yi > point.y != yj > point.y &&
point.x < ((xj - xi) * (point.y - yi)) / (yj - yi) + xi;
if (intersect) inside = !inside;
}
return inside;
}
export function isCCW(ring: Point[]): boolean {
var area = 0;
for (var i = 0; i < ring.length; i++) {
let j = (i + 1) % ring.length;
area += ring[i].x * ring[j].y;
area -= ring[j].x * ring[i].y;
}
return area < 0;
}
export function pointInPolygon(point: Point, geom: Point[][]): boolean {
var isInCurrentExterior = false;
for (let ring of geom) {
if (isCCW(ring)) {
// it is an interior ring
if (isInRing(point, ring)) isInCurrentExterior = false;
} else {
// it is an exterior ring
if (isInCurrentExterior) return true;
if (isInRing(point, ring)) isInCurrentExterior = true;
}
}
return isInCurrentExterior;
}
export function pointMinDistToPoints(point: Point, geom: Point[][]): number {
let min = Infinity;
for (let l of geom) {
let dist = Math.sqrt(dist2(point, l[0]));
if (dist < min) min = dist;
}
return min;
}
export function pointMinDistToLines(point: Point, geom: Point[][]): number {
let min = Infinity;
for (let l of geom) {
for (var i = 0; i < l.length - 1; i++) {
let dist = Math.sqrt(distToSegmentSquared(point, l[i], l[i + 1]));
if (dist < min) min = dist;
}
}
return min;
}
export interface PickedFeature {
feature: Feature;
layerName: string;
}
export class TileCache {
source: TileSource;
cache: Map<string, CacheEntry>;
inflight: Map<string, any[]>;
tileSize: number;
constructor(source: TileSource, tileSize: number) {
this.source = source;
this.cache = new Map<string, CacheEntry>();
this.inflight = new Map<string, any[]>();
this.tileSize = tileSize;
}
public queryFeatures(
lng: number,
lat: number,
zoom: number,
brushSize: number
): PickedFeature[] {
let projected = project([lat, lng]);
var normalized = new Point(
(projected.x + MAXCOORD) / (MAXCOORD * 2),
1 - (projected.y + MAXCOORD) / (MAXCOORD * 2)
);
if (normalized.x > 1)
normalized.x = normalized.x - Math.floor(normalized.x);
let on_zoom = normalized.mult(1 << zoom);
let tile_x = Math.floor(on_zoom.x);
let tile_y = Math.floor(on_zoom.y);
const idx = toIndex({ z: zoom, x: tile_x, y: tile_y });
let retval: PickedFeature[] = [];
let entry = this.cache.get(idx);
if (entry) {
const center = {
x: (on_zoom.x - tile_x) * this.tileSize,
y: (on_zoom.y - tile_y) * this.tileSize,
};
for (let [layer_name, layer_arr] of entry.data.entries()) {
for (let feature of layer_arr) {
// rough check by bbox
// if ((query_bbox.maxX >= feature.bbox.minX && feature.bbox.maxX >= query_bbox.minX) &&
// (query_bbox.maxY >= feature.bbox.minY && feature.bbox.maxY >= query_bbox.minY)) {
// }
if (feature.geomType == GeomType.Point) {
if (pointMinDistToPoints(center, feature.geom) < brushSize) {
retval.push({ feature, layerName: layer_name });
}
} else if (feature.geomType == GeomType.Line) {
if (pointMinDistToLines(center, feature.geom) < brushSize) {
retval.push({ feature, layerName: layer_name });
}
} else {
if (pointInPolygon(center, feature.geom)) {
retval.push({ feature, layerName: layer_name });
}
}
}
}
}
return retval;
}
public async get(c: Zxy): Promise<Map<string, Feature[]>> {
const idx = toIndex(c);
return new Promise((resolve, reject) => {
let entry = this.cache.get(idx);
if (entry) {
entry.used = performance.now();
resolve(entry.data);
} else {
let ifentry = this.inflight.get(idx);
if (ifentry) {
ifentry.push([resolve, reject]);
} else {
this.inflight.set(idx, []);
this.source
.get(c, this.tileSize)
.then((tile) => {
this.cache.set(idx, { used: performance.now(), data: tile });
let ifentry2 = this.inflight.get(idx);
if (ifentry2) ifentry2.forEach((f) => f[0](tile));
this.inflight.delete(idx);
resolve(tile);
if (this.cache.size >= 64) {
let min_used = +Infinity;
let min_key = undefined;
this.cache.forEach((value, key) => {
if (value.used < min_used) {
min_used = value.used;
min_key = key;
}
});
if (min_key) this.cache.delete(min_key);
}
})
.catch((e) => {
let ifentry2 = this.inflight.get(idx);
if (ifentry2) ifentry2.forEach((f) => f[1](e));
this.inflight.delete(idx);
reject(e);
});
}
}
});
}
} | the_stack |
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import {
FeatureEnum,
IOrganization,
IRolePermission,
IUser,
PermissionsEnum
} from '@gauzy/contracts';
import { NbMenuItem } from '@nebular/theme';
import { TranslateService } from '@ngx-translate/core';
import { filter, map, mergeMap, tap } from 'rxjs/operators';
import { NgxPermissionsService } from 'ngx-permissions';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { chain } from 'underscore';
import { distinctUntilChange, isNotEmpty } from '@gauzy/common-angular';
import { SelectorService } from '../@core/utils/selector.service';
import { EmployeesService, Store, UsersService } from '../@core/services';
import {
DEFAULT_SELECTOR_VISIBILITY,
ISelectorVisibility,
SelectorBuilderService
} from '../@core/services/selector-builder';
import { ReportService } from './reports/all-report/report.service';
import { AuthStrategy } from '../@core/auth/auth-strategy.service';
import { TranslationBaseComponent } from '../@shared/language-base';
interface GaMenuItem extends NbMenuItem {
data: {
translationKey: string; //Translation key for the title, mandatory for all items
permissionKeys?: PermissionsEnum[]; //Check permissions and hide item if any given permission is not present
featureKey?: FeatureEnum; //Check permissions and hide item if any given permission is not present
withOrganizationShortcuts?: boolean; //Declare if the sidebar item has organization level shortcuts
hide?: () => boolean; //Hide the menu item if this returns true
};
}
@UntilDestroy({ checkProperties: true })
@Component({
selector: 'ngx-pages',
styleUrls: ['pages.component.scss'],
template: `
<ngx-one-column-layout *ngIf="!!menu && user">
<nb-menu [items]="menu"></nb-menu>
<router-outlet></router-outlet>
</ngx-one-column-layout>
`
})
export class PagesComponent extends TranslationBaseComponent implements OnInit, OnDestroy {
isEmployee: boolean;
organization: IOrganization;
user: IUser;
menu: NbMenuItem[] = [];
reportMenuItems: NbMenuItem[] = [];
headerSelectors: ISelectorVisibility;
constructor(
private readonly employeeService: EmployeesService,
public readonly translate: TranslateService,
private readonly store: Store,
private readonly reportService: ReportService,
private readonly selectorService: SelectorService,
private readonly router: Router,
private readonly _activatedRoute: ActivatedRoute,
private readonly ngxPermissionsService: NgxPermissionsService,
private readonly usersService: UsersService,
private readonly authStrategy: AuthStrategy,
public readonly selectorBuilderService: SelectorBuilderService
) {
super(translate);
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this._activatedRoute),
map((route) => {
while (route.firstChild) route = route.firstChild;
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data)
)
.subscribe(({ selectors }: any) => {
this.headerSelectors = Object.assign(
{},
DEFAULT_SELECTOR_VISIBILITY,
selectors
);
Object.entries(this.headerSelectors).forEach(([id, value]) => {
selectorBuilderService.setSelectorsVisibility(id, value);
});
selectorBuilderService.getSelectorsVisibility();
});
}
getMenuItems(): GaMenuItem[] {
return [
{
title: 'Dashboard',
icon: 'home-outline',
link: '/pages/dashboard',
pathMatch: 'prefix',
home: true,
data: {
translationKey: 'MENU.DASHBOARD',
featureKey: FeatureEnum.FEATURE_DASHBOARD
}
},
{
title: 'Accounting',
icon: 'credit-card-outline',
data: {
translationKey: 'MENU.ACCOUNTING'
},
children: [
{
title: 'Estimates',
icon: 'file-outline',
link: '/pages/accounting/invoices/estimates',
data: {
translationKey: 'MENU.ESTIMATES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.ESTIMATES_VIEW
],
featureKey: FeatureEnum.FEATURE_ESTIMATE
}
},
{
title: 'Estimates Received',
icon: 'archive-outline',
link: '/pages/accounting/invoices/received-estimates',
data: {
translationKey: 'MENU.ESTIMATES_RECEIVED',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.ESTIMATES_VIEW
],
featureKey: FeatureEnum.FEATURE_ESTIMATE_RECEIVED
}
},
{
title: 'Invoices',
icon: 'file-text-outline',
link: '/pages/accounting/invoices',
pathMatch: 'full',
data: {
translationKey: 'MENU.INVOICES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.INVOICES_VIEW
],
featureKey: FeatureEnum.FEATURE_INVOICE
}
},
{
title: 'Invoices Recurring',
icon: 'flip-outline',
link: '/pages/accounting/invoices/recurring',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.RECURRING_INVOICES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.INVOICES_VIEW
],
featureKey: FeatureEnum.FEATURE_INVOICE_RECURRING
}
},
{
title: 'Invoices Received',
icon: 'archive',
link: '/pages/accounting/invoices/received-invoices',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.INVOICES_RECEIVED',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.INVOICES_VIEW
],
featureKey: FeatureEnum.FEATURE_INVOICE_RECEIVED
}
},
{
title: 'Income',
icon: 'plus-circle-outline',
link: '/pages/accounting/income',
data: {
translationKey: 'MENU.INCOME',
permissionKeys: [PermissionsEnum.ORG_INCOMES_VIEW],
featureKey: FeatureEnum.FEATURE_INCOME
}
},
{
title: 'Expenses',
icon: 'minus-circle-outline',
link: '/pages/accounting/expenses',
data: {
translationKey: 'MENU.EXPENSES',
permissionKeys: [PermissionsEnum.ORG_EXPENSES_VIEW],
featureKey: FeatureEnum.FEATURE_EXPENSE
}
},
{
title: 'Payments',
icon: 'clipboard-outline',
link: '/pages/accounting/payments',
data: {
translationKey: 'MENU.PAYMENTS',
permissionKeys: [PermissionsEnum.ORG_PAYMENT_VIEW],
featureKey: FeatureEnum.FEATURE_PAYMENT
}
}
]
},
{
title: 'Sales',
icon: 'trending-up-outline',
link: '/pages/sales',
data: {
translationKey: 'MENU.SALES',
permissionKeys: [PermissionsEnum.ORG_PROPOSALS_VIEW]
},
children: [
{
title: 'Proposals',
icon: 'paper-plane-outline',
link: '/pages/sales/proposals',
data: {
translationKey: 'MENU.PROPOSALS',
permissionKeys: [
PermissionsEnum.ORG_PROPOSALS_VIEW
],
featureKey: FeatureEnum.FEATURE_PROPOSAL
}
},
{
title: 'Estimates',
icon: 'file-outline',
link: '/pages/sales/invoices/estimates',
data: {
translationKey: 'MENU.ESTIMATES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.ESTIMATES_VIEW
],
featureKey: FeatureEnum.FEATURE_PROPOSAL
}
},
{
title: 'Invoices',
icon: 'file-text-outline',
link: '/pages/sales/invoices',
data: {
translationKey: 'MENU.INVOICES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.INVOICES_VIEW
],
featureKey: FeatureEnum.FEATURE_INVOICE
}
},
{
title: 'Invoices Recurring',
icon: 'flip-outline',
link: '/pages/sales/invoices/recurring',
data: {
translationKey: 'MENU.RECURRING_INVOICES',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.INVOICES_VIEW
],
featureKey: FeatureEnum.FEATURE_INVOICE_RECURRING
}
},
{
title: 'Payments',
icon: 'clipboard-outline',
link: '/pages/sales/payments',
data: {
translationKey: 'MENU.PAYMENTS',
permissionKeys: [PermissionsEnum.ORG_PAYMENT_VIEW],
featureKey: FeatureEnum.FEATURE_PAYMENT
}
},
{
title: 'Pipelines',
icon: 'funnel-outline',
link: '/pages/sales/pipelines',
data: {
translationKey: 'MENU.PIPELINES',
permissionKeys: [
PermissionsEnum.VIEW_SALES_PIPELINES
],
featureKey: FeatureEnum.FEATURE_PIPELINE
}
}
]
},
{
title: 'Tasks',
icon: 'browser-outline',
link: '/pages/tasks',
data: {
translationKey: 'MENU.TASKS'
},
children: [
{
title: 'Dashboard',
icon: 'list-outline',
link: '/pages/tasks/dashboard',
data: {
translationKey: 'MENU.DASHBOARD',
featureKey: FeatureEnum.FEATURE_DASHBOARD_TASK
}
},
{
title: 'My Tasks',
icon: 'person-outline',
link: '/pages/tasks/me',
data: {
translationKey: 'MENU.MY_TASKS',
hide: () => !this.isEmployee,
featureKey: FeatureEnum.FEATURE_MY_TASK
}
},
{
title: "Team's Tasks",
icon: 'people-outline',
link: '/pages/tasks/team',
data: {
translationKey: 'MENU.TEAM_TASKS',
featureKey: FeatureEnum.FEATURE_TEAM_TASK
}
}
]
},
{
title: 'Jobs',
icon: 'briefcase-outline',
link: '/pages/jobs',
data: {
translationKey: 'MENU.JOBS',
featureKey: FeatureEnum.FEATURE_JOB
},
children: [
{
title: 'Employee',
icon: 'people-outline',
link: '/pages/jobs/employee',
data: {
translationKey: 'MENU.EMPLOYEES',
permissionKeys: [
PermissionsEnum.ORG_JOB_EMPLOYEE_VIEW
]
}
},
{
title: 'Browse',
icon: 'list-outline',
link: '/pages/jobs/search',
data: {
translationKey: 'MENU.JOBS_SEARCH'
}
},
{
title: 'Matching',
icon: 'person-outline',
link: '/pages/jobs/matching',
data: {
translationKey: 'MENU.JOBS_MATCHING',
permissionKeys: [
PermissionsEnum.ORG_JOB_MATCHING_VIEW
]
}
},
{
title: 'Proposal Template',
icon: 'file-text-outline',
link: '/pages/jobs/proposal-template',
data: {
translationKey: 'MENU.PROPOSAL_TEMPLATE',
permissionKeys: [
PermissionsEnum.ORG_PROPOSAL_TEMPLATES_VIEW
]
}
}
]
},
{
title: 'Employees',
icon: 'people-outline',
data: {
translationKey: 'MENU.EMPLOYEES'
},
children: [
{
title: 'Manage',
icon: 'list-outline',
link: '/pages/employees',
pathMatch: 'full',
data: {
translationKey: 'MENU.MANAGE',
permissionKeys: [
PermissionsEnum.ORG_EMPLOYEES_VIEW
],
featureKey: FeatureEnum.FEATURE_EMPLOYEES
}
},
{
title: 'Time & Activity',
icon: 'trending-up-outline',
link: '/pages/employees/activity',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.TIME_ACTIVITY',
featureKey:
FeatureEnum.FEATURE_EMPLOYEE_TIME_ACTIVITY
}
},
{
title: 'Timesheets',
icon: 'clock-outline',
link: '/pages/employees/timesheets',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.TIMESHEETS',
featureKey: FeatureEnum.FEATURE_EMPLOYEE_TIMESHEETS
}
},
{
title: 'Appointments',
icon: 'calendar-outline',
link: '/pages/employees/appointments',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.APPOINTMENTS',
featureKey: FeatureEnum.FEATURE_EMPLOYEE_APPOINTMENT
}
},
{
title: 'Approvals',
icon: 'flip-2-outline',
link: '/pages/employees/approvals',
data: {
translationKey: 'MENU.APPROVALS',
featureKey: FeatureEnum.FEATURE_EMPLOYEE_APPROVAL
}
},
{
title: 'Employee Levels',
icon: 'bar-chart-outline',
link: `/pages/employees/employee-level`,
data: {
translationKey: 'MENU.EMPLOYEE_LEVEL',
permissionKeys: [PermissionsEnum.ALL_ORG_VIEW],
featureKey: FeatureEnum.FEATURE_EMPLOYEE_LEVEL
}
},
{
title: 'Positions',
icon: 'award-outline',
link: `/pages/employees/positions`,
data: {
translationKey: 'MENU.POSITIONS',
permissionKeys: [PermissionsEnum.ALL_ORG_VIEW],
featureKey: FeatureEnum.FEATURE_EMPLOYEE_POSITION
}
},
{
title: 'Time Off',
icon: 'eye-off-2-outline',
link: '/pages/employees/time-off',
data: {
translationKey: 'MENU.TIME_OFF',
permissionKeys: [PermissionsEnum.ORG_TIME_OFF_VIEW],
featureKey: FeatureEnum.FEATURE_EMPLOYEE_TIMEOFF
}
},
{
title: 'Recurring Expenses',
icon: 'flip-outline',
link: '/pages/employees/recurring-expenses',
data: {
translationKey: 'MENU.RECURRING_EXPENSE',
permissionKeys: [
PermissionsEnum.EMPLOYEE_EXPENSES_VIEW
],
featureKey:
FeatureEnum.FEATURE_EMPLOYEE_RECURRING_EXPENSE
}
},
{
title: 'Candidates',
icon: 'person-done-outline',
link: '/pages/employees/candidates',
data: {
translationKey: 'MENU.CANDIDATES',
permissionKeys: [
PermissionsEnum.ORG_CANDIDATES_VIEW
],
featureKey: FeatureEnum.FEATURE_EMPLOYEE_CANDIDATE
}
}
]
},
{
title: 'Organization',
icon: 'globe-2-outline',
data: {
translationKey: 'MENU.ORGANIZATION',
withOrganizationShortcuts: true
},
children: [
{
title: 'Manage',
icon: 'globe-2-outline',
pathMatch: 'prefix',
data: {
organizationShortcut: true,
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
urlPrefix: `/pages/organizations/edit/`,
urlPostfix: '',
translationKey: 'MENU.MANAGE',
featureKey: FeatureEnum.FEATURE_ORGANIZATION
}
},
{
title: 'Equipment',
icon: 'shopping-bag-outline',
link: '/pages/organization/equipment',
data: {
permissionKeys: [PermissionsEnum.ALL_ORG_VIEW],
translationKey: 'MENU.EQUIPMENT',
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_EQUIPMENT
}
},
{
title: 'Inventory',
icon: 'grid-outline',
link: '/pages/organization/inventory',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.INVENTORY',
permissionKeys: [PermissionsEnum.ALL_ORG_VIEW],
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_INVENTORY
}
},
{
title: 'Tags',
icon: 'pricetags-outline',
link: '/pages/organization/tags',
data: {
translationKey: 'MENU.TAGS',
featureKey: FeatureEnum.FEATURE_ORGANIZATION_TAG
}
},
{
title: 'Vendors',
icon: 'car-outline',
link: '/pages/organization/vendors',
data: {
translationKey: 'ORGANIZATIONS_PAGE.VENDORS',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey: FeatureEnum.FEATURE_ORGANIZATION_VENDOR
}
},
{
title: 'Projects',
icon: 'book-outline',
link: `/pages/organization/projects`,
data: {
translationKey: 'ORGANIZATIONS_PAGE.PROJECTS',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey: FeatureEnum.FEATURE_ORGANIZATION_PROJECT
}
},
{
title: 'Departments',
icon: 'briefcase-outline',
link: `/pages/organization/departments`,
data: {
translationKey: 'ORGANIZATIONS_PAGE.DEPARTMENTS',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_DEPARTMENT
}
},
{
title: 'Teams',
icon: 'people-outline',
link: `/pages/organization/teams`,
data: {
translationKey: 'ORGANIZATIONS_PAGE.EDIT.TEAMS',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey: FeatureEnum.FEATURE_ORGANIZATION_TEAM
}
},
{
title: 'Documents',
icon: 'file-text-outline',
link: `/pages/organization/documents`,
data: {
translationKey: 'ORGANIZATIONS_PAGE.DOCUMENTS',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_DOCUMENT
}
},
{
title: 'Employment Types',
icon: 'layers-outline',
link: `/pages/organization/employment-types`,
data: {
translationKey:
'ORGANIZATIONS_PAGE.EMPLOYMENT_TYPES',
permissionKeys: [PermissionsEnum.ALL_ORG_EDIT],
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_EMPLOYMENT_TYPE
}
},
{
title: 'Expense Recurring',
icon: 'flip-outline',
link: '/pages/organization/expense-recurring',
data: {
translationKey:
'ORGANIZATIONS_PAGE.EXPENSE_RECURRING',
permissionKeys: [PermissionsEnum.ORG_EXPENSES_VIEW],
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_RECURRING_EXPENSE
}
},
{
title: 'Help Center',
icon: 'question-mark-circle-outline',
link: '/pages/organization/help-center',
data: {
translationKey: 'ORGANIZATIONS_PAGE.HELP_CENTER',
featureKey:
FeatureEnum.FEATURE_ORGANIZATION_HELP_CENTER
}
}
]
},
{
title: 'Contacts',
icon: 'book-open-outline',
data: {
translationKey: 'MENU.CONTACTS',
permissionKeys: [
PermissionsEnum.ORG_CONTACT_VIEW,
PermissionsEnum.ALL_ORG_VIEW
],
featureKey: FeatureEnum.FEATURE_CONTACT
},
children: [
{
title: 'Visitors',
icon: 'book-open-outline',
link: `/pages/contacts/visitors`,
data: {
translationKey: 'CONTACTS_PAGE.VISITORS'
}
},
{
title: 'Leads',
icon: 'book-open-outline',
link: `/pages/contacts/leads`,
data: {
translationKey: 'CONTACTS_PAGE.LEADS'
}
},
{
title: 'Customers',
icon: 'book-open-outline',
link: `/pages/contacts/customers`,
data: {
translationKey: 'CONTACTS_PAGE.CUSTOMERS'
}
},
{
title: 'Clients',
icon: 'book-open-outline',
link: `/pages/contacts/clients`,
data: {
translationKey: 'CONTACTS_PAGE.CLIENTS'
}
}
]
},
{
title: 'Goals',
icon: 'flag-outline',
data: {
translationKey: 'MENU.GOALS'
},
children: [
{
title: 'Manage',
link: '/pages/goals',
pathMatch: 'full',
icon: 'list-outline',
data: {
translationKey: 'MENU.MANAGE',
featureKey: FeatureEnum.FEATURE_GOAL
}
},
{
title: 'Report',
link: '/pages/goals/reports',
icon: 'file-text-outline',
data: {
translationKey: 'MENU.REPORTS',
featureKey: FeatureEnum.FEATURE_GOAL_REPORT
}
},
{
title: 'Settings',
link: '/pages/goals/settings',
icon: 'settings-outline',
data: {
translationKey: 'MENU.SETTINGS',
featureKey: FeatureEnum.FEATURE_GOAL_SETTING
}
}
]
},
{
title: 'Reports',
icon: 'file-text-outline',
link: '/pages/reports',
data: {
translationKey: 'MENU.REPORTS',
featureKey: FeatureEnum.FEATURE_REPORT
},
children: [
{
title: 'All Reports',
link: '/pages/reports/all',
icon: 'bar-chart-outline',
data: {
translationKey: 'MENU.ALL_REPORTS'
}
},
...this.reportMenuItems
]
},
{
title: 'Admin',
group: true,
data: {
translationKey: 'MENU.ADMIN',
permissionKeys: [
PermissionsEnum.ORG_EMPLOYEES_VIEW,
PermissionsEnum.ORG_USERS_VIEW,
PermissionsEnum.ALL_ORG_EDIT,
PermissionsEnum.ALL_ORG_VIEW
]
}
},
{
title: 'Users',
icon: 'people-outline',
link: '/pages/users',
data: {
translationKey: 'MENU.USERS',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.ORG_USERS_VIEW
],
featureKey: FeatureEnum.FEATURE_USER
}
},
{
title: 'Organizations',
icon: 'globe-outline',
link: '/pages/organizations',
data: {
translationKey: 'MENU.ORGANIZATIONS',
permissionKeys: [
PermissionsEnum.ALL_ORG_VIEW,
PermissionsEnum.ORG_EXPENSES_EDIT
],
featureKey: FeatureEnum.FEATURE_ORGANIZATIONS
}
},
{
title: 'Integrations',
icon: 'pantone-outline',
link: '/pages/integrations',
pathMatch: 'prefix',
data: {
translationKey: 'MENU.INTEGRATIONS',
permissionKeys: [PermissionsEnum.INTEGRATION_VIEW],
featureKey: FeatureEnum.FEATURE_APP_INTEGRATION
}
},
{
title: 'Settings',
icon: 'settings-outline',
data: {
translationKey: 'MENU.SETTINGS'
},
children: [
{
title: 'General',
icon: 'edit-outline',
link: '/pages/settings/general',
data: {
translationKey: 'MENU.GENERAL',
featureKey: FeatureEnum.FEATURE_SETTING
}
},
{
title: 'Features',
icon: 'pantone-outline',
link: '/pages/settings/features',
data: {
translationKey: 'MENU.FEATURES',
permissionKeys: [
PermissionsEnum.ALL_ORG_EDIT,
PermissionsEnum.ALL_ORG_VIEW
]
}
},
{
title: 'Email History',
icon: 'email-outline',
link: '/pages/settings/email-history',
data: {
translationKey: 'MENU.EMAIL_HISTORY',
permissionKeys: [PermissionsEnum.VIEW_ALL_EMAILS],
featureKey: FeatureEnum.FEATURE_EMAIL_HISTORY
}
},
{
title: 'Email Templates',
icon: 'email-outline',
link: '/pages/settings/email-templates',
data: {
translationKey: 'MENU.EMAIL_TEMPLATES',
permissionKeys: [
PermissionsEnum.VIEW_ALL_EMAIL_TEMPLATES
],
featureKey: FeatureEnum.FEATURE_EMAIL_TEMPLATE
}
},
{
title: 'Accounting Templates',
icon: 'clipboard-outline',
link: '/pages/settings/accounting-templates',
data: {
translationKey: 'MENU.ACCOUNTING_TEMPLATES',
permissionKeys: [
PermissionsEnum.VIEW_ALL_ACCOUNTING_TEMPLATES
]
}
},
{
title: 'Import/Export',
icon: 'flip-outline',
link: '/pages/settings/import-export',
data: {
translationKey: 'MENU.IMPORT_EXPORT.IMPORT_EXPORT',
permissionKeys: [
PermissionsEnum.IMPORT_EXPORT_VIEW
],
featureKey: FeatureEnum.FEATURE_IMPORT_EXPORT
}
},
{
title: 'File storage',
icon: 'file',
link: '/pages/settings/file-storage',
data: {
translationKey: 'MENU.FILE_STORAGE',
permissionKeys: [PermissionsEnum.FILE_STORAGE_VIEW],
featureKey: FeatureEnum.FEATURE_FILE_STORAGE
}
},
{
title: 'Payment Gateways',
icon: 'credit-card-outline',
data: {
translationKey: 'MENU.PAYMENT_GATEWAYS',
permissionKeys: [
PermissionsEnum.PAYMENT_GATEWAY_VIEW
],
featureKey: FeatureEnum.FEATURE_PAYMENT_GATEWAY
}
},
{
title: 'SMS Gateways',
icon: 'at-outline',
link: '/pages/settings/sms-gateway',
data: {
translationKey: 'MENU.SMS_GATEWAYS',
permissionKeys: [PermissionsEnum.SMS_GATEWAY_VIEW],
featureKey: FeatureEnum.FEATURE_SMS_GATEWAY
}
},
{
title: 'Custom SMTP',
icon: 'at-outline',
link: '/pages/settings/custom-smtp',
data: {
translationKey: 'MENU.CUSTOM_SMTP',
permissionKeys: [PermissionsEnum.CUSTOM_SMTP_VIEW],
featureKey: FeatureEnum.FEATURE_SMTP
}
},
{
title: 'Roles & Permissions',
link: '/pages/settings/roles',
icon: 'award-outline',
data: {
translationKey: 'MENU.ROLES',
permissionKeys: [
PermissionsEnum.CHANGE_ROLES_PERMISSIONS
],
featureKey: FeatureEnum.FEATURE_ROLES_PERMISSION
}
},
{
title: 'Danger Zone',
link: '/pages/settings/danger-zone',
icon: 'alert-triangle-outline',
data: {
translationKey: 'MENU.DANGER_ZONE',
permissionKeys: [
PermissionsEnum.ACCESS_DELETE_ACCOUNT,
PermissionsEnum.ACCESS_DELETE_ALL_DATA
],
}
}
]
}
];
}
async ngOnInit() {
await this._createEntryPoint();
this._applyTranslationOnSmartTable();
this.store.user$
.pipe(
filter((user: IUser) => !!user),
tap(() => this.checkForEmployee()),
untilDestroyed(this)
)
.subscribe();
this.store.selectedOrganization$
.pipe(
filter((organization: IOrganization) => !!organization),
distinctUntilChange(),
tap((organization: IOrganization) => this.organization = organization),
tap(() => this.getReportsMenus()),
untilDestroyed(this)
)
.subscribe();
this.store.userRolePermissions$
.pipe(
filter((permissions: IRolePermission[]) => isNotEmpty(permissions)),
map((permissions) => permissions.map(({ permission }) => permission)),
tap((permissions) => this.ngxPermissionsService.loadPermissions(permissions)),
untilDestroyed(this)
)
.subscribe(() => {
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
});
this.router.events
.pipe(filter((event) => event instanceof NavigationEnd))
.pipe(untilDestroyed(this))
.subscribe((e) => {
this.loadItems(
this.selectorService.showSelectors(e['url'])
.showOrganizationShortcuts
);
});
this.reportService.menuItems$
.pipe(
distinctUntilChange(),
untilDestroyed(this)
)
.subscribe((menuItems) => {
if (menuItems) {
this.reportMenuItems = chain(menuItems)
.values()
.map((item) => {
return {
title: item.name,
link: `/pages/reports/${item.slug}`,
icon: item.iconClass,
data: {
translationKey: `${item.name}`
}
};
})
.value();
} else {
this.reportMenuItems = [];
}
this.menu = this.getMenuItems();
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
});
this.store.featureOrganizations$
.pipe(untilDestroyed(this))
.subscribe(() => {
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
});
this.store.featureTenant$.pipe(untilDestroyed(this)).subscribe(() => {
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
});
this.menu = this.getMenuItems();
}
async getReportsMenus() {
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
await this.reportService.getReportMenuItems({
tenantId,
organizationId
});
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
}
/*
* This is app entry point after login
*/
private async _createEntryPoint() {
const id = this.store.userId;
if (!id) return;
this.user = await this.usersService.getMe([
'employee',
'employee.contact',
'role',
'role.rolePermissions',
'tenant',
'tenant.featureOrganizations',
'tenant.featureOrganizations.feature'
]);
this.authStrategy.electronAuthentication({
user: this.user,
token: this.store.token
});
//When a new user registers & logs in for the first time, he/she does not have tenantId.
//In this case, we have to redirect the user to the onboarding page to create their first organization, tenant, role.
if (!this.user.tenantId) {
this.router.navigate(['/onboarding/tenant']);
return;
}
this.store.user = this.user;
//tenant enabled/disabled features for relatives organizations
const { tenant, role } = this.user;
this.store.featureTenant = tenant.featureOrganizations.filter(
(item) => !item.organizationId
);
//only enabled permissions assign to logged in user
this.store.userRolePermissions = role.rolePermissions.filter(
(permission) => permission.enabled
);
}
loadItems(withOrganizationShortcuts: boolean) {
this.menu.forEach((item) => {
this.refreshMenuItem(item, withOrganizationShortcuts);
});
}
refreshMenuItem(item, withOrganizationShortcuts) {
item.title = this.getTranslation(item.data.translationKey);
if (item.data.permissionKeys || item.data.hide) {
const anyPermission = item.data.permissionKeys
? item.data.permissionKeys.reduce((permission, key) => {
return this.store.hasPermission(key) || permission;
}, false)
: true;
item.hidden = !anyPermission || (item.data.hide && item.data.hide());
if (anyPermission && item.data.organizationShortcut) {
item.hidden = !withOrganizationShortcuts || !this.organization;
if (!item.hidden) {
item.link =
item.data.urlPrefix +
this.organization.id +
item.data.urlPostfix;
}
}
}
// enabled/disabled features from here
if (item.data.hasOwnProperty('featureKey') && item.hidden !== true) {
const { featureKey } = item.data;
const enabled = !this.store.hasFeatureEnabled(featureKey);
item.hidden = enabled || (item.data.hide && item.data.hide());
}
if (item.children) {
item.children.forEach((childItem) => {
this.refreshMenuItem(childItem, withOrganizationShortcuts);
});
}
}
checkForEmployee() {
const { tenantId, id: userId } = this.store.user;
this.employeeService
.getEmployeeByUserId(userId, [], { tenantId })
.then(({ success }) => {
this.isEmployee = success;
});
}
private _applyTranslationOnSmartTable() {
this.translate.onLangChange.pipe(untilDestroyed(this)).subscribe(() => {
this.loadItems(
this.selectorService.showSelectors(this.router.url)
.showOrganizationShortcuts
);
});
}
ngOnDestroy() {}
} | the_stack |
import services = require('services/Service');
import site = require('Site');
import mapping = require('knockout.mapping');
function translateOrder(source) {
//source.OrderDate = services.fixJsonDates(source.OrderDate);
var order = mapping.fromJS(source);
var orderDetails = order.OrderDetails();
order.OrderDetails = ko.observableArray();
for (var i = 0; i < orderDetails.length; i++) {
orderDetails[i].Amount = ko.computed(function () {
return this.Price() * this.Quantity();
}, orderDetails[i]);
order.OrderDetails.push(orderDetails[i]);
}
order.ProductsAmount = ko.computed(function () {
var amount = 0;
for (var i = 0; i < orderDetails.length; i++) {
amount = amount + orderDetails[i].Amount();
}
return amount;
}, order);
order.StatusText = ko.computed(function () {
var status = this.Status();
switch (status) {
case 'WaitingForPayment':
return '待付款';
case 'Paid':
return '已付款';
case 'Send':
return '已发货';
case 'Canceled':
return '已取消';
case 'Finish':
return '已完成'
case 'Received':
return '已收货';
default:
//
return '';
}
}, order);
order.ReceiptInfoId = ko.observable();
order.ReceiptAddress.extend({ required: { message: '请填写收货信息' } });
return order;
};
function translateProductData(data) {
data.ImageUrls = (data.ImageUrl || '').split(',');
data.ImageUrl = data.ImageUrls[0];
var arr = [];
var obj = (data.Arguments || []) as Array<{ key: string, value: string }>; //JSON.parse(data.Arguments || '{}');
for (let i = 0; i < obj.length; i++) {
let item = obj[i];
arr.push({ Name: item.key, Value: item.value });
}
data.Arguments = arr;
// arr = [];
// obj = (data.Fields || []) as Array<{ key: string, value: string }>;
// for (let i = 0; i < obj.length; i++) {
// let item = obj[i];
// arr.push({ Name: item.key, Options: [{ Name: item.value, Value: item.value, Selected: true }] });
// }
// data.CustomProperties = arr;
return data;
}
function translateComment(data) {
data.Stars = new Array<string>();
for (var i = 0; i < data.Score; i++) {
data.Stars.push('*');
}
//data.ImageDatas = data.ImageDatas || '';
//data.ImageThumbs = data.ImageThumbs || '';
if (data.ImageDatas)
data.ImageDatas = <string[]>(<string>data.ImageDatas).split(site.config.imageDataSpliter);
else
data.ImageDatas = [];
if (data.ImageThumbs)
data.ImageThumbs = <string[]>(<string>data.ImageThumbs).split(site.config.imageDataSpliter);
else
data.ImageThumbs = [];
return data;
}
class ShoppingService {
getCategories = (parentName: string = undefined): JQueryPromise<any> => {
var result = services.get(services.config.shopServiceUrl, 'Product/GetCategories', { parentName: parentName });
return result;
}
getCategory = (categoryId): JQueryPromise<any> => {
var result = services.get(services.config.shopServiceUrl, 'Product/GetCategory', { categoryId: categoryId });
return result;
}
getProductsByCategory = (categoryName): JQueryPromise<any> => {
var result = services.get(services.config.shopServiceUrl, 'Product/GetProducts',
{ categoryName: categoryName });
return result;
}
getProductsByBrand = (brand): JQueryPromise<any> => {
var result = services.get(services.config.shopServiceUrl, 'Product/GetProducts', { brand: brand });
return result;
}
getProduct = (productId): JQueryPromise<any> => {
var result = services.get(services.config.shopServiceUrl, 'Product/GetProduct', { productId: productId })
.then(translateProductData);
return result;
}
getProducts = (args) => {
var result = $.Deferred();
services.get(services.config.shopServiceUrl, 'Product/GetProducts', args)
.fail($.proxy(function (args) {
this._result.reject(args);
}, { _result: result }))
.done($.proxy(function (args) {
var products = args.Products;
var filters = args.Filters;
this._result.resolve(products, filters);
}, { _result: result }));
return result;
}
getProductIntroduce = (productId) => {
return services.get<any>(services.config.shopServiceUrl, 'Product/GetProductIntroduce', { productId: productId });
}
findProductsByName = (name) => {
var result = services.get(services.config.shopServiceUrl, 'Product/FindProducts', { name: name });
return result;
}
createOrder = (productIds, quantities) => {
/// <param name="productids" type="Array">所购买产品的编号</param>
/// <param name="quantities" type="Array"></param>
var result = services.callRemoteMethod('Order/CreateOrder', { productIds: productIds, quantities: quantities })
.then(function (order) {
return translateOrder(order);
});
return result;
}
getOrder = (orderId) => {
/// <param name="orderId">订单编号</param>
/// <returns type="models.order"/>
var result = services.get(services.config.shopServiceUrl, 'Order/GetOrder', { orderId: orderId }).then(function (order) {
return translateOrder(order);
});
return result;
}
confirmOrder = (args) => {//orderId, couponCode
var result = services.callRemoteMethod('Order/ConfirmOrder', args);
return result;
}
useCoupon = (orderId: string, couponCode: string) => {
return services.callRemoteMethod('Order/UseCoupon', { orderId: orderId, couponCode: couponCode });
}
getMyOrders = (status, pageIndex, lastDateTime) => {
/// <summary>获取当前登录用户的订单</summary>
/// <param name="lastDateTime" type="Date"/>
var filters = [];
if (status) {
//filter = 'it.Status=="' + status + '"';
filters.push('Status=="' + status + '"');
}
if (lastDateTime) {
var m = lastDateTime.getMilliseconds();
var d = lastDateTime.toFormattedString('G') + '.' + m;
filters.push('CreateDateTime < #' + d + '#');
}
var filter = filters.join(' && ');
var args = { filter: filter, StartRowIndex: pageIndex * services.defaultPageSize, MaximumRows: services.defaultPageSize };
var result = services.get<any[]>(services.config.shopServiceUrl, 'Order/GetMyOrders', args)
.then(function (orders) {
for (var i = 0; i < orders.length; i++) {
orders[i] = translateOrder(orders[i]);
}
return orders;
});
return result;
}
getMyLastestOrders = (status, dateTime) => {
/// <param name="dateTime" type="Date"/>
var d;
if (dateTime) {
var m = dateTime.getMilliseconds();
dateTime = dateTime.toFormattedString('G') + '.' + m;
}
return services.callRemoteMethod('Order/GetMyLastestOrders', { dateTime: d, status: status })
.then(function (orders) {
for (var i = 0; i < orders.length; i++) {
orders[i] = translateOrder(orders[i]);
}
return orders;
});
}
getMyOrderList = (status, pageIndex, lastDateTime): JQueryPromise<Array<any>> => {
var filters = [];
//if (status) {
// filters.push('Status=="' + status + '"');
//}
//var filter = filters.join(' && ');
var args = { status, StartRowIndex: pageIndex * services.defaultPageSize, MaximumRows: services.defaultPageSize };
var result = services.get<Array<any>>(services.config.shopServiceUrl, 'Order/GetMyOrderList', args)
.then(function (orders) {
//for (var i = 0; i < orders.length; i++) {
// orders[i] = translateOrder(orders[i]);
//}
return orders;
});
result.done($.proxy(function (orders) {
this._result.loadCompleted = orders.length < services.defaultPageSize;
}, { _result: result }));
return result;
}
getBrands = (args) => {
var result = services.callRemoteMethod('Product/GetBrands', args).then(function (data) {
return data;
});
return result;
}
getBrand = (itemId: string): JQueryPromise<any> => {
var result = services.callRemoteMethod('Product/GetBrand', { brandId: itemId });
return result;
}
getShippingInfo = (orderId) => {
var result = services.callRemoteMethod('Order/GetShippingInfo', { orderId: orderId });
return result;
}
changeReceipt = (orderId, receiptId) => {
var result = services.callRemoteMethod('Order/ChangeReceipt', { orderId: orderId, receiptId: receiptId });
return result;
}
allowPurchase(orderId) {
var result = services.callRemoteMethod('Order/AllowPurchase', { orderId: orderId });
return result;
}
getProductStock = (productId) => {
/// <returns type="jQuery.Deferred"/>
return services.get<any[]>(services.config.shopServiceUrl, 'Product/GetProductStocks', { productIds: productId })
.then(o => {
return o[0] ? o[0] : { Quantity: null };
});
}
balancePay = (orderId, amount) => {
/// <returns type="jQuery.Deferred"/>
return services.callRemoteMethod('Order/BalancePay', { orderId: orderId, amount: amount });
}
getProductCustomProperties = (productId: string): JQueryPromise<any> => {
return services.callMethod(services.config.shopServiceUrl, 'Product/GetCustomProperties', { productId: productId });
}
getProductByPropertyFilter(groupId, data): JQueryPromise<any> {
var d = { groupId, filter: JSON.stringify(data) };
return services.callMethod(services.config.shopServiceUrl, 'Product/GetProductByPropertyFilter', d)
.then(translateProductData);
}
getProductComments(productId: string, pageSize: number): JQueryPromise<Array<any>> {
var data = { productId, pageSize };
return services.get<any[]>(services.config.shopServiceUrl, 'Product/GetProductCommentList', data).then((datas) => {
for (var i = 0; i < datas.length; i++) {
datas[i] = translateComment(datas[i]);
}
return datas;
});
}
favorProduct(productId: string, productName: string): JQueryPromise<any> {
var data = { productId, productName };
return services.callMethod(services.config.shopServiceUrl, 'Product/FavorProduct', data);
}
isFavored(productId: string): JQueryPromise<boolean> {
if (!site.storage.token) {
return $.Deferred<boolean>().resolve(false);
}
var data = { productId };
return services.get(services.config.shopServiceUrl, 'Product/IsFavored', data);
}
getFavorProducts(): LoadListPromise<any> {
var result = <LoadListPromise<any>>services.callMethod(services.config.shopServiceUrl, 'Product/GetFavorProducts');
return result;
}
unFavorProduct(productId: string) {
return services.callMethod(services.config.shopServiceUrl, 'Product/UnFavorProduct', { productId });
}
}
window['services']['shopping'] = window['services']['shopping'] || new ShoppingService();
export = <ShoppingService>window['services']['shopping']; | the_stack |
module android.content.res{
import DisplayMetrics = android.util.DisplayMetrics;
import Drawable = android.graphics.drawable.Drawable;
import Color = android.graphics.Color;
import SynchronizedPool = android.util.Pools.SynchronizedPool;
import ColorDrawable = android.graphics.drawable.ColorDrawable;
export class Resources{
private static instance = new Resources();
// Pool of TypedArrays targeted to this Resources object.
mTypedArrayPool:SynchronizedPool<TypedArray> = new SynchronizedPool<TypedArray>(5);
private displayMetrics:DisplayMetrics;
private context:Context;
//value set in app's R.ts
static _AppBuildImageFileFinder: (refString:string)=>Drawable = null;
static _AppBuildXmlFinder: (refString:string)=>HTMLElement = null;
static _AppBuildValueFinder: (refString:string)=>HTMLElement = null;
constructor(context?:Context) {
this.context = context;
// FIXME will memory leak (Activity ref with window)
window.addEventListener('resize', ()=>{
if(this.displayMetrics){
this.fillDisplayMetrics(this.displayMetrics);
}
});
}
static getSystem():Resources {
return Resources.instance;
}
private static from(context:Context){
return context.getResources();
}
static getDisplayMetrics():DisplayMetrics {
return Resources.instance.getDisplayMetrics();
}
getDisplayMetrics():DisplayMetrics {
if(this.displayMetrics) return this.displayMetrics;
this.displayMetrics = new DisplayMetrics();
this.fillDisplayMetrics(this.displayMetrics);
return this.displayMetrics;
}
private fillDisplayMetrics(displayMetrics:DisplayMetrics){
let density = window.devicePixelRatio;
displayMetrics.xdpi = window.screen.deviceXDPI || DisplayMetrics.DENSITY_DEFAULT;
displayMetrics.ydpi = window.screen.deviceYDPI || DisplayMetrics.DENSITY_DEFAULT;
displayMetrics.density = density;
displayMetrics.densityDpi = density * DisplayMetrics.DENSITY_DEFAULT;
displayMetrics.scaledDensity = density;
let contentEle = this.context ? this.context.androidUI.androidUIElement : document.documentElement;
displayMetrics.widthPixels = contentEle.offsetWidth * density;
displayMetrics.heightPixels = contentEle.offsetHeight * density;
}
getDefStyle(refString:string):any {
if (refString === '@null') return null;
if(refString.startsWith('@android:attr/')){
refString = refString.substring('@android:attr/'.length);
return android.R.attr[refString];
}
}
/**
* @param refString @drawable/xxx, @android:drawable/xxx
*/
getDrawable(refString:string):Drawable {
if (refString === '@null') return null;
if(refString.startsWith('@android:drawable/')){
refString = refString.substring('@android:drawable/'.length);
return android.R.drawable[refString] || android.R.image[refString];
}
if(refString.startsWith('@android:color/')){
refString = refString.substring('@android:color/'.length);
let color = android.R.color[refString];
if(color instanceof ColorStateList){
color = (<ColorStateList>color).getDefaultColor();
}
return new ColorDrawable(color);
}
if(Resources._AppBuildImageFileFinder){
let drawable = Resources._AppBuildImageFileFinder(refString);
if(drawable) return drawable;
}
if(!refString.startsWith('@')){
refString = '@drawable/' + refString;
}
let ele = this.getXml(refString);
if(ele){
return Drawable.createFromXml(this, ele);
}
ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
if(text.startsWith('@android:drawable/') || text.startsWith('@drawable/')) {
return this.getDrawable(text);
}
if(text.startsWith('@android:color/') || text.startsWith('@color/')) {
let color = this.getColor(text);
return new ColorDrawable(color);
}
return Drawable.createFromXml(this, ele);
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* @param refString @color/xxx @android:color/xxx
*/
getColor(refString:string):number {
if(refString.startsWith('@android:color/')){
refString = refString.substring('@android:color/'.length);
let color = android.R.color[refString];
if(color instanceof ColorStateList){
color = (<ColorStateList>color).getDefaultColor();
}
return color;
}else{
if(!refString.startsWith('@color/')){
refString = '@color/' + refString;
}
let ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
if(text.startsWith('@android:color/') || text.startsWith('@color/')){
return this.getColor(text);
}
return Color.parseColor(text);
}
ele = this.getXml(refString);
if(ele){
let colorList = ColorStateList.createFromXml(this, ele);
if(colorList) return colorList.getDefaultColor();
}
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* @param refString @color/xxx @android:color/xxx
*/
getColorStateList(refString:string):ColorStateList {
if (refString === '@null') return null;
if(refString.startsWith('@android:color/')){
refString = refString.substring('@android:color/'.length);
let color = android.R.color[refString];
if(typeof color === "number"){
color = ColorStateList.valueOf(color);
}
return color;
} else {
if(!refString.startsWith('@color/')){
refString = '@color/' + refString;
}
let ele = this.getXml(refString);
if(ele){
return ColorStateList.createFromXml(this, ele);
}
ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
if(text.startsWith('@android:color/') || text.startsWith('@color/')){
return this.getColorStateList(text);
}
return ColorStateList.valueOf(Color.parseColor(text));
}
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* Retrieve a dimensional for a particular resource reference. Unit
* conversions are based on the current {@link DisplayMetrics} associated
* with the resources.
*
* @return Resource dimension value multiplied by the appropriate
* metric.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @see #getDimensionPixelOffset
* @see #getDimensionPixelSize
*/
getDimension(refString:string, baseValue=0): number {
if(!refString.startsWith('@dimen/')) refString = '@dimen/' + refString;
let ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
return android.util.TypedValue.complexToDimension(text, baseValue, this.getDisplayMetrics());
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* Retrieve a dimensional for a particular resource reference for use
* as an offset in raw pixels. This is the same as
* {@link #getDimension}, except the returned value is converted to
* integer pixels for you. An offset conversion involves simply
* truncating the base value to an integer.
*
* @return Resource dimension value multiplied by the appropriate
* metric and truncated to integer pixels.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @see #getDimension
* @see #getDimensionPixelSize
*/
getDimensionPixelOffset(refString:string, baseValue=0): number {
if(!refString.startsWith('@dimen/')) refString = '@dimen/' + refString;
let ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
return android.util.TypedValue.complexToDimensionPixelOffset(text, baseValue, this.getDisplayMetrics());
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
getDimensionPixelSize(refString:string, baseValue=0): number {
if(!refString.startsWith('@dimen/')) refString = '@dimen/' + refString;
let ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
return android.util.TypedValue.complexToDimensionPixelSize(text, baseValue, this.getDisplayMetrics());
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
getBoolean(refString:string):boolean {
if(!refString.startsWith('@bool/')) refString = '@bool/' + refString;
let ele = this.getValue(refString);
if(ele){
let text = ele.innerText;
return text == 'true'
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
getInteger(refString:string):number {
if(!refString.startsWith('@integer/')) refString = '@integer/' + refString;
let ele = this.getValue(refString);
if(ele){
return parseInt(ele.innerText);
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
getIntArray(refString:string):number[] {
if(!refString.startsWith('@array/')) refString = '@array/' + refString;
let ele = this.getValue(refString);
if(ele){
let intArray:number[] = [];
for(let child of Array.from(ele.children)){
intArray.push(parseInt((<HTMLElement>child).innerText));
}
return intArray;
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
getFloat(refString:string):number {
return this.getDimension(refString);
}
/**
* @param refString @string/xxx @android:string/xxx
*/
getString(refString:string):string {
if(refString.startsWith('@android:string/')){
refString = refString.substring('@android:string/'.length);
return android.R.string_[refString];
}
if(!refString.startsWith('@string/')) refString = '@string/' + refString;
let ele = this.getValue(refString);
if(ele){
return ele.innerText;
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* @param refString @array/xxx @android:array/xxx
*/
getStringArray(refString:string):string[] {
if(!refString.startsWith('@array/')) refString = '@array/' + refString;
let ele = this.getValue(refString);
if(ele){
let stringArray:string[] = [];
for(let child of Array.from(ele.children)){
stringArray.push((<HTMLElement>child).innerText);
}
return stringArray;
}
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* @param refString @layout/xxx, @android:layout/xxx
*/
getLayout(refString:string):HTMLElement {
if(!refString || !refString.trim().startsWith('@')) return null;
if (refString === '@null') return null;
if(refString.startsWith('@android:layout/')){
refString = refString.substring('@android:layout/'.length);
return android.R.layout.getLayoutData(refString);
}
if(!refString.startsWith('@layout/')) refString = '@layout/' + refString;
let ele = this.getXml(refString);
if(ele) return ele;
throw new Error("NotFoundException: Resource " + refString + " is not found");
}
/**
* @param refString @anim/xxx, @android:anim/xxx
*/
getAnimation(refString:string):android.view.animation.Animation {
if (refString === '@null') return null;
if(!refString || !refString.trim().startsWith('@')) return null;
if(refString.startsWith('@android:anim/')){
refString = refString.substring('@android:anim/'.length);
return android.R.anim[refString];
}
// if(refString.startsWith('@anim/')){
// refString = refString.substring('@anim/'.length);
// return window.R.anim[refString];
// }
}
private getStyleAsMap(refString:string):Map<string, string>{
if (refString === '@null') return null;
if(!refString.startsWith('@style/')){
refString = '@style/' + refString;
}
let styleMap = new Map<string, string>();
const parseStyle = (refString:string)=>{
let styleXml = this.getValue(refString);
if(!styleXml) return;
//merge attr 'parent'
let parent = styleXml.getAttribute('parent');
if(parent){
if(!parent.startsWith('@style/')){
parent = '@style/' + parent;
}
parseStyle(parent);
}
//merge attr name's parent
let styleName = refString.substring('@style/'.length);
if(styleName.includes('.')){
let parts = styleName.split('.');
parts.shift();
let nameParent = parts.join('.');
parseStyle('@style/' + nameParent);
}
for(let item of Array.from(styleXml.children)){
let name = (<Element>item).getAttribute('name');
if(name){
styleMap.set(name, (<HTMLElement>item).innerText);
}
}
};
parseStyle(refString);
return styleMap;
}
/**
* Return an Xml file through which you can read a generic XML
* resource for the given resource.
* @param refString @layout/xxx, @drawable/xxx, @color/xxx
*/
getXml(refString:string):HTMLElement {
if (refString === '@null') return null;
if(Resources._AppBuildXmlFinder) return Resources._AppBuildXmlFinder(refString);
}
/**
* Return the raw data associated with a resource reference string.
* @param refString @string/xxx, @color/xxx, @array/xxx, ...
* @param resolveRefs If true, a resource that is a reference to another
* resource will be followed so that you receive the
* actual final resource data. If false, the TypedValue
* will be filled in with the reference itself.
*/
getValue(refString:string, resolveRefs=true):HTMLElement {
if (refString === '@null') return null;
if(Resources._AppBuildValueFinder){
let ele = Resources._AppBuildValueFinder(refString);
if(!ele) return null;
if(resolveRefs && ele.children.length==0){
let str = ele.innerText;
if(str.startsWith('@')){
return this.getValue(refString, true) || ele;
}
}
return ele;
}
}
/**
* Retrieve a set of basic attribute values from an AttributeSet, not
* performing styling of them using a theme and/or style resources.
*
* @param attrs The specific attributes to be retrieved.
* @return Returns a TypedArray holding an array of the attribute values.
* Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
* when done with it.
*
* @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
*/
public obtainAttributes(attrs:HTMLElement):TypedArray {
return TypedArray.obtain(this, attrs);
}
/**
* Retrieve styled attribute information.
*/
public obtainStyledAttributes(attrs:HTMLElement, defStyleAttr:Map<string, string>):TypedArray {
return TypedArray.obtain(this, attrs, defStyleAttr);
}
}
} | the_stack |
import vm, {Context} from 'vm';
import {ModuleMocker, fn, mocked, spyOn} from '../';
describe('moduleMocker', () => {
let moduleMocker: ModuleMocker;
let mockContext: Context;
let mockGlobals: typeof globalThis;
beforeEach(() => {
mockContext = vm.createContext();
mockGlobals = vm.runInNewContext('this', mockContext);
moduleMocker = new ModuleMocker(mockGlobals);
});
describe('getMetadata', () => {
it('returns the function `name` property', () => {
function x() {}
const metadata = moduleMocker.getMetadata(x);
expect(x.name).toBe('x');
expect(metadata.name).toBe('x');
});
it('mocks constant values', () => {
const metadata = moduleMocker.getMetadata(Symbol.for('bowties.are.cool'));
expect(metadata.value).toEqual(Symbol.for('bowties.are.cool'));
expect(moduleMocker.getMetadata('banana').value).toEqual('banana');
expect(moduleMocker.getMetadata(27).value).toEqual(27);
expect(moduleMocker.getMetadata(false).value).toEqual(false);
expect(moduleMocker.getMetadata(Infinity).value).toEqual(Infinity);
});
it('does not retrieve metadata for arrays', () => {
const array = [1, 2, 3];
const metadata = moduleMocker.getMetadata(array);
expect(metadata.value).toBeUndefined();
expect(metadata.members).toBeUndefined();
expect(metadata.type).toEqual('array');
});
it('does not retrieve metadata for undefined', () => {
const metadata = moduleMocker.getMetadata(undefined);
expect(metadata.value).toBeUndefined();
expect(metadata.members).toBeUndefined();
expect(metadata.type).toEqual('undefined');
});
it('does not retrieve metadata for null', () => {
const metadata = moduleMocker.getMetadata(null);
expect(metadata.value).toBeNull();
expect(metadata.members).toBeUndefined();
expect(metadata.type).toEqual('null');
});
it('retrieves metadata for ES6 classes', () => {
class ClassFooMock {
bar() {}
}
const fooInstance = new ClassFooMock();
const metadata = moduleMocker.getMetadata(fooInstance);
expect(metadata.type).toEqual('object');
expect(metadata.members.constructor.name).toEqual('ClassFooMock');
});
it('retrieves synchronous function metadata', () => {
function functionFooMock() {}
const metadata = moduleMocker.getMetadata(functionFooMock);
expect(metadata.type).toEqual('function');
expect(metadata.name).toEqual('functionFooMock');
});
it('retrieves asynchronous function metadata', () => {
async function asyncFunctionFooMock() {}
const metadata = moduleMocker.getMetadata(asyncFunctionFooMock);
expect(metadata.type).toEqual('function');
expect(metadata.name).toEqual('asyncFunctionFooMock');
});
it("retrieves metadata for object literals and it's members", () => {
const metadata = moduleMocker.getMetadata({
bar: 'two',
foo: 1,
});
expect(metadata.type).toEqual('object');
expect(metadata.members.bar.value).toEqual('two');
expect(metadata.members.bar.type).toEqual('constant');
expect(metadata.members.foo.value).toEqual(1);
expect(metadata.members.foo.type).toEqual('constant');
});
it('retrieves Date object metadata', () => {
const metadata = moduleMocker.getMetadata(Date);
expect(metadata.type).toEqual('function');
expect(metadata.name).toEqual('Date');
expect(metadata.members.now.name).toEqual('now');
expect(metadata.members.parse.name).toEqual('parse');
expect(metadata.members.UTC.name).toEqual('UTC');
});
});
describe('generateFromMetadata', () => {
it('forwards the function name property', () => {
function foo() {}
const mock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(foo),
);
expect(mock.name).toBe('foo');
});
it('fixes illegal function name properties', () => {
function getMockFnWithOriginalName(name) {
const fn = () => {};
Object.defineProperty(fn, 'name', {value: name});
return moduleMocker.generateFromMetadata(moduleMocker.getMetadata(fn));
}
expect(getMockFnWithOriginalName('1').name).toBe('$1');
expect(getMockFnWithOriginalName('foo-bar').name).toBe('foo$bar');
expect(getMockFnWithOriginalName('foo-bar-2').name).toBe('foo$bar$2');
expect(getMockFnWithOriginalName('foo-bar-3').name).toBe('foo$bar$3');
expect(getMockFnWithOriginalName('foo/bar').name).toBe('foo$bar');
expect(getMockFnWithOriginalName('foo𠮷bar').name).toBe('foo𠮷bar');
});
it('special cases the mockConstructor name', () => {
function mockConstructor() {}
const mock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(mockConstructor),
);
// Depends on node version
expect(!mock.name || mock.name === 'mockConstructor').toBeTruthy();
});
it('wont interfere with previous mocks on a shared prototype', () => {
const ClassFoo = function () {};
ClassFoo.prototype.x = () => {};
const ClassFooMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(ClassFoo),
);
const foo = new ClassFooMock();
const bar = new ClassFooMock();
foo.x.mockImplementation(() => 'Foo');
bar.x.mockImplementation(() => 'Bar');
expect(foo.x()).toBe('Foo');
expect(bar.x()).toBe('Bar');
});
it('does not mock non-enumerable getters', () => {
const foo = Object.defineProperties(
{},
{
nonEnumGetter: {
get: () => {
throw new Error();
},
},
nonEnumMethod: {
value: () => {},
},
},
);
const mock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(foo),
);
expect(typeof foo.nonEnumMethod).toBe('function');
expect(mock.nonEnumMethod.mock).toBeDefined();
expect(mock.nonEnumGetter).toBeUndefined();
});
it('mocks getters of ES modules', () => {
const foo = Object.defineProperties(
{},
{
__esModule: {
value: true,
},
enumGetter: {
enumerable: true,
get: () => 10,
},
},
);
const mock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(foo),
);
expect(mock.enumGetter).toBeDefined();
});
it('mocks ES2015 non-enumerable methods', () => {
class ClassFoo {
foo() {}
toString() {
return 'Foo';
}
}
const ClassFooMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(ClassFoo),
);
const foo = new ClassFooMock();
const instanceFoo = new ClassFoo();
const instanceFooMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(instanceFoo),
);
expect(typeof foo.foo).toBe('function');
expect(typeof instanceFooMock.foo).toBe('function');
expect(instanceFooMock.foo.mock).toBeDefined();
expect(instanceFooMock.toString.mock).toBeDefined();
});
it('mocks ES2015 non-enumerable static properties and methods', () => {
class ClassFoo {
static foo() {}
static fooProp: Function;
}
ClassFoo.fooProp = () => {};
class ClassBar extends ClassFoo {}
const ClassBarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(ClassBar),
);
expect(typeof ClassBarMock.foo).toBe('function');
expect(typeof ClassBarMock.fooProp).toBe('function');
expect(ClassBarMock.foo.mock).toBeDefined();
expect(ClassBarMock.fooProp.mock).toBeDefined();
});
it('mocks methods in all the prototype chain (null prototype)', () => {
const Foo = Object.assign(Object.create(null), {foo() {}});
const Bar = Object.assign(Object.create(Foo), {bar() {}});
const BarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(Bar),
);
expect(typeof BarMock.foo).toBe('function');
expect(typeof BarMock.bar).toBe('function');
});
it('does not mock methods from Object.prototype', () => {
const Foo = {foo() {}};
const Bar = Object.assign(Object.create(Foo), {bar() {}});
const BarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(Bar),
);
expect(BarMock).toBeInstanceOf(mockGlobals.Object);
expect(
Object.prototype.hasOwnProperty.call(BarMock, 'hasOwnProperty'),
).toBe(false);
expect(BarMock.hasOwnProperty).toBe(
mockGlobals.Object.prototype.hasOwnProperty,
);
});
it('does not mock methods from Object.prototype (in mock context)', () => {
const Bar = vm.runInContext(
`
const Foo = { foo() {} };
const Bar = Object.assign(Object.create(Foo), { bar() {} });
Bar;
`,
mockContext,
);
const BarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(Bar),
);
expect(BarMock).toBeInstanceOf(mockGlobals.Object);
expect(
Object.prototype.hasOwnProperty.call(BarMock, 'hasOwnProperty'),
).toBe(false);
expect(BarMock.hasOwnProperty).toBe(
mockGlobals.Object.prototype.hasOwnProperty,
);
});
it('does not mock methods from Function.prototype', () => {
class Foo {}
class Bar extends Foo {}
const BarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(Bar),
);
expect(BarMock).toBeInstanceOf(mockGlobals.Function);
expect(Object.prototype.hasOwnProperty.call(BarMock, 'bind')).toBe(false);
expect(BarMock.bind).toBe(mockGlobals.Function.prototype.bind);
});
it('does not mock methods from Function.prototype (in mock context)', () => {
const Bar = vm.runInContext(
`
class Foo {}
class Bar extends Foo {}
Bar;
`,
mockContext,
);
const BarMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(Bar),
);
expect(BarMock).toBeInstanceOf(mockGlobals.Function);
expect(Object.prototype.hasOwnProperty.call(BarMock, 'bind')).toBe(false);
expect(BarMock.bind).toBe(mockGlobals.Function.prototype.bind);
});
it('does not mock methods from RegExp.prototype', () => {
const bar = /bar/;
const barMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(bar),
);
expect(barMock).toBeInstanceOf(mockGlobals.RegExp);
expect(Object.prototype.hasOwnProperty.call(barMock, 'test')).toBe(false);
expect(barMock.test).toBe(mockGlobals.RegExp.prototype.test);
});
it('does not mock methods from RegExp.prototype (in mock context)', () => {
const bar = vm.runInContext(
`
const bar = /bar/;
bar;
`,
mockContext,
);
const barMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(bar),
);
expect(barMock).toBeInstanceOf(mockGlobals.RegExp);
expect(Object.prototype.hasOwnProperty.call(barMock, 'test')).toBe(false);
expect(barMock.test).toBe(mockGlobals.RegExp.prototype.test);
});
it('mocks methods that are bound multiple times', () => {
const func = function func() {};
const multipleBoundFunc = func.bind(null).bind(null);
const multipleBoundFuncMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(multipleBoundFunc),
);
expect(typeof multipleBoundFuncMock).toBe('function');
});
it('mocks methods that are bound after mocking', () => {
const fooMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(() => {}),
);
const barMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(fooMock.bind(null)),
);
expect(barMock).not.toThrow();
});
it('mocks regexp instances', () => {
expect(() =>
moduleMocker.generateFromMetadata(moduleMocker.getMetadata(/a/)),
).not.toThrow();
});
it('mocks functions with numeric names', () => {
const obj = {
1: () => {},
};
const objMock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata(obj),
);
expect(typeof objMock[1]).toBe('function');
});
describe('mocked functions', () => {
it('tracks calls to mocks', () => {
const fn = moduleMocker.fn();
expect(fn.mock.calls).toEqual([]);
fn(1, 2, 3);
expect(fn.mock.calls).toEqual([[1, 2, 3]]);
fn('a', 'b', 'c');
expect(fn.mock.calls).toEqual([
[1, 2, 3],
['a', 'b', 'c'],
]);
});
it('tracks instances made by mocks', () => {
const fn = moduleMocker.fn();
expect(fn.mock.instances).toEqual([]);
const instance1 = new fn();
expect(fn.mock.instances[0]).toBe(instance1);
const instance2 = new fn();
expect(fn.mock.instances[1]).toBe(instance2);
});
it('supports clearing mock calls', () => {
const fn = moduleMocker.fn();
expect(fn.mock.calls).toEqual([]);
fn(1, 2, 3);
expect(fn.mock.calls).toEqual([[1, 2, 3]]);
fn.mockReturnValue('abcd');
fn.mockClear();
expect(fn.mock.calls).toEqual([]);
fn('a', 'b', 'c');
expect(fn.mock.calls).toEqual([['a', 'b', 'c']]);
expect(fn()).toEqual('abcd');
});
it('supports clearing mocks', () => {
const fn = moduleMocker.fn();
expect(fn.mock.calls).toEqual([]);
fn(1, 2, 3);
expect(fn.mock.calls).toEqual([[1, 2, 3]]);
fn.mockClear();
expect(fn.mock.calls).toEqual([]);
fn('a', 'b', 'c');
expect(fn.mock.calls).toEqual([['a', 'b', 'c']]);
});
it('supports clearing all mocks', () => {
const fn1 = moduleMocker.fn();
fn1.mockImplementation(() => 'abcd');
fn1(1, 2, 3);
expect(fn1.mock.calls).toEqual([[1, 2, 3]]);
const fn2 = moduleMocker.fn();
fn2.mockReturnValue('abcde');
fn2('a', 'b', 'c', 'd');
expect(fn2.mock.calls).toEqual([['a', 'b', 'c', 'd']]);
moduleMocker.clearAllMocks();
expect(fn1.mock.calls).toEqual([]);
expect(fn2.mock.calls).toEqual([]);
expect(fn1()).toEqual('abcd');
expect(fn2()).toEqual('abcde');
});
it('supports resetting mock return values', () => {
const fn = moduleMocker.fn();
fn.mockReturnValue('abcd');
const before = fn();
expect(before).toEqual('abcd');
fn.mockReset();
const after = fn();
expect(after).not.toEqual('abcd');
});
it('supports resetting single use mock return values', () => {
const fn = moduleMocker.fn();
fn.mockReturnValueOnce('abcd');
fn.mockReset();
const after = fn();
expect(after).not.toEqual('abcd');
});
it('supports resetting mock implementations', () => {
const fn = moduleMocker.fn();
fn.mockImplementation(() => 'abcd');
const before = fn();
expect(before).toEqual('abcd');
fn.mockReset();
const after = fn();
expect(after).not.toEqual('abcd');
});
it('supports resetting single use mock implementations', () => {
const fn = moduleMocker.fn();
fn.mockImplementationOnce(() => 'abcd');
fn.mockReset();
const after = fn();
expect(after).not.toEqual('abcd');
});
it('supports resetting all mocks', () => {
const fn1 = moduleMocker.fn();
fn1.mockImplementation(() => 'abcd');
fn1(1, 2, 3);
expect(fn1.mock.calls).toEqual([[1, 2, 3]]);
const fn2 = moduleMocker.fn();
fn2.mockReturnValue('abcd');
fn2('a', 'b', 'c');
expect(fn2.mock.calls).toEqual([['a', 'b', 'c']]);
moduleMocker.resetAllMocks();
expect(fn1.mock.calls).toEqual([]);
expect(fn2.mock.calls).toEqual([]);
expect(fn1()).not.toEqual('abcd');
expect(fn2()).not.toEqual('abcd');
});
it('maintains function arity', () => {
const mockFunctionArity1 = moduleMocker.fn(x => x);
const mockFunctionArity2 = moduleMocker.fn((x, y) => y);
expect(mockFunctionArity1.length).toBe(1);
expect(mockFunctionArity2.length).toBe(2);
});
});
it('mocks the method in the passed object itself', () => {
const parent = {func: () => 'abcd'};
const child = Object.create(parent);
moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');
expect(child.hasOwnProperty('func')).toBe(true);
expect(child.func()).toEqual('efgh');
expect(parent.func()).toEqual('abcd');
});
it('should delete previously inexistent methods when restoring', () => {
const parent = {func: () => 'abcd'};
const child = Object.create(parent);
moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');
moduleMocker.restoreAllMocks();
expect(child.func()).toEqual('abcd');
moduleMocker.spyOn(parent, 'func').mockReturnValue('jklm');
expect(child.hasOwnProperty('func')).toBe(false);
expect(child.func()).toEqual('jklm');
});
it('supports mock value returning undefined', () => {
const obj = {
func: () => 'some text',
};
moduleMocker.spyOn(obj, 'func').mockReturnValue(undefined);
expect(obj.func()).not.toEqual('some text');
});
it('supports mock value once returning undefined', () => {
const obj = {
func: () => 'some text',
};
moduleMocker.spyOn(obj, 'func').mockReturnValueOnce(undefined);
expect(obj.func()).not.toEqual('some text');
});
it('mockReturnValueOnce mocks value just once', () => {
const fake = jest.fn(a => a + 2);
fake.mockReturnValueOnce(42);
expect(fake(2)).toEqual(42);
expect(fake(2)).toEqual(4);
});
it('supports mocking resolvable async functions', () => {
const fn = moduleMocker.fn();
fn.mockResolvedValue('abcd');
const promise = fn();
expect(promise).toBeInstanceOf(Promise);
return expect(promise).resolves.toBe('abcd');
});
it('supports mocking resolvable async functions only once', () => {
const fn = moduleMocker.fn();
fn.mockResolvedValue('abcd');
fn.mockResolvedValueOnce('abcde');
return Promise.all([
expect(fn()).resolves.toBe('abcde'),
expect(fn()).resolves.toBe('abcd'),
]);
});
it('supports mocking rejectable async functions', () => {
const err = new Error('rejected');
const fn = moduleMocker.fn();
fn.mockRejectedValue(err);
const promise = fn();
expect(promise).toBeInstanceOf(Promise);
return expect(promise).rejects.toBe(err);
});
it('supports mocking rejectable async functions only once', () => {
const defaultErr = new Error('default rejected');
const err = new Error('rejected');
const fn = moduleMocker.fn();
fn.mockRejectedValue(defaultErr);
fn.mockRejectedValueOnce(err);
return Promise.all([
expect(fn()).rejects.toBe(err),
expect(fn()).rejects.toBe(defaultErr),
]);
});
describe('return values', () => {
it('tracks return values', () => {
const fn = moduleMocker.fn(x => x * 2);
expect(fn.mock.results).toEqual([]);
fn(1);
fn(2);
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 2,
},
{
type: 'return',
value: 4,
},
]);
});
it('tracks mocked return values', () => {
const fn = moduleMocker.fn(x => x * 2);
fn.mockReturnValueOnce('MOCKED!');
fn(1);
fn(2);
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 'MOCKED!',
},
{
type: 'return',
value: 4,
},
]);
});
it('supports resetting return values', () => {
const fn = moduleMocker.fn(x => x * 2);
expect(fn.mock.results).toEqual([]);
fn(1);
fn(2);
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 2,
},
{
type: 'return',
value: 4,
},
]);
fn.mockReset();
expect(fn.mock.results).toEqual([]);
});
});
it('tracks thrown errors without interfering with other tracking', () => {
const error = new Error('ODD!');
const fn = moduleMocker.fn((x, y) => {
// multiply params
const result = x * y;
if (result % 2 === 1) {
// throw error if result is odd
throw error;
} else {
return result;
}
});
expect(fn(2, 4)).toBe(8);
// Mock still throws the error even though it was internally
// caught and recorded
expect(() => {
fn(3, 5);
}).toThrow('ODD!');
expect(fn(6, 3)).toBe(18);
// All call args tracked
expect(fn.mock.calls).toEqual([
[2, 4],
[3, 5],
[6, 3],
]);
// Results are tracked
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 8,
},
{
type: 'throw',
value: error,
},
{
type: 'return',
value: 18,
},
]);
});
it(`a call that throws undefined is tracked properly`, () => {
const fn = moduleMocker.fn(() => {
// eslint-disable-next-line no-throw-literal
throw undefined;
});
try {
fn(2, 4);
} catch {
// ignore error
}
// All call args tracked
expect(fn.mock.calls).toEqual([[2, 4]]);
// Results are tracked
expect(fn.mock.results).toEqual([
{
type: 'throw',
value: undefined,
},
]);
});
it('results of recursive calls are tracked properly', () => {
// sums up all integers from 0 -> value, using recursion
const fn = moduleMocker.fn(value => {
if (value === 0) {
return 0;
} else {
return value + fn(value - 1);
}
});
fn(4);
// All call args tracked
expect(fn.mock.calls).toEqual([[4], [3], [2], [1], [0]]);
// Results are tracked
// (in correct order of calls, rather than order of returns)
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 10,
},
{
type: 'return',
value: 6,
},
{
type: 'return',
value: 3,
},
{
type: 'return',
value: 1,
},
{
type: 'return',
value: 0,
},
]);
});
it('test results of recursive calls from within the recursive call', () => {
// sums up all integers from 0 -> value, using recursion
const fn = moduleMocker.fn(value => {
if (value === 0) {
return 0;
} else {
const recursiveResult = fn(value - 1);
if (value === 3) {
// All recursive calls have been made at this point.
expect(fn.mock.calls).toEqual([[4], [3], [2], [1], [0]]);
// But only the last 3 calls have returned at this point.
expect(fn.mock.results).toEqual([
{
type: 'incomplete',
value: undefined,
},
{
type: 'incomplete',
value: undefined,
},
{
type: 'return',
value: 3,
},
{
type: 'return',
value: 1,
},
{
type: 'return',
value: 0,
},
]);
}
return value + recursiveResult;
}
});
fn(4);
});
it('call mockClear inside recursive mock', () => {
// sums up all integers from 0 -> value, using recursion
const fn = moduleMocker.fn(value => {
if (value === 3) {
fn.mockClear();
}
if (value === 0) {
return 0;
} else {
return value + fn(value - 1);
}
});
fn(3);
// All call args (after the call that cleared the mock) are tracked
expect(fn.mock.calls).toEqual([[2], [1], [0]]);
// Results (after the call that cleared the mock) are tracked
expect(fn.mock.results).toEqual([
{
type: 'return',
value: 3,
},
{
type: 'return',
value: 1,
},
{
type: 'return',
value: 0,
},
]);
});
describe('invocationCallOrder', () => {
it('tracks invocationCallOrder made by mocks', () => {
const fn1 = moduleMocker.fn();
expect(fn1.mock.invocationCallOrder).toEqual([]);
fn1(1, 2, 3);
expect(fn1.mock.invocationCallOrder[0]).toBe(1);
fn1('a', 'b', 'c');
expect(fn1.mock.invocationCallOrder[1]).toBe(2);
fn1(1, 2, 3);
expect(fn1.mock.invocationCallOrder[2]).toBe(3);
const fn2 = moduleMocker.fn();
expect(fn2.mock.invocationCallOrder).toEqual([]);
fn2('d', 'e', 'f');
expect(fn2.mock.invocationCallOrder[0]).toBe(4);
fn2(4, 5, 6);
expect(fn2.mock.invocationCallOrder[1]).toBe(5);
});
it('supports clearing mock invocationCallOrder', () => {
const fn = moduleMocker.fn();
expect(fn.mock.invocationCallOrder).toEqual([]);
fn(1, 2, 3);
expect(fn.mock.invocationCallOrder).toEqual([1]);
fn.mockReturnValue('abcd');
fn.mockClear();
expect(fn.mock.invocationCallOrder).toEqual([]);
fn('a', 'b', 'c');
expect(fn.mock.invocationCallOrder).toEqual([2]);
expect(fn()).toEqual('abcd');
});
it('supports clearing all mocks invocationCallOrder', () => {
const fn1 = moduleMocker.fn();
fn1.mockImplementation(() => 'abcd');
fn1(1, 2, 3);
expect(fn1.mock.invocationCallOrder).toEqual([1]);
const fn2 = moduleMocker.fn();
fn2.mockReturnValue('abcde');
fn2('a', 'b', 'c', 'd');
expect(fn2.mock.invocationCallOrder).toEqual([2]);
moduleMocker.clearAllMocks();
expect(fn1.mock.invocationCallOrder).toEqual([]);
expect(fn2.mock.invocationCallOrder).toEqual([]);
expect(fn1()).toEqual('abcd');
expect(fn2()).toEqual('abcde');
});
it('handles a property called `prototype`', () => {
const mock = moduleMocker.generateFromMetadata(
moduleMocker.getMetadata({prototype: 1}),
);
expect(mock.prototype).toBe(1);
});
});
});
describe('getMockImplementation', () => {
it('should mock calls to a mock function', () => {
const mockFn = moduleMocker.fn();
mockFn.mockImplementation(() => 'Foo');
expect(typeof mockFn.getMockImplementation()).toBe('function');
expect(mockFn.getMockImplementation()()).toBe('Foo');
});
});
describe('mockImplementationOnce', () => {
it('should mock constructor', () => {
const mock1 = jest.fn();
const mock2 = jest.fn();
const Module = jest.fn(() => ({someFn: mock1}));
const testFn = function () {
const m = new Module();
m.someFn();
};
Module.mockImplementationOnce(() => ({someFn: mock2}));
testFn();
expect(mock2).toHaveBeenCalled();
expect(mock1).not.toHaveBeenCalled();
testFn();
expect(mock1).toHaveBeenCalled();
});
it('should mock single call to a mock function', () => {
const mockFn = moduleMocker.fn();
mockFn
.mockImplementationOnce(() => 'Foo')
.mockImplementationOnce(() => 'Bar');
expect(mockFn()).toBe('Foo');
expect(mockFn()).toBe('Bar');
expect(mockFn()).toBeUndefined();
});
it('should fallback to default mock function when no specific mock is available', () => {
const mockFn = moduleMocker.fn();
mockFn
.mockImplementationOnce(() => 'Foo')
.mockImplementationOnce(() => 'Bar')
.mockImplementation(() => 'Default');
expect(mockFn()).toBe('Foo');
expect(mockFn()).toBe('Bar');
expect(mockFn()).toBe('Default');
expect(mockFn()).toBe('Default');
});
});
test('mockReturnValue does not override mockImplementationOnce', () => {
const mockFn = jest
.fn()
.mockReturnValue(1)
.mockImplementationOnce(() => 2);
expect(mockFn()).toBe(2);
expect(mockFn()).toBe(1);
});
test('mockImplementation resets the mock', () => {
const fn = jest.fn();
expect(fn()).toBeUndefined();
fn.mockReturnValue('returnValue');
fn.mockImplementation(() => 'foo');
expect(fn()).toBe('foo');
});
it('should recognize a mocked function', () => {
const mockFn = moduleMocker.fn();
expect(moduleMocker.isMockFunction(() => {})).toBe(false);
expect(moduleMocker.isMockFunction(mockFn)).toBe(true);
});
test('default mockName is jest.fn()', () => {
const fn = jest.fn();
expect(fn.getMockName()).toBe('jest.fn()');
});
test('mockName sets the mock name', () => {
const fn = jest.fn();
fn.mockName('myMockFn');
expect(fn.getMockName()).toBe('myMockFn');
});
test('mockName gets reset by mockReset', () => {
const fn = jest.fn();
expect(fn.getMockName()).toBe('jest.fn()');
fn.mockName('myMockFn');
expect(fn.getMockName()).toBe('myMockFn');
fn.mockReset();
expect(fn.getMockName()).toBe('jest.fn()');
});
test('mockName gets reset by mockRestore', () => {
const fn = jest.fn();
expect(fn.getMockName()).toBe('jest.fn()');
fn.mockName('myMockFn');
expect(fn.getMockName()).toBe('myMockFn');
fn.mockRestore();
expect(fn.getMockName()).toBe('jest.fn()');
});
test('mockName is not reset by mockClear', () => {
const fn = jest.fn(() => false);
fn.mockName('myMockFn');
expect(fn.getMockName()).toBe('myMockFn');
fn.mockClear();
expect(fn.getMockName()).toBe('myMockFn');
});
describe('spyOn', () => {
it('should work', () => {
let isOriginalCalled = false;
let originalCallThis;
let originalCallArguments;
const obj = {
method() {
isOriginalCalled = true;
originalCallThis = this;
originalCallArguments = arguments;
},
};
const spy = moduleMocker.spyOn(obj, 'method');
const thisArg = {this: true};
const firstArg = {first: true};
const secondArg = {second: true};
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).toHaveBeenCalled();
isOriginalCalled = false;
originalCallThis = null;
originalCallArguments = null;
spy.mockRestore();
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});
it('should throw on invalid input', () => {
expect(() => {
moduleMocker.spyOn(null, 'method');
}).toThrow();
expect(() => {
moduleMocker.spyOn({}, 'method');
}).toThrow();
expect(() => {
moduleMocker.spyOn({method: 10}, 'method');
}).toThrow();
});
it('supports restoring all spies', () => {
let methodOneCalls = 0;
let methodTwoCalls = 0;
const obj = {
methodOne() {
methodOneCalls++;
},
methodTwo() {
methodTwoCalls++;
},
};
const spy1 = moduleMocker.spyOn(obj, 'methodOne');
const spy2 = moduleMocker.spyOn(obj, 'methodTwo');
// First, we call with the spies: both spies and both original functions
// should be called.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(1);
expect(methodTwoCalls).toBe(1);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
moduleMocker.restoreAllMocks();
// Then, after resetting all mocks, we call methods again. Only the real
// methods should bump their count, not the spies.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(2);
expect(methodTwoCalls).toBe(2);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
});
it('should work with getters', () => {
let isOriginalCalled = false;
let originalCallThis;
let originalCallArguments;
const obj = {
get method() {
return function () {
isOriginalCalled = true;
originalCallThis = this;
originalCallArguments = arguments;
};
},
};
const spy = moduleMocker.spyOn(obj, 'method');
const thisArg = {this: true};
const firstArg = {first: true};
const secondArg = {second: true};
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).toHaveBeenCalled();
isOriginalCalled = false;
originalCallThis = null;
originalCallArguments = null;
spy.mockRestore();
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});
it('should work with object of null prototype', () => {
const Foo = Object.assign(Object.create(null), {
foo() {},
});
const spy = moduleMocker.spyOn(Foo, 'foo');
Foo.foo();
expect(spy).toHaveBeenCalled();
});
});
describe('spyOnProperty', () => {
it('should work - getter', () => {
let isOriginalCalled = false;
let originalCallThis;
let originalCallArguments;
const obj = {
get method() {
return function () {
isOriginalCalled = true;
originalCallThis = this;
originalCallArguments = arguments;
};
},
};
const spy = moduleMocker.spyOn(obj, 'method', 'get');
const thisArg = {this: true};
const firstArg = {first: true};
const secondArg = {second: true};
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).toHaveBeenCalled();
isOriginalCalled = false;
originalCallThis = null;
originalCallArguments = null;
spy.mockRestore();
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});
it('should work - setter', () => {
const obj = {
_property: false,
set property(value) {
this._property = value;
},
get property() {
return this._property;
},
};
const spy = moduleMocker.spyOn(obj, 'property', 'set');
obj.property = true;
expect(spy).toHaveBeenCalled();
expect(obj.property).toBe(true);
obj.property = false;
spy.mockRestore();
obj.property = true;
expect(spy).not.toHaveBeenCalled();
expect(obj.property).toBe(true);
});
it('should throw on invalid input', () => {
expect(() => {
moduleMocker.spyOn(null, 'method');
}).toThrow();
expect(() => {
moduleMocker.spyOn({}, 'method');
}).toThrow();
expect(() => {
moduleMocker.spyOn({method: 10}, 'method');
}).toThrow();
});
it('supports restoring all spies', () => {
let methodOneCalls = 0;
let methodTwoCalls = 0;
const obj = {
get methodOne() {
return function () {
methodOneCalls++;
};
},
get methodTwo() {
return function () {
methodTwoCalls++;
};
},
};
const spy1 = moduleMocker.spyOn(obj, 'methodOne', 'get');
const spy2 = moduleMocker.spyOn(obj, 'methodTwo', 'get');
// First, we call with the spies: both spies and both original functions
// should be called.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(1);
expect(methodTwoCalls).toBe(1);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
moduleMocker.restoreAllMocks();
// Then, after resetting all mocks, we call methods again. Only the real
// methods should bump their count, not the spies.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(2);
expect(methodTwoCalls).toBe(2);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
});
it('should work with getters on the prototype chain', () => {
let isOriginalCalled = false;
let originalCallThis;
let originalCallArguments;
const prototype = {
get method() {
return function () {
isOriginalCalled = true;
originalCallThis = this;
originalCallArguments = arguments;
};
},
};
const obj = Object.create(prototype, {});
const spy = moduleMocker.spyOn(obj, 'method', 'get');
const thisArg = {this: true};
const firstArg = {first: true};
const secondArg = {second: true};
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).toHaveBeenCalled();
isOriginalCalled = false;
originalCallThis = null;
originalCallArguments = null;
spy.mockRestore();
obj.method.call(thisArg, firstArg, secondArg);
expect(isOriginalCalled).toBe(true);
expect(originalCallThis).toBe(thisArg);
expect(originalCallArguments.length).toBe(2);
expect(originalCallArguments[0]).toBe(firstArg);
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});
test('should work with setters on the prototype chain', () => {
const prototype = {
_property: false,
set property(value) {
this._property = value;
},
get property() {
return this._property;
},
};
const obj = Object.create(prototype, {});
const spy = moduleMocker.spyOn(obj, 'property', 'set');
obj.property = true;
expect(spy).toHaveBeenCalled();
expect(obj.property).toBe(true);
obj.property = false;
spy.mockRestore();
obj.property = true;
expect(spy).not.toHaveBeenCalled();
expect(obj.property).toBe(true);
});
it('supports restoring all spies on the prototype chain', () => {
let methodOneCalls = 0;
let methodTwoCalls = 0;
const prototype = {
get methodOne() {
return function () {
methodOneCalls++;
};
},
get methodTwo() {
return function () {
methodTwoCalls++;
};
},
};
const obj = Object.create(prototype, {});
const spy1 = moduleMocker.spyOn(obj, 'methodOne', 'get');
const spy2 = moduleMocker.spyOn(obj, 'methodTwo', 'get');
// First, we call with the spies: both spies and both original functions
// should be called.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(1);
expect(methodTwoCalls).toBe(1);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
moduleMocker.restoreAllMocks();
// Then, after resetting all mocks, we call methods again. Only the real
// methods should bump their count, not the spies.
obj.methodOne();
obj.methodTwo();
expect(methodOneCalls).toBe(2);
expect(methodTwoCalls).toBe(2);
expect(spy1.mock.calls.length).toBe(1);
expect(spy2.mock.calls.length).toBe(1);
});
});
});
describe('mocked', () => {
it('should return unmodified input', () => {
const subject = {};
expect(mocked(subject)).toBe(subject);
});
});
test('`fn` and `spyOn` do not throw', () => {
expect(() => {
fn();
spyOn({apple: () => {}}, 'apple');
}).not.toThrow();
}); | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace licensing_v1 {
export interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: 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;
/**
* 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;
}
/**
* Enterprise License Manager API
*
* The Google Enterprise License Manager API's allows you to license apps for all the users of a domain managed by you.
*
* @example
* ```js
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
* ```
*/
export class Licensing {
context: APIRequestContext;
licenseAssignments: Resource$Licenseassignments;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.licenseAssignments = new Resource$Licenseassignments(this.context);
}
}
/**
* A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} The JSON representation for `Empty` is empty JSON object `{\}`.
*/
export interface Schema$Empty {}
/**
* Representation of a license assignment.
*/
export interface Schema$LicenseAssignment {
/**
* ETag of the resource.
*/
etags?: string | null;
/**
* Identifies the resource as a LicenseAssignment, which is `licensing#licenseAssignment`.
*/
kind?: string | null;
/**
* A product's unique identifier. For more information about products in this version of the API, see Product and SKU IDs.
*/
productId?: string | null;
/**
* Display Name of the product.
*/
productName?: string | null;
/**
* Link to this page.
*/
selfLink?: string | null;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string | null;
/**
* Display Name of the sku of the product.
*/
skuName?: string | null;
/**
* The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
*/
userId?: string | null;
}
/**
* Representation of a license assignment.
*/
export interface Schema$LicenseAssignmentInsert {
/**
* Email id of the user
*/
userId?: string | null;
}
export interface Schema$LicenseAssignmentList {
/**
* ETag of the resource.
*/
etag?: string | null;
/**
* The LicenseAssignments in this page of results.
*/
items?: Schema$LicenseAssignment[];
/**
* Identifies the resource as a collection of LicenseAssignments.
*/
kind?: string | null;
/**
* The token that you must submit in a subsequent request to retrieve additional license results matching your query parameters. The `maxResults` query string is related to the `nextPageToken` since `maxResults` determines how many entries are returned on each next page.
*/
nextPageToken?: string | null;
}
export class Resource$Licenseassignments {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Revoke a license.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.delete({
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
* // The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
* userId: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {}
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
delete(
params: Params$Resource$Licenseassignments$Delete,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
delete(
params?: Params$Resource$Licenseassignments$Delete,
options?: MethodOptions
): GaxiosPromise<Schema$Empty>;
delete(
params: Params$Resource$Licenseassignments$Delete,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
delete(
params: Params$Resource$Licenseassignments$Delete,
options: MethodOptions | BodyResponseCallback<Schema$Empty>,
callback: BodyResponseCallback<Schema$Empty>
): void;
delete(
params: Params$Resource$Licenseassignments$Delete,
callback: BodyResponseCallback<Schema$Empty>
): void;
delete(callback: BodyResponseCallback<Schema$Empty>): void;
delete(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Delete
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$Empty>
| BodyResponseCallback<Readable>
): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Delete;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Delete;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/user/{userId}'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE',
},
options
),
params,
requiredParams: ['productId', 'skuId', 'userId'],
pathParams: ['productId', 'skuId', 'userId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$Empty>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$Empty>(parameters);
}
}
/**
* Get a specific user's license by product SKU.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.get({
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
* // The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
* userId: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
get(
params: Params$Resource$Licenseassignments$Get,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
get(
params?: Params$Resource$Licenseassignments$Get,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignment>;
get(
params: Params$Resource$Licenseassignments$Get,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
get(
params: Params$Resource$Licenseassignments$Get,
options: MethodOptions | BodyResponseCallback<Schema$LicenseAssignment>,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
get(
params: Params$Resource$Licenseassignments$Get,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
get(callback: BodyResponseCallback<Schema$LicenseAssignment>): void;
get(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Get
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignment>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Get;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Get;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/user/{userId}'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['productId', 'skuId', 'userId'],
pathParams: ['productId', 'skuId', 'userId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignment>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignment>(parameters);
}
}
/**
* Assign a license.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.insert({
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "userId": "my_userId"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
insert(
params: Params$Resource$Licenseassignments$Insert,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
insert(
params?: Params$Resource$Licenseassignments$Insert,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignment>;
insert(
params: Params$Resource$Licenseassignments$Insert,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
insert(
params: Params$Resource$Licenseassignments$Insert,
options: MethodOptions | BodyResponseCallback<Schema$LicenseAssignment>,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
insert(
params: Params$Resource$Licenseassignments$Insert,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
insert(callback: BodyResponseCallback<Schema$LicenseAssignment>): void;
insert(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Insert
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignment>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Insert;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Insert;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/user'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'POST',
},
options
),
params,
requiredParams: ['productId', 'skuId'],
pathParams: ['productId', 'skuId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignment>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignment>(parameters);
}
}
/**
* List all users assigned licenses for a specific product SKU.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.listForProduct({
* // Customer's `customerId`. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error.
* customerId: 'placeholder-value',
* // The `maxResults` query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number.
* maxResults: 'placeholder-value',
* // Token to fetch the next page of data. The `maxResults` query string is related to the `pageToken` since `maxResults` determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page.
* pageToken: 'placeholder-value',
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etag": "my_etag",
* // "items": [],
* // "kind": "my_kind",
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
listForProduct(
params: Params$Resource$Licenseassignments$Listforproduct,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
listForProduct(
params?: Params$Resource$Licenseassignments$Listforproduct,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignmentList>;
listForProduct(
params: Params$Resource$Licenseassignments$Listforproduct,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
listForProduct(
params: Params$Resource$Licenseassignments$Listforproduct,
options:
| MethodOptions
| BodyResponseCallback<Schema$LicenseAssignmentList>,
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProduct(
params: Params$Resource$Licenseassignments$Listforproduct,
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProduct(
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProduct(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Listforproduct
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignmentList>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Listforproduct;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Listforproduct;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl + '/apps/licensing/v1/product/{productId}/users'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['productId', 'customerId'],
pathParams: ['productId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignmentList>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignmentList>(parameters);
}
}
/**
* List all users assigned licenses for a specific product SKU.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.listForProductAndSku({
* // Customer's `customerId`. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error.
* customerId: 'placeholder-value',
* // The `maxResults` query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number.
* maxResults: 'placeholder-value',
* // Token to fetch the next page of data. The `maxResults` query string is related to the `pageToken` since `maxResults` determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page.
* pageToken: 'placeholder-value',
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etag": "my_etag",
* // "items": [],
* // "kind": "my_kind",
* // "nextPageToken": "my_nextPageToken"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
listForProductAndSku(
params: Params$Resource$Licenseassignments$Listforproductandsku,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
listForProductAndSku(
params?: Params$Resource$Licenseassignments$Listforproductandsku,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignmentList>;
listForProductAndSku(
params: Params$Resource$Licenseassignments$Listforproductandsku,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
listForProductAndSku(
params: Params$Resource$Licenseassignments$Listforproductandsku,
options:
| MethodOptions
| BodyResponseCallback<Schema$LicenseAssignmentList>,
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProductAndSku(
params: Params$Resource$Licenseassignments$Listforproductandsku,
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProductAndSku(
callback: BodyResponseCallback<Schema$LicenseAssignmentList>
): void;
listForProductAndSku(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Listforproductandsku
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignmentList>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignmentList>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Listforproductandsku;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Listforproductandsku;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/users'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['productId', 'skuId', 'customerId'],
pathParams: ['productId', 'skuId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignmentList>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignmentList>(parameters);
}
}
/**
* Reassign a user's product SKU with a different SKU in the same product. This method supports patch semantics.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.patch({
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
* // The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
* userId: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
patch(
params: Params$Resource$Licenseassignments$Patch,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
patch(
params?: Params$Resource$Licenseassignments$Patch,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignment>;
patch(
params: Params$Resource$Licenseassignments$Patch,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
patch(
params: Params$Resource$Licenseassignments$Patch,
options: MethodOptions | BodyResponseCallback<Schema$LicenseAssignment>,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
patch(
params: Params$Resource$Licenseassignments$Patch,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
patch(callback: BodyResponseCallback<Schema$LicenseAssignment>): void;
patch(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Patch
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignment>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Patch;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Patch;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/user/{userId}'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'PATCH',
},
options
),
params,
requiredParams: ['productId', 'skuId', 'userId'],
pathParams: ['productId', 'skuId', 'userId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignment>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignment>(parameters);
}
}
/**
* Reassign a user's product SKU with a different SKU in the same product.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/licensing.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const licensing = google.licensing('v1');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/apps.licensing'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await licensing.licenseAssignments.update({
* // A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
* productId: 'placeholder-value',
* // A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
* skuId: 'placeholder-value',
* // The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
* userId: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "etags": "my_etags",
* // "kind": "my_kind",
* // "productId": "my_productId",
* // "productName": "my_productName",
* // "selfLink": "my_selfLink",
* // "skuId": "my_skuId",
* // "skuName": "my_skuName",
* // "userId": "my_userId"
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
update(
params: Params$Resource$Licenseassignments$Update,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
update(
params?: Params$Resource$Licenseassignments$Update,
options?: MethodOptions
): GaxiosPromise<Schema$LicenseAssignment>;
update(
params: Params$Resource$Licenseassignments$Update,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
update(
params: Params$Resource$Licenseassignments$Update,
options: MethodOptions | BodyResponseCallback<Schema$LicenseAssignment>,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
update(
params: Params$Resource$Licenseassignments$Update,
callback: BodyResponseCallback<Schema$LicenseAssignment>
): void;
update(callback: BodyResponseCallback<Schema$LicenseAssignment>): void;
update(
paramsOrCallback?:
| Params$Resource$Licenseassignments$Update
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$LicenseAssignment>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$LicenseAssignment>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Licenseassignments$Update;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Licenseassignments$Update;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl = options.rootUrl || 'https://licensing.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (
rootUrl +
'/apps/licensing/v1/product/{productId}/sku/{skuId}/user/{userId}'
).replace(/([^:]\/)\/+/g, '$1'),
method: 'PUT',
},
options
),
params,
requiredParams: ['productId', 'skuId', 'userId'],
pathParams: ['productId', 'skuId', 'userId'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$LicenseAssignment>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$LicenseAssignment>(parameters);
}
}
}
export interface Params$Resource$Licenseassignments$Delete
extends StandardParameters {
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
/**
* The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
*/
userId?: string;
}
export interface Params$Resource$Licenseassignments$Get
extends StandardParameters {
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
/**
* The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
*/
userId?: string;
}
export interface Params$Resource$Licenseassignments$Insert
extends StandardParameters {
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$LicenseAssignmentInsert;
}
export interface Params$Resource$Licenseassignments$Listforproduct
extends StandardParameters {
/**
* Customer's `customerId`. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error.
*/
customerId?: string;
/**
* The `maxResults` query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number.
*/
maxResults?: number;
/**
* Token to fetch the next page of data. The `maxResults` query string is related to the `pageToken` since `maxResults` determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page.
*/
pageToken?: string;
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
}
export interface Params$Resource$Licenseassignments$Listforproductandsku
extends StandardParameters {
/**
* Customer's `customerId`. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error.
*/
customerId?: string;
/**
* The `maxResults` query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number.
*/
maxResults?: number;
/**
* Token to fetch the next page of data. The `maxResults` query string is related to the `pageToken` since `maxResults` determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page.
*/
pageToken?: string;
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
}
export interface Params$Resource$Licenseassignments$Patch
extends StandardParameters {
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
/**
* The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
*/
userId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$LicenseAssignment;
}
export interface Params$Resource$Licenseassignments$Update
extends StandardParameters {
/**
* A product's unique identifier. For more information about products in this version of the API, see Products and SKUs.
*/
productId?: string;
/**
* A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs.
*/
skuId?: string;
/**
* The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a `userId` is subject to change, do not use a `userId` value as a key for persistent data. This key could break if the current user's email address changes. If the `userId` is suspended, the license status changes.
*/
userId?: string;
/**
* Request body metadata
*/
requestBody?: Schema$LicenseAssignment;
}
} | the_stack |
import type { CellAction } from '../../actions/cell';
import {
CELL_INSERT_ABOVE,
CELL_INSERT_BELOW,
CELL_INSERT_INLINE_LEFT,
CELL_INSERT_INLINE_RIGHT,
CELL_INSERT_LEFT_OF,
CELL_INSERT_RIGHT_OF,
CELL_REMOVE,
CELL_RESIZE,
CELL_UPDATE_DATA,
CELL_UPDATE_IS_DRAFT,
CELL_INSERT_AT_END,
CELL_INSERT_AS_NEW_ROW,
} from '../../actions/cell';
import type { Cell, Row } from '../../types/node';
import { createId } from '../../utils/createId';
import { removeUndefinedProps } from '../../utils/removeUndefinedProps';
import {
flatten,
optimizeCell,
optimizeCells,
optimizeRow,
optimizeRows,
} from './helper/optimize';
import { resizeCells } from './helper/sizing';
const cell = (s: Cell, a: CellAction, depth: number): Cell =>
optimizeCell(
((state: Cell, action): Cell => {
const reduce = (): Cell => {
return removeUndefinedProps({
...state,
rows: rows(state.rows, action, depth + 1),
});
};
switch (action.type) {
case CELL_UPDATE_IS_DRAFT:
if (action.id === state.id) {
const reduced = reduce();
if (action.lang) {
return {
...reduced,
isDraftI18n: {
...(reduced.isDraftI18n ?? {}),
[action.lang]: action.isDraft,
},
};
} else {
return {
...reduced,
isDraft: action.isDraft,
};
}
}
return reduce();
case CELL_UPDATE_DATA:
if (action.id === state.id) {
// If this cell is being updated, set the data
const reduced = reduce();
// copy because we mutate afterwards with delete
const newI18nData = { ...(reduced.dataI18n ?? {}) };
const emptyValue = action.data === null;
if (action.lang && emptyValue) {
delete newI18nData?.[action.lang];
}
return {
...reduced,
dataI18n: {
...(newI18nData ?? {}),
...(!emptyValue
? { [action.lang]: action.data as { [key: string]: unknown } }
: {}),
},
};
}
return reduce();
case CELL_INSERT_ABOVE:
if (action.hoverId === state.id) {
return {
id: action.ids.cell,
rows: rows(
[
{
id: action.ids.others[0],
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
},
{
id: action.ids.others[1],
cells: [{ ...reduce(), id: action.ids.others[2] }],
},
],
{ ...action, hoverId: null },
depth + 1
),
};
}
return reduce();
case CELL_INSERT_BELOW:
if (action.hoverId === state.id) {
return {
id: action.ids.cell,
rows: rows(
[
{
id: action.ids.others[0],
cells: [{ ...reduce(), id: action.ids.others[1] }],
},
{
id: action.ids.others[2],
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
},
],
{ ...action, hoverId: null },
depth + 1
),
};
}
return reduce();
case CELL_INSERT_AS_NEW_ROW: {
if (action.hoverId === state.id) {
return {
...state,
rows: [
...(state.rows ?? []),
{
id: action.ids.others[1],
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
},
],
};
}
return reduce();
}
default:
return reduce();
}
})(s, a)
);
const createEmptyCell = (): Cell => ({
id: createId(),
rows: [
{
id: createId(),
cells: [],
},
],
});
export const cells = (state: Cell[] = [], action, depth = 0): Cell[] => {
let newCells =
depth === 0 && state.length === 0 ? [createEmptyCell()] : state;
switch (action.type) {
case CELL_RESIZE:
// eslint-disable-next-line @typescript-eslint/no-explicit-any
newCells = resizeCells(newCells, action);
break;
case CELL_INSERT_AT_END:
case CELL_INSERT_AS_NEW_ROW:
case CELL_INSERT_BELOW:
case CELL_INSERT_ABOVE:
newCells = newCells.filter((c: Cell) => c.id !== action.item.id); // this removes the cell if it already exists
break;
case CELL_INSERT_LEFT_OF:
newCells = newCells
.filter((c: Cell) => c.id !== action.item.id) // this removes the cell if it already exists
.map((c: Cell) =>
action.hoverId === c.id
? [
{ ...action.item, id: action.ids.item, inline: null },
{ ...c, id: action.ids.others[0] },
]
: [c]
)
.reduce(flatten, []);
break;
case CELL_INSERT_RIGHT_OF:
newCells = newCells
.filter((c: Cell) => c.id !== action.item.id) // this removes the cell if it already exists
.map((c: Cell) =>
action.hoverId === c.id
? [
{ ...c, id: action.ids.others[0] },
{ ...action.item, id: action.ids.item, inline: null },
]
: [c]
)
.reduce(flatten, []);
break;
case CELL_INSERT_INLINE_RIGHT:
case CELL_INSERT_INLINE_LEFT:
newCells = newCells
.filter((c: Cell) => c.id !== action.item.id) // this removes the cell if it already exists
.map((c: Cell) => {
if (action.hoverId === c.id) {
return [
{
id: action.ids.cell,
rows: [
{
id: action.ids.others[0],
cells: [
{
...action.item,
inline:
action.type === CELL_INSERT_INLINE_RIGHT
? 'right'
: 'left',
id: action.ids.item,
size: 0,
},
{
...c,
id: action.ids.others[1],
inline: null,
hasInlineNeighbour: action.ids.item,
size: 0,
},
],
},
],
},
] as Cell[];
}
return [c];
})
.reduce(flatten, []);
break;
case CELL_REMOVE:
newCells = newCells.filter(({ id }: Cell) => !action.ids.includes(id));
break;
}
const reducedCells = newCells.map((c) => cell(c, action, depth));
return optimizeCells(reducedCells);
};
const row = (s: Row, a, depth: number): Row =>
optimizeRow(
((state: Row, action): Row => {
const reduce = () => ({
...state,
cells: cells(state.cells, action, depth + 1),
});
switch (action.type) {
case CELL_INSERT_LEFT_OF:
if (action.hoverId !== state.id) {
return reduce();
}
return {
...state,
cells: cells(
[
{ ...action.item, id: action.ids.item, inline: null },
...state.cells,
],
{ ...action, hoverId: null },
depth + 1
),
};
case CELL_INSERT_RIGHT_OF:
if (action.hoverId !== state.id) {
return reduce();
}
return {
...state,
cells: cells(
[
...state.cells,
{ ...action.item, id: action.ids.item, inline: null },
],
{ ...action, hoverId: null },
depth + 1
),
};
/*case CELL_DRAG_HOVER:
if (action.hoverId === state.id) {
return { ...reduce(), hoverPosition: action.position };
}
return reduce();
*/
default:
return reduce();
}
})(s, a)
);
export const rows = (s: Row[] = [], a, depth = 0): Row[] =>
optimizeRows(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
((state: Row[], action): Row[] => {
const reduce = () => state.map((r) => row(r, action, depth));
switch (action.type) {
case CELL_INSERT_ABOVE:
return state
.map((r: Row) =>
action.hoverId === r.id
? [
{
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
id: action.ids.others[0],
},
{
...r,
id: action.ids.others[1],
},
]
: [r]
)
.reduce(flatten, [])
.map((r) => row(r, action, depth));
case CELL_INSERT_BELOW:
return state
.map((r: Row) =>
action.hoverId === r.id
? [
{
...r,
id: action.ids.others[0],
},
{
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
id: action.ids.others[1],
},
]
: [r]
)
.reduce(flatten, [])
.map((r) => row(r, action, depth));
case CELL_INSERT_AT_END: {
const newRows =
depth !== 0
? state
: [
...state,
{
cells: [
{ ...action.item, id: action.ids.item, inline: null },
],
id: action.ids.others[1],
},
];
return newRows.map((r) => row(r, action, depth));
}
default:
return reduce();
}
})(s, a)
); | the_stack |
import React, { Component, PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Action, Dispatch } from 'redux';
import * as themes from 'redux-devtools-themes';
import { Base16Theme } from 'redux-devtools-themes';
import {
ActionCreators,
LiftedAction,
LiftedState,
} from '@redux-devtools/core';
import {
Button,
Divider,
SegmentedControl,
Slider,
Toolbar,
} from '@redux-devtools/ui';
import reducer from './reducers';
import SliderButton from './SliderButton';
// eslint-disable-next-line @typescript-eslint/unbound-method
const { reset, jumpToAction } = ActionCreators;
interface ExternalProps<S, A extends Action<unknown>> {
// eslint-disable-next-line @typescript-eslint/ban-types
dispatch: Dispatch<LiftedAction<S, A, {}>>;
preserveScrollTop: boolean;
select: (state: S) => unknown;
theme: keyof typeof themes | Base16Theme;
keyboardEnabled: boolean;
hideResetButton?: boolean;
}
interface DefaultProps {
select: (state: unknown) => unknown;
theme: keyof typeof themes;
preserveScrollTop: boolean;
keyboardEnabled: boolean;
}
interface SliderMonitorProps<S, A extends Action<unknown>> // eslint-disable-next-line @typescript-eslint/ban-types
extends LiftedState<S, A, {}> {
// eslint-disable-next-line @typescript-eslint/ban-types
dispatch: Dispatch<LiftedAction<S, A, {}>>;
preserveScrollTop: boolean;
select: (state: S) => unknown;
theme: keyof typeof themes | Base16Theme;
keyboardEnabled: boolean;
hideResetButton?: boolean;
}
interface State {
timer: number | undefined;
replaySpeed: string;
}
class SliderMonitor<S, A extends Action<unknown>> extends (PureComponent ||
Component)<SliderMonitorProps<S, A>, State> {
static update = reducer;
static propTypes = {
dispatch: PropTypes.func,
computedStates: PropTypes.array,
stagedActionIds: PropTypes.array,
actionsById: PropTypes.object,
currentStateIndex: PropTypes.number,
monitorState: PropTypes.shape({
initialScrollTop: PropTypes.number,
}),
preserveScrollTop: PropTypes.bool,
// stagedActions: PropTypes.array,
select: PropTypes.func.isRequired,
hideResetButton: PropTypes.bool,
theme: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
keyboardEnabled: PropTypes.bool,
};
static defaultProps = {
select: (state: unknown) => state,
theme: 'nicinabox',
preserveScrollTop: true,
keyboardEnabled: true,
};
state: State = {
timer: undefined,
replaySpeed: '1x',
};
componentDidMount() {
if (typeof window !== 'undefined') {
window.addEventListener('keydown', this.handleKeyPress);
}
}
componentWillUnmount() {
if (typeof window !== 'undefined') {
window.removeEventListener('keydown', this.handleKeyPress);
}
}
setUpTheme = (): Base16Theme => {
let theme;
if (typeof this.props.theme === 'string') {
if (typeof themes[this.props.theme] !== 'undefined') {
theme = themes[this.props.theme];
} else {
theme = themes.nicinabox;
}
} else {
theme = this.props.theme;
}
return theme;
};
handleReset = () => {
this.pauseReplay();
this.props.dispatch(reset());
};
handleKeyPress = (event: KeyboardEvent) => {
if (!this.props.keyboardEnabled) {
return null;
}
if (event.ctrlKey && event.keyCode === 74) {
// ctrl+j
event.preventDefault();
if (this.state.timer) {
return this.pauseReplay();
}
if (this.state.replaySpeed === 'Live') {
this.startRealtimeReplay();
} else {
this.startReplay();
}
} else if (event.ctrlKey && event.keyCode === 219) {
// ctrl+[
event.preventDefault();
this.stepLeft();
} else if (event.ctrlKey && event.keyCode === 221) {
// ctrl+]
event.preventDefault();
this.stepRight();
}
return null;
};
handleSliderChange = (value: number) => {
if (this.state.timer) {
this.pauseReplay();
}
this.props.dispatch(jumpToAction(this.props.stagedActionIds[value]));
};
startReplay = () => {
const { computedStates, currentStateIndex, dispatch, stagedActionIds } =
this.props;
if (computedStates.length < 2) {
return;
}
const speed = this.state.replaySpeed === '1x' ? 500 : 200;
let stateIndex;
if (currentStateIndex === computedStates.length - 1) {
dispatch(jumpToAction(stagedActionIds[0]));
stateIndex = 0;
} else if (currentStateIndex === computedStates.length - 2) {
dispatch(jumpToAction(stagedActionIds[currentStateIndex + 1]));
return;
} else {
stateIndex = currentStateIndex + 1;
dispatch(jumpToAction(stagedActionIds[currentStateIndex + 1]));
}
let counter = stateIndex;
const timer = window.setInterval(() => {
if (counter + 1 <= computedStates.length - 1) {
dispatch(jumpToAction(stagedActionIds[counter + 1]));
}
counter += 1;
if (counter >= computedStates.length - 1) {
clearInterval(this.state.timer);
this.setState({
timer: undefined,
});
}
}, speed);
this.setState({ timer });
};
startRealtimeReplay = () => {
if (this.props.computedStates.length < 2) {
return;
}
if (this.props.currentStateIndex === this.props.computedStates.length - 1) {
this.props.dispatch(jumpToAction(this.props.stagedActionIds[0]));
this.loop(0);
} else {
this.loop(this.props.currentStateIndex);
}
};
loop = (index: number) => {
let currentTimestamp = Date.now();
let timestampDiff = this.getLatestTimestampDiff(index);
const aLoop = () => {
const replayDiff = Date.now() - currentTimestamp;
if (replayDiff >= timestampDiff) {
this.props.dispatch(
jumpToAction(
this.props.stagedActionIds[this.props.currentStateIndex + 1]
)
);
if (
this.props.currentStateIndex >=
this.props.computedStates.length - 1
) {
this.pauseReplay();
return;
}
timestampDiff = this.getLatestTimestampDiff(
this.props.currentStateIndex
);
currentTimestamp = Date.now();
this.setState({
timer: requestAnimationFrame(aLoop),
});
} else {
this.setState({
timer: requestAnimationFrame(aLoop),
});
}
};
if (index !== this.props.computedStates.length - 1) {
this.setState({
timer: requestAnimationFrame(aLoop),
});
}
};
getLatestTimestampDiff = (index: number) =>
this.getTimestampOfStateIndex(index + 1) -
this.getTimestampOfStateIndex(index);
getTimestampOfStateIndex = (stateIndex: number) => {
const id = this.props.stagedActionIds[stateIndex];
return this.props.actionsById[id].timestamp;
};
pauseReplay = (cb?: () => void) => {
if (this.state.timer) {
cancelAnimationFrame(this.state.timer);
clearInterval(this.state.timer);
this.setState(
{
timer: undefined,
},
() => {
if (typeof cb === 'function') {
cb();
}
}
);
}
};
stepLeft = () => {
this.pauseReplay();
if (this.props.currentStateIndex !== 0) {
this.props.dispatch(
jumpToAction(
this.props.stagedActionIds[this.props.currentStateIndex - 1]
)
);
}
};
stepRight = () => {
this.pauseReplay();
if (this.props.currentStateIndex !== this.props.computedStates.length - 1) {
this.props.dispatch(
jumpToAction(
this.props.stagedActionIds[this.props.currentStateIndex + 1]
)
);
}
};
changeReplaySpeed = (replaySpeed: string) => {
this.setState({ replaySpeed });
if (this.state.timer) {
this.pauseReplay(() => {
if (replaySpeed === 'Live') {
this.startRealtimeReplay();
} else {
this.startReplay();
}
});
}
};
render() {
const {
currentStateIndex,
computedStates,
actionsById,
stagedActionIds,
hideResetButton,
} = this.props;
const { replaySpeed } = this.state;
const theme = this.setUpTheme();
const max = computedStates.length - 1;
const actionId = stagedActionIds[currentStateIndex];
let actionType = actionsById[actionId].action.type;
if (actionType === undefined) actionType = '<UNDEFINED>';
else if (actionType === null) actionType = '<NULL>';
else actionType = (actionType as string).toString() || '<EMPTY>';
const onPlayClick =
replaySpeed === 'Live' ? this.startRealtimeReplay : this.startReplay;
const playPause = this.state.timer ? (
<SliderButton theme={theme} type="pause" onClick={this.pauseReplay} />
) : (
<SliderButton
theme={theme}
type="play"
disabled={max <= 0}
onClick={onPlayClick}
/>
);
return (
<Toolbar noBorder compact fullHeight theme={theme}>
{playPause}
<Slider
label={actionType as string}
sublabel={`(${actionId})`}
min={0}
max={max}
value={currentStateIndex}
onChange={this.handleSliderChange}
theme={theme}
/>
<SliderButton
theme={theme}
type="stepLeft"
disabled={currentStateIndex <= 0}
onClick={this.stepLeft}
/>
<SliderButton
theme={theme}
type="stepRight"
disabled={currentStateIndex === max}
onClick={this.stepRight}
/>
<Divider theme={theme} />
<SegmentedControl
theme={theme}
values={['Live', '1x', '2x']}
selected={replaySpeed}
onClick={this.changeReplaySpeed}
/>
{!hideResetButton && [
<Divider key="divider" theme={theme} />,
<Button key="reset" theme={theme} onClick={this.handleReset}>
Reset
</Button>,
]}
</Toolbar>
);
}
}
export default SliderMonitor as unknown as React.ComponentType<
ExternalProps<unknown, Action<unknown>>
> & {
update(
monitorProps: ExternalProps<unknown, Action<unknown>>,
// eslint-disable-next-line @typescript-eslint/ban-types
state: {} | undefined,
action: Action<unknown>
// eslint-disable-next-line @typescript-eslint/ban-types
): {};
defaultProps: DefaultProps;
}; | the_stack |
import {
Site,
SiteSchema,
Dictionary,
Options,
DataResult,
EDataResultType,
SearchEntry,
EModule,
ERequestResultType,
SearchEntryConfigArea,
SearchEntryConfig,
ISearchPayload,
SiteCategories,
SiteCategory,
ERequestMethod,
BASE_TAG_COLORS
} from "@/interface/common";
import { APP } from "@/service/api";
import { SiteService } from "./site";
import PTPlugin from "./service";
import extend from "extend";
import { InfoParser } from "./infoParser";
import { PPF } from "@/service/public";
import { PageParser } from "./pageParser";
export type SearchConfig = {
site?: Site;
entry?: SearchEntry[];
rootPath?: string;
torrentTagSelectors?: any[];
};
/**
* 搜索结果解析状态
*/
export enum ESearchResultParseStatus {
success = "success",
needLogin = "needLogin",
noTorrents = "noTorrents",
torrentTableIsEmpty = "torrentTableIsEmpty",
parseError = "parseError"
}
Object.assign(window, {
ESearchResultParseStatus
});
/**
* 搜索类
*/
export class Searcher {
// 搜索入口定义缓存
private searchConfigs: any = {};
// 解析文件内容缓存
private parseScriptCache: any = {};
public options: Options = {
sites: [],
clients: []
};
private searchRequestQueue: Dictionary<JQueryXHR> = {};
constructor(public service: PTPlugin) { }
/**
* 搜索种子
* @param site 需要搜索的站点
* @param key 需要搜索的关键字
* @param payload 附加数据
*/
public searchTorrent(
site: Site,
key: string = "",
payload?: ISearchPayload
): Promise<any> {
this.service.debug("searchTorrent: start", key, payload);
return new Promise<any>((resolve?: any, reject?: any) => {
let result: DataResult = {
success: false
};
let siteService: SiteService = new SiteService(
PPF.clone(site),
PPF.clone(this.options)
);
let searchConfig: SearchConfig = {};
let schema = this.getSiteSchema(site);
let host = site.host as string;
// 当前站点默认搜索页
let siteSearchPage = "";
// 当前站点默认搜索配置信息
let searchEntryConfig: SearchEntryConfig | undefined = extend(
true,
{
torrentTagSelectors: []
},
schema && schema.searchEntryConfig ? schema.searchEntryConfig : {},
siteService.options.searchEntryConfig
);
let searchEntryConfigQueryString = "";
if (siteService.options.searchEntry) {
searchConfig.rootPath = `sites/${host}/`;
searchConfig.entry = siteService.options.searchEntry;
} else if (schema && schema.searchEntry) {
searchConfig.rootPath = `schemas/${schema.name}/`;
searchConfig.entry = schema.searchEntry;
}
if (schema && schema.torrentTagSelectors) {
searchConfig.torrentTagSelectors = schema.torrentTagSelectors;
}
if (siteService.options.torrentTagSelectors) {
// 是否合并 Schema 的标签选择器
if (siteService.options.mergeSchemaTagSelectors) {
searchConfig.torrentTagSelectors = siteService.options.torrentTagSelectors.concat(
searchConfig.torrentTagSelectors
);
} else {
searchConfig.torrentTagSelectors =
siteService.options.torrentTagSelectors;
}
}
if (!searchConfig.entry) {
result.msg = this.service.i18n.t(
"service.searcher.siteSearchConfigEntryIsEmpty",
{
site
}
); //`该站点[${site.name}]未配置搜索页面,请先配置`;
result.type = EDataResultType.error;
reject(result);
this.service.debug("searchTorrent: tip");
return;
}
// 提取 IMDb 编号,如果带整个网址,则只取编号部分
let imdb = key.match(/(tt\d+)/);
let autoMatched = false;
if (imdb && imdb.length >= 2) {
key = imdb[1];
}
// 将所有 . 替换为空格
key = key.replace(/\./g, " ");
// 是否有搜索入口配置项
if (searchEntryConfig && searchEntryConfig.page) {
siteSearchPage = searchEntryConfig.page;
searchEntryConfigQueryString = searchEntryConfig.queryString + "";
// 搜索区域
if (searchEntryConfig.area) {
searchEntryConfig.area.some((area: SearchEntryConfigArea) => {
// 是否有自动匹配关键字的正则
if (
area.keyAutoMatch &&
new RegExp(area.keyAutoMatch, "").test(key)
) {
// 是否替换默认页面
if (area.page) {
siteSearchPage = area.page;
}
autoMatched = true;
// 如果有定义查询字符串,则替换默认的查询字符串
if (area.queryString) {
searchEntryConfigQueryString = area.queryString;
}
// 追加查询字符串
if (area.appendQueryString) {
searchEntryConfigQueryString += area.appendQueryString;
}
// 替换关键字
if (area.replaceKey) {
key = key.replace(
new RegExp(area.replaceKey[0], "g"),
area.replaceKey[1]
);
}
// 解析脚本,最终返回搜索关键字,可调用 payload 里的数据进行关键字替换
if (area.parseScript) {
try {
key = eval(area.parseScript);
} catch (error) { }
}
return true;
}
return false;
});
}
}
this.searchConfigs[host] = searchConfig;
let results: any[] = [];
let entryCount = 0;
let doneCount = 0;
const KEY = "$key$";
// 转换 uri
key = encodeURIComponent(key);
// 遍历需要搜索的入口
searchConfig.entry.forEach((entry: SearchEntry) => {
let searchPage = entry.entry || siteSearchPage;
// 当已自动匹配规则时,去除入口页面中已指定的关键字字段
if (
autoMatched &&
searchPage.indexOf(KEY) !== -1 &&
searchEntryConfigQueryString.indexOf(KEY) !== -1
) {
searchPage = PPF.removeQueryStringFromValue(searchPage, KEY);
}
let queryString = entry.queryString;
if (searchEntryConfigQueryString) {
// 当前入口没有查询字符串时,尝试使用默认配置
if (!queryString) {
queryString = searchEntryConfigQueryString;
// 当前入口有查询字符串,并且不包含搜索关键字时,使用追加方式
} else if (queryString && queryString.indexOf(KEY) === -1) {
queryString = searchEntryConfigQueryString + "&" + queryString;
}
}
if (entry.appendQueryString) {
queryString += entry.appendQueryString;
}
if (searchEntryConfig) {
entry.parseScriptFile =
searchEntryConfig.parseScriptFile || entry.parseScriptFile;
entry.resultType = searchEntryConfig.resultType || entry.resultType;
entry.resultSelector =
searchEntryConfig.resultSelector || entry.resultSelector;
entry.headers = searchEntryConfig.headers || entry.headers;
entry.asyncParse = searchEntryConfig.asyncParse || entry.asyncParse;
entry.requestData = searchEntryConfig.requestData;
}
// 判断是否指定了搜索页和用于获取搜索结果的脚本
if (searchPage && entry.parseScriptFile && entry.enabled !== false) {
let rows: number =
this.options.search && this.options.search.rows
? this.options.search.rows
: 10;
// 如果有自定义地址,则使用自定义地址
if (site.cdn && site.cdn.length > 0) {
site.url = site.cdn[0];
}
// 组织搜索入口
if ((site.url + "").substr(-1) != "/") {
site.url += "/";
}
if ((searchPage + "").substr(0, 1) == "/") {
searchPage = (searchPage + "").substr(1);
}
let url: string = site.url + searchPage;
if (queryString) {
if (searchPage.indexOf("?") !== -1) {
url += "&" + queryString;
} else {
url += "?" + queryString;
}
}
// 支除重复的参数
url = PPF.removeDuplicateQueryString(url);
let searchKey =
key +
(entry.appendToSearchKeyString
? ` ${entry.appendToSearchKeyString}`
: "");
url = this.replaceKeys(url, {
key: searchKey,
rows: rows,
passkey: site.passkey ? site.passkey : ""
});
// 替换要提交数据中包含的关键字内容
if (entry.requestData) {
try {
for (const key in entry.requestData) {
if (entry.requestData.hasOwnProperty(key)) {
const value = entry.requestData[key];
entry.requestData[key] = PPF.replaceKeys(value, {
key: searchKey,
passkey: site.passkey ? site.passkey : ""
});
if (site.user) {
entry.requestData[key] = PPF.replaceKeys(
value,
site.user,
"user"
);
}
}
}
} catch (error) {
this.service.writeErrorLog(error);
this.service.debug(error);
}
}
// 替换用户相关信息
if (site.user) {
url = this.replaceKeys(url, site.user, "user");
}
entryCount++;
let scriptPath = entry.parseScriptFile;
// 判断是否为相对路径
if (scriptPath.substr(0, 1) !== "/") {
scriptPath = `${searchConfig.rootPath}${scriptPath}`;
}
entry.parseScript = this.parseScriptCache[scriptPath];
if (!entry.parseScript) {
this.service.debug("searchTorrent: getScriptContent", scriptPath);
APP.getScriptContent(scriptPath)
.done((script: string) => {
this.service.debug(
"searchTorrent: getScriptContent done",
scriptPath
);
this.parseScriptCache[scriptPath] = script;
entry.parseScript = script;
this.getSearchResult(
url,
site,
Object.assign(PPF.clone(searchEntryConfig), PPF.clone(entry)),
searchConfig.torrentTagSelectors
)
.then((result: any) => {
this.service.debug(
"searchTorrent: getSearchResult done",
url
);
if (result && result.length) {
results.push(...result);
}
doneCount++;
if (doneCount === entryCount || results.length >= rows) {
resolve(results.slice(0, rows));
}
})
.catch((result: any) => {
this.service.debug(
"searchTorrent: getSearchResult catch",
url,
result
);
doneCount++;
if (doneCount === entryCount) {
if (results.length > 0) {
resolve(results.slice(0, rows));
} else {
reject(result);
}
}
});
})
.fail(error => {
this.service.debug(
"searchTorrent: getScriptContent fail",
error
);
});
} else {
this.getSearchResult(
url,
site,
Object.assign(PPF.clone(searchEntryConfig), PPF.clone(entry)),
searchConfig.torrentTagSelectors
)
.then((result: any) => {
if (result && result.length) {
results.push(...result);
}
doneCount++;
if (doneCount === entryCount || results.length >= rows) {
resolve(results.slice(0, rows));
}
})
.catch((result: any) => {
doneCount++;
if (doneCount === entryCount) {
if (results.length > 0) {
resolve(results.slice(0, rows));
} else {
reject(result);
}
}
});
}
}
});
// 没有指定搜索入口
if (entryCount == 0) {
result.msg = this.service.i18n.t(
"service.searcher.siteSearchEntryIsEmpty",
{
site
}
); //`该站点[${site.name}]未指定搜索页面,请先指定一个搜索入口`;
result.type = EDataResultType.error;
reject(result);
}
this.service.debug("searchTorrent: quene done");
});
}
/**
* 获取搜索结果
* @param url
* @param site
* @param entry
* @param torrentTagSelectors
*/
public getSearchResult(
url: string,
site: Site,
entry: SearchEntry,
torrentTagSelectors?: any[]
): Promise<any> {
return new Promise<any>((resolve?: any, reject?: any) => {
// 是否有需要搜索前处理的数据
if (entry.beforeSearch) {
let pageParser = new PageParser(
entry.beforeSearch,
site,
this.service.options.connectClientTimeout
);
pageParser
.getInfos()
.then(beforeSearchData => {
this.addSearchRequestQueue(
url,
site,
entry,
torrentTagSelectors,
beforeSearchData
)
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
});
})
.catch(error => {
this.service.writeErrorLog(error);
this.addSearchRequestQueue(url, site, entry, torrentTagSelectors)
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
});
});
} else {
this.addSearchRequestQueue(url, site, entry, torrentTagSelectors)
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
});
}
});
}
/**
* 获取搜索结果
* @param url
* @param site
* @param entry
* @param torrentTagSelectors
*/
public addSearchRequestQueue(
url: string,
site: Site,
entry: SearchEntry,
torrentTagSelectors?: any[],
beforeSearchData?: any
): Promise<any> {
let _entry = PPF.clone(entry);
if (_entry.parseScript) {
delete _entry.parseScript;
}
// 是否包含搜索前处理的数据
if (beforeSearchData) {
this.service.debug("beforeSearchData", beforeSearchData);
url = this.replaceKeys(url, beforeSearchData, "beforeSearchData");
// 替换要提交数据中包含的关键字内容
if (entry.requestData) {
try {
for (const key in entry.requestData) {
if (entry.requestData.hasOwnProperty(key)) {
const value = entry.requestData[key];
entry.requestData[key] = PPF.replaceKeys(
value,
beforeSearchData,
"beforeSearchData"
);
}
}
} catch (error) {
this.service.writeErrorLog(error);
this.service.debug(error);
}
}
}
this.service.debug("getSearchResult.start", {
url,
site: site.host,
entry: _entry
});
let logId = "";
return new Promise<any>((resolve?: any, reject?: any) => {
this.searchRequestQueue[url] = $.ajax({
url: url,
cache: false,
dataType: "text",
contentType: "text/plain",
timeout: this.options.connectClientTimeout || 30000,
headers: entry.headers,
method: entry.requestMethod || ERequestMethod.GET,
data: entry.requestData
})
.done((result: any) => {
this.service.debug("getSearchResult.done", url);
delete this.searchRequestQueue[url];
if (
(result && typeof result == "string" && result.length > 100) ||
typeof result == "object"
) {
let page: any;
let doc: any;
try {
switch (entry.resultType) {
case ERequestResultType.JSON:
page = JSON.parse(result);
break;
default:
doc = new DOMParser().parseFromString(result, "text/html");
// 构造 jQuery 对象
page = $(doc).find("body");
break;
}
} catch (error) {
logId = this.service.logger.add({
module: EModule.background,
event:
"service.searcher.getSearchResult.siteSearchResultParseFailed",
msg: error
});
// 数据解析失败
reject({
success: false,
msg: this.service.i18n.t(
"service.searcher.siteSearchResultParseFailed",
{
site
}
),
data: {
logId
}
});
return;
}
let options: any = {
results: [],
responseText: result,
site,
resultSelector: entry.resultSelector,
page,
entry,
torrentTagSelectors: torrentTagSelectors,
errorMsg: "",
isLogged: false,
status: ESearchResultParseStatus.success,
searcher: this,
url
};
// 执行获取结果的脚本
try {
if (entry.parseScript) {
// 异步脚本,由脚本负责调用 reject 和 resolve
if (entry.asyncParse) {
options = Object.assign(
{
reject,
resolve
},
options
);
eval(entry.parseScript);
return;
} else {
eval(entry.parseScript);
}
}
if (
options.errorMsg ||
options.status != ESearchResultParseStatus.success
) {
reject({
success: false,
msg: this.getErrorMessage(
site,
options.status,
options.errorMsg
),
data: {
site,
isLogged: options.isLogged
}
});
} else {
resolve(PPF.clone(options.results));
}
} catch (error) {
console.error(error);
logId = this.service.logger.add({
module: EModule.background,
event: "service.searcher.getSearchResult.siteEvalScriptFailed",
msg: error
});
// 脚本执行出错
reject({
success: false,
msg: this.service.i18n.t(
"service.searcher.siteEvalScriptFailed",
{
site
}
),
data: {
logId
}
});
}
} else {
logId = this.service.logger.add({
module: EModule.background,
event: "service.searcher.getSearchResult.siteSearchResultError",
msg: result
});
// 没有返回预期的数据
reject({
success: false,
msg: this.service.i18n.t(
"service.searcher.siteSearchResultError",
{
site
}
),
data: {
logId
},
type: EDataResultType.error
});
}
})
.fail((jqXHR, textStatus, errorThrown) => {
delete this.searchRequestQueue[url];
this.service.debug({
title: "getSearchResult.fail",
url,
entry,
textStatus,
errorThrown
});
logId = this.service.logger.add({
module: EModule.background,
event: "service.searcher.getSearchResult.fail",
msg: errorThrown,
data: {
url,
entry,
code: jqXHR.status,
textStatus,
errorThrown,
responseText: jqXHR.responseText
}
});
// 网络请求失败
reject({
data: {
logId,
textStatus
},
msg: this.service.i18n.t("service.searcher.siteNetworkFailed", {
site,
msg: `${jqXHR.status} ${errorThrown}, ${textStatus}`
}),
success: false,
type: EDataResultType.error
});
});
});
}
/**
* 根据错误代码获取错误信息
* @param code
*/
public getErrorMessage(
site: Site,
status: ESearchResultParseStatus = ESearchResultParseStatus.success,
msg: string = ""
): string {
if (status != ESearchResultParseStatus.success) {
return this.service.i18n.t(`contentPage.search.${status}`, {
siteName: site.name,
msg
});
}
return msg;
}
/**
* 取消正在执行的搜索请求
* @param site
* @param key
*/
public abortSearch(site: Site, key: string = ""): Promise<any> {
return new Promise<any>((resolve?: any, reject?: any) => {
let host = site.host + "";
let searchConfig: SearchConfig = this.searchConfigs[host];
if (searchConfig.entry) {
this.service.logger.add({
module: EModule.background,
event: "searcher.abortSearch",
msg: this.service.i18n.t("service.searcher.siteAbortSearch", {
site
}), //`正在取消[${site.host}]的搜索请求`,
data: {
site: site.host,
key: key
}
});
searchConfig.entry.forEach((entry: SearchEntry) => {
// 判断是否指定了搜索页和用于获取搜索结果的脚本
if (entry.entry && entry.parseScriptFile && entry.enabled !== false) {
// 如果有自定义地址,则使用自定义地址
if (site.cdn && site.cdn.length > 0) {
site.url = site.cdn[0];
}
let rows: number =
this.options.search && this.options.search.rows
? this.options.search.rows
: 10;
let url: string = site.url + entry.entry;
url = this.replaceKeys(url, {
key: key,
rows: rows,
passkey: site.passkey ? site.passkey : ""
});
let queue = this.searchRequestQueue[url];
if (queue) {
try {
queue.abort();
resolve();
} catch (error) {
this.service.logger.add({
module: EModule.background,
event: "searcher.abortSearch.error",
msg: this.service.i18n.t(
"service.searcher.siteAbortSearchError",
{
site
}
), // "取消搜索请求失败",
data: {
site: site.host,
key: key,
error
}
});
reject(error);
}
} else {
resolve();
}
} else {
resolve();
}
});
}
});
}
/**
* 根据指定的站点获取站点的架构信息
* @param site 站点信息
*/
getSiteSchema(site: Site): SiteSchema {
let schema: SiteSchema = {};
if (typeof site.schema === "string") {
schema =
this.options.system &&
this.options.system.schemas &&
this.options.system.schemas.find((item: SiteSchema) => {
return item.name == site.schema;
});
if (schema === undefined) {
return schema;
}
}
return PPF.clone(schema);
}
/**
* 替换指定的字符串列表
* @param source
* @param keys
*/
replaceKeys(
source: string,
keys: Dictionary<any>,
prefix: string = ""
): string {
let result: string = source;
for (const key in keys) {
if (keys.hasOwnProperty(key)) {
const value = keys[key];
let search = "$" + key + "$";
if (prefix) {
search = `$${prefix}.${key}$`;
}
result = result.replace(search, value);
}
}
return result;
}
/**
* 从当前行中获取指定字段的值
* @param site 当前站点
* @param row 当前行
* @param fieldName 字段名称
* @return null 表示没有获取到内容
*/
public getFieldValue(
site: Site,
row: JQuery<HTMLElement>,
fieldName: string = ""
) {
let selector: any;
if (site.searchEntryConfig && site.searchEntryConfig.fieldSelector) {
selector = site.searchEntryConfig.fieldSelector[fieldName];
if (!selector) {
return null;
}
} else {
return null;
}
const parser = new InfoParser(this.service);
return parser.getFieldData(
row,
selector,
site.searchEntryConfig.fieldSelector
);
}
/**
* 根据指定信息获取分类
* @param site 站点
* @param page 当前搜索页面
* @param id 分类ID
*/
public getCategoryById(site: Site, page: string, id: string) {
let result = {};
if (site.categories) {
site.categories.forEach((item: SiteCategories) => {
if (
item.category &&
(item.entry == "*" || page.indexOf(item.entry as string))
) {
let category = item.category.find((c: SiteCategory) => {
return c.id == id;
});
if (category) {
result = category;
}
}
});
}
return result;
}
/**
* cloudflare Email 解码方法,来自 https://usamaejaz.com/cloudflare-email-decoding/
* @param {*} encodedString
*/
public cfDecodeEmail(encodedString: string) {
let email = "",
r = parseInt(encodedString.substr(0, 2), 16),
n,
i;
for (n = 2; encodedString.length - n; n += 2) {
i = parseInt(encodedString.substr(n, 2), 16) ^ r;
email += String.fromCharCode(i);
}
return email;
}
/**
* 获取指定站点当前行标签列表
* @param site
* @param row
*/
public getRowTags(site: Site, row: JQuery<HTMLElement>) {
let tags: {}[] = [];
if (site && site.host) {
let config = this.searchConfigs[site.host];
let selectors = config.torrentTagSelectors;
if (selectors && selectors.length > 0) {
selectors.forEach((item: any) => {
if (item.selector) {
let result = row.find(item.selector);
if (result.length) {
let color = item.color || BASE_TAG_COLORS[item.name] || "";
let data: Dictionary<any> = {
name: item.name,
color
};
if (item.title && result.attr(item.title)) {
data.title = result.attr(item.title);
}
tags.push(data);
}
}
});
}
}
return tags;
}
} | the_stack |
import BigNumber from 'bignumber.js'
import AsyncStorage from '@react-native-community/async-storage'
import moment from 'moment'
import { combineReducers } from 'redux'
import RNFS from 'react-native-fs'
import { persistReducer } from 'redux-persist'
import {
ADDRESS_TRANSPORT_METHOD,
getConfigForRust,
mapRustTx,
mapRustOutputStrategy,
getSlatePath,
} from 'src/common'
import { log } from 'src/common/logger'
import {
RustTx,
Tx,
Action,
Store,
Slate,
txCancelRequestAction,
txListRequestAction,
txCreateRequestAction,
txSendAddressRequestAction,
txPostRequestAction,
txReceiveRequestAction,
txFinalizeRequestAction,
slateSetRequestAction,
slateRemoveRequestAction,
txPostCloseAction,
txGetRequestAction,
txFormOutputStrategiesRequestAction,
OutputStrategy,
Error as AppError,
} from 'src/common/types'
import { getNavigation } from './navigation'
import { RootState } from 'src/common/redux'
import WalletBridge from 'src/bridges/wallet'
export type ListState = {
data: Array<Tx>
inProgress: boolean
isOffline: boolean
refreshFromNode: boolean
showLoader: boolean
lastUpdated: moment.Moment | undefined | null
error: AppError | undefined | null
}
export type TxCreateState = {
data: Tx | undefined | null
created: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxSendState = {
data: Tx | undefined | null
sent: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxPostState = {
txSlateId: string | undefined | null
showModal: boolean
posted: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxGetState = {
data: Tx | undefined | null
isRefreshed: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxReceiveState = {
data: Tx | undefined | null
received: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxFinalizeState = {
data: Tx | undefined | null
finalized: boolean
inProgress: boolean
error: AppError | undefined | null
}
export type TxCancelState = {
data: Tx | undefined | null
inProgress: boolean
error: AppError | undefined | null
}
export type TxForm = {
amount: number
outputStrategy: OutputStrategy | undefined | null
outputStrategies: Array<OutputStrategy>
outputStrategies_error: string
outputStrategies_inProgress: boolean
textAmount: string
message: string
address: string
}
export type SlateShareState = {
inProgress: boolean
}
export type SlateState = {
data: Slate | undefined | null
inProgress: boolean
error: AppError | undefined | null
}
export type State = Readonly<{
list: ListState
txCreate: TxCreateState
txSend: TxSendState
txGet: TxGetState
txPost: TxPostState
txCancel: TxCancelState
txReceive: TxReceiveState
txFinalize: TxFinalizeState
txForm: TxForm
slate: SlateState
slateShare: SlateShareState
}>
const initialState: State = {
list: {
data: [],
inProgress: false,
showLoader: false,
isOffline: false,
refreshFromNode: false,
lastUpdated: null,
error: null,
},
txCreate: {
data: null,
created: false,
inProgress: false,
error: null,
},
txSend: {
data: null,
sent: false,
inProgress: false,
error: null,
},
txPost: {
txSlateId: null,
posted: false,
showModal: false,
inProgress: false,
error: null,
},
txGet: {
data: null,
isRefreshed: false,
inProgress: false,
error: null,
},
txReceive: {
data: null,
received: false,
inProgress: false,
error: null,
},
txFinalize: {
data: null,
finalized: false,
inProgress: false,
error: null,
},
txCancel: {
data: null,
inProgress: false,
error: null,
},
txForm: {
amount: 0,
outputStrategy: null,
outputStrategies: [],
outputStrategies_error: '',
outputStrategies_inProgress: false,
textAmount: '',
message: '',
address: '',
},
slate: {
data: null,
inProgress: false,
error: null,
},
slateShare: {
inProgress: false,
},
}
function twoStringArrayEqual<T>(a: T[], b: T[]) {
return (a || []).join('') === (b || []).join('')
}
async function getArrayFromStorage(key: string) {
const raw = await AsyncStorage.getItem(key)
if (!raw) {
return []
}
return JSON.parse(raw)
}
// Catching received transaction
function filterReceivedUnconfirmed(tx: Tx) {
return !tx.confirmed && tx.type === 'TxReceived'
}
export const sideEffects = {
['TX_LIST_REQUEST']: async (action: txListRequestAction, store: Store) => {
try {
const finalized = await getArrayFromStorage('@finalizedTxs')
const newFinalized: string[] = []
const posted = await getArrayFromStorage('@postedTxs')
const newPosted: string[] = []
const received = await getArrayFromStorage('@receivedTxs')
const newReceived: string[] = []
const data = await WalletBridge.txsGet(
getConfigForRust(store.getState()).minimum_confirmations,
action.refreshFromNode,
).then(JSON.parse)
let mappedData = data[1]
.filter((tx: RustTx) => tx.tx_type.indexOf('Cancelled') === -1)
.map((tx: RustTx) => {
let pos = finalized.indexOf(tx.tx_slate_id)
if (pos !== -1) {
if (tx.confirmed) {
return tx
} else if (tx.tx_slate_id) {
newFinalized.push(tx.tx_slate_id)
return { ...tx, tx_type: 'TxFinalized' }
}
}
pos = posted.indexOf(tx.tx_slate_id)
if (pos !== -1) {
if (tx.confirmed) {
return tx
} else if (tx.tx_slate_id) {
newPosted.push(tx.tx_slate_id)
return { ...tx, tx_type: 'TxPosted' }
}
}
pos = received.indexOf(tx.tx_slate_id)
if (pos !== -1 && !tx.confirmed && tx.tx_slate_id) {
newReceived.push(tx.tx_slate_id)
}
return tx
})
// TODO: This horrible parody of atomic changes should be rewritten in a proper way
if (
twoStringArrayEqual(received, await getArrayFromStorage('@receivedTxs'))
) {
await AsyncStorage.setItem('@receivedTxs', JSON.stringify(newReceived))
}
if (
twoStringArrayEqual(
finalized,
await getArrayFromStorage('@finalizedTxs'),
)
) {
await AsyncStorage.setItem(
'@finalizedTxs',
JSON.stringify(newFinalized),
)
}
if (
twoStringArrayEqual(posted, await getArrayFromStorage('@postedTxs'))
) {
await AsyncStorage.setItem('@postedTxs', JSON.stringify(newPosted))
}
mappedData = mappedData.map(mapRustTx)
if (
mappedData.filter(filterReceivedUnconfirmed).length >
store.getState().tx.list.data.filter(filterReceivedUnconfirmed).length
) {
store.dispatch({
type: 'TOAST_SHOW',
text: 'Transaction has been received',
})
}
store.dispatch({
type: 'TX_LIST_SUCCESS',
data: mappedData,
isRefreshed: data[0],
balance: data[2],
})
} catch (e) {
store.dispatch({
type: 'TX_LIST_FAILURE',
message: e.message,
})
log(e, true)
}
},
['TX_CANCEL_REQUEST']: (action: txCancelRequestAction, store: Store) => {
return WalletBridge.txCancel(action.id)
.then(() => {
store.dispatch({
type: 'TX_CANCEL_SUCCESS',
})
store.dispatch({
type: 'SLATE_REMOVE_REQUEST',
id: action.slateId,
isResponse: action.isResponse,
})
store.dispatch({
type: 'TX_LIST_REQUEST',
showLoader: false,
refreshFromNode: false,
})
})
.catch((error) => {
const e = JSON.parse(error.message)
store.dispatch({
type: 'TX_CANCEL_FAILURE',
code: 1,
message: error,
})
log(e, true)
})
},
['TX_GET_REQUEST']: async (action: txGetRequestAction, store: Store) => {
return WalletBridge.txGet(true, action.txSlateId)
.then((json: string) => JSON.parse(json))
.then((result) => {
store.dispatch({
type: 'TX_GET_SUCCESS',
isRefreshed: result[0],
tx: result[1][0],
})
})
.catch((error) => {
const e = JSON.parse(error.message)
store.dispatch({
type: 'TX_GET_FAILURE',
code: 1,
message: error,
})
log(e, true)
})
},
['TX_CREATE_REQUEST']: async (
action: txCreateRequestAction,
store: Store,
) => {
try {
const jsonResponse = await WalletBridge.txCreate(
action.amount,
getConfigForRust(store.getState()).minimum_confirmations,
action.selectionStrategyIsUseAll,
)
const [[rustTx], slatepack] = JSON.parse(jsonResponse)
const tx = mapRustTx(rustTx)
store.dispatch({
type: 'TX_CREATE_SUCCESS',
})
if (tx.slateId) {
store.dispatch({
type: 'SLATE_SET_REQUEST',
id: tx.slateId,
slatepack,
isResponse: false,
})
}
const navigation = await getNavigation()
navigation?.navigate('TxIncompleteSend', { tx })
store.dispatch({
type: 'TX_LIST_REQUEST',
showLoader: false,
refreshFromNode: false,
})
} catch (error) {
store.dispatch({
type: 'TX_CREATE_FAILURE',
message: error.message,
})
log(error, true)
}
},
['TX_SEND_ADDRESS_REQUEST']: async (
action: txSendAddressRequestAction,
store: Store,
) => {
try {
const finalized = await getArrayFromStorage('@finalizedTxs')
const slateId = await WalletBridge.txSendAddress(
action.amount,
getConfigForRust(store.getState()).minimum_confirmations,
action.selectionStrategyIsUseAll,
action.address,
).then(JSON.parse)
finalized.push(slateId)
await AsyncStorage.setItem('@finalizedTxs', JSON.stringify(finalized))
store.dispatch({
type: 'TX_SEND_ADDRESS_SUCCESS',
})
const navigation = await getNavigation()
navigation?.goBack()
store.dispatch({
type: 'TX_POST_SHOW',
txSlateId: slateId,
})
} catch (e) {
if (e.message.indexOf('HostUnreachable') !== -1) {
store.dispatch({
type: 'TX_CREATE_REQUEST',
amount: action.amount,
selectionStrategyIsUseAll: action.selectionStrategyIsUseAll,
})
} else {
store.dispatch({
type: 'TX_SEND_ADDRESS_FAILURE',
message: e.message,
})
log(e, true)
}
}
},
['TX_POST_REQUEST']: async (action: txPostRequestAction, store: Store) => {
try {
const finalized = await getArrayFromStorage('@finalizedTxs')
const posted = await getArrayFromStorage('@postedTxs')
await WalletBridge.txPost(action.txSlateId)
posted.push(action.txSlateId)
const pos = finalized.indexOf(action.txSlateId)
if (pos !== -1) {
finalized.splice(pos, 1)
}
await AsyncStorage.setItem('@finalizedTxs', JSON.stringify(finalized))
await AsyncStorage.setItem('@postedTxs', JSON.stringify(posted))
store.dispatch({
type: 'TX_POST_SUCCESS',
})
setTimeout(() => {
store.dispatch({
type: 'TX_POST_CLOSE',
})
}, 3000)
} catch (e) {
store.dispatch({
type: 'TX_POST_FAILURE',
message: e.message,
})
log(e, true)
}
},
['TX_POST_CLOSE']: async (_action: txPostCloseAction, store: Store) => {
store.dispatch({
type: 'TX_LIST_REQUEST',
showLoader: false,
refreshFromNode: false,
})
},
['TX_RECEIVE_REQUEST']: async (
action: txReceiveRequestAction,
store: Store,
) => {
try {
const received = await getArrayFromStorage('@receivedTxs')
const [[rustTx], slatepack] = await WalletBridge.txReceive(
getConfigForRust(store.getState()).account,
action.slatepack,
).then((json: string) => JSON.parse(json))
const tx = mapRustTx(rustTx)
received.push(tx.slateId)
await AsyncStorage.setItem('@receivedTxs', JSON.stringify(received))
store.dispatch({
type: 'TX_RECEIVE_SUCCESS',
})
if (tx.slateId) {
store.dispatch({
type: 'SLATE_SET_REQUEST',
id: tx.slateId,
slatepack,
isResponse: true,
})
}
const navigation = await getNavigation()
navigation?.navigate('TxIncompleteReceive', { tx })
store.dispatch({
type: 'TX_LIST_REQUEST',
showLoader: false,
refreshFromNode: false,
})
} catch (e) {
store.dispatch({
type: 'TX_RECEIVE_FAILURE',
message: e.message,
})
log(e, true)
}
},
['TX_FINALIZE_REQUEST']: async (
action: txFinalizeRequestAction,
store: Store,
) => {
try {
const finalized = await getArrayFromStorage('@finalizedTxs')
try {
const [rustTx] = await WalletBridge.txFinalize(action.slatepack).then(
JSON.parse,
)
// this hack is needed until TxFinalized is not natively supported
const tx = mapRustTx({ ...rustTx, tx_type: 'TxFinalized' })
store.dispatch({
type: 'TX_FINALIZE_SUCCESS',
})
finalized.push(tx.slateId)
await AsyncStorage.setItem('@finalizedTxs', JSON.stringify(finalized))
const navigation = await getNavigation()
navigation?.navigate('Overview')
if (tx.slateId) {
store.dispatch({
type: 'TX_POST_SHOW',
txSlateId: tx.slateId,
})
}
} catch (e) {
console.log(e.message)
if (
e.message.indexOf(
'LibWallet Error: Wallet store error: DB Not Found Error: Slate id: ',
) !== -1
) {
log(
{
message:
'Slate has been already finalized. You only need to confirm it now',
},
true,
)
} else {
throw e
}
}
} catch (e) {
store.dispatch({
type: 'TX_FINALIZE_FAILURE',
message: e.message,
})
log(e, true)
}
},
['SLATE_SET_REQUEST']: (action: slateSetRequestAction, store: Store) => {
const path = getSlatePath(action.id, action.isResponse)
return RNFS.writeFile(path, action.slatepack, 'utf8')
.then(() => {
store.dispatch({
type: 'SLATE_SET_SUCCESS',
})
})
.catch((error) => {
store.dispatch({
type: 'SLATE_SET_FAILURE',
code: 1,
message: error.message,
})
log(error, true)
})
},
['SLATE_REMOVE_REQUEST']: async (
action: slateRemoveRequestAction,
store: Store,
) => {
const path = getSlatePath(action.id, action.isResponse)
if (await RNFS.exists(path)) {
return RNFS.unlink(path)
.then(() => {
store.dispatch({
type: 'SLATE_REMOVE_SUCCESS',
})
})
.catch((error) => {
store.dispatch({
type: 'SLATE_REMOVE_FAILURE',
code: 1,
message: error.message,
})
log(error, true)
})
} else {
store.dispatch({
type: 'SLATE_REMOVE_SUCCESS',
})
}
},
['TX_FORM_OUTPUT_STRATEGIES_REQUEST']: (
action: txFormOutputStrategiesRequestAction,
store: Store,
) => {
return WalletBridge.txStrategies(
action.amount,
getConfigForRust(store.getState()).minimum_confirmations,
)
.then((json: string) => JSON.parse(json))
.then((outputStrategies) => {
if (!outputStrategies.length) {
throw new Error('Not enough funds')
}
store.dispatch({
type: 'TX_FORM_OUTPUT_STRATEGIES_SUCCESS',
outputStrategies,
})
})
.catch((error: Error) => {
store.dispatch({
type: 'TX_FORM_OUTPUT_STRATEGIES_FAILURE',
code: 1,
message: error.message,
})
})
},
}
const list = function (
state: ListState = initialState.list,
action: Action,
): ListState {
switch (action.type) {
case 'TX_LIST_CLEAR':
return { ...state, data: [] }
case 'TX_LIST_REQUEST':
return {
...state,
inProgress: true,
refreshFromNode: action.refreshFromNode,
showLoader: action.showLoader,
error: null,
}
case 'TX_LIST_SUCCESS': {
const txs: Tx[] = action.data.slice(0)
txs.sort(function (a, b) {
return (
new Date(b.creationTime).getTime() -
new Date(a.creationTime).getTime()
)
})
return {
...state,
data: txs,
showLoader: false,
refreshFromNode: false,
isOffline: state.refreshFromNode && !action.isRefreshed,
lastUpdated: moment(),
inProgress: false,
}
}
case 'TX_LIST_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
isOffline: false,
refreshFromNode: false,
showLoader: false,
inProgress: false,
lastUpdated: moment(),
}
default:
return state
}
}
const txCreate = function (
state: TxCreateState = initialState.txCreate,
action: Action,
): TxCreateState {
switch (action.type) {
case 'TX_CREATE_REQUEST':
return { ...state, inProgress: true, created: false, error: null }
case 'TX_CREATE_SUCCESS':
return { ...state, created: true, inProgress: false }
case 'TX_CREATE_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
created: false,
inProgress: false,
}
case 'TX_FORM_RESET':
return { ...state, created: false }
default:
return state
}
}
const txSend = function (
state: TxSendState = initialState.txSend,
action: Action,
): TxSendState {
switch (action.type) {
case 'TX_SEND_ADDRESS_REQUEST':
return { ...state, inProgress: true, sent: false, error: null }
case 'TX_SEND_ADDRESS_SUCCESS':
return { ...state, sent: true, inProgress: false }
case 'TX_SEND_ADDRESS_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
sent: false,
inProgress: false,
}
case 'TX_FORM_RESET':
return { ...state, sent: false }
default:
return state
}
}
const txPost = function (
state: TxPostState = initialState.txPost,
action: Action,
): TxPostState {
switch (action.type) {
case 'TX_POST_SHOW':
return {
...state,
txSlateId: action.txSlateId,
showModal: true,
posted: false,
}
case 'TX_POST_CLOSE':
return { ...state, txSlateId: null, showModal: false, posted: false }
case 'TX_POST_REQUEST':
return { ...state, inProgress: true, posted: false, error: null }
case 'TX_POST_SUCCESS':
return { ...state, inProgress: false, posted: true }
case 'TX_POST_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
posted: false,
inProgress: false,
}
default:
return state
}
}
const txGet = function (
state: TxGetState = initialState.txGet,
action: Action,
): TxGetState {
switch (action.type) {
case 'TX_GET_REQUEST':
return {
data: initialState.txGet.data,
inProgress: true,
isRefreshed: false,
error: null,
}
case 'TX_GET_SUCCESS':
return {
...state,
data: mapRustTx(action.tx),
isRefreshed: action.isRefreshed,
inProgress: false,
}
case 'TX_GET_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
isRefreshed: false,
inProgress: false,
}
default:
return state
}
}
const txCancel = function (
state: TxCancelState = initialState.txCancel,
action: Action,
): TxCancelState {
switch (action.type) {
case 'TX_CANCEL_REQUEST':
return { ...state, inProgress: true, error: null }
case 'TX_CANCEL_SUCCESS':
return { ...state, inProgress: false }
case 'TX_CANCEL_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
inProgress: false,
}
default:
return state
}
}
const txReceive = function (
state: TxReceiveState = initialState.txReceive,
action: Action,
): TxReceiveState {
switch (action.type) {
case 'TX_RECEIVE_REQUEST':
return { ...state, inProgress: true, received: false, error: null }
case 'TX_RECEIVE_SUCCESS':
return { ...state, received: true, inProgress: false }
case 'TX_RECEIVE_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
received: false,
inProgress: false,
}
default:
return state
}
}
const txFinalize = function (
state: TxFinalizeState = initialState.txFinalize,
action: Action,
): TxFinalizeState {
switch (action.type) {
case 'TX_FINALIZE_REQUEST':
return { ...state, inProgress: true, finalized: false, error: null }
case 'TX_FINALIZE_SUCCESS':
return { ...state, finalized: true, inProgress: false }
case 'TX_FINALIZE_FAILURE':
return {
...state,
error: {
code: action.code,
message: action.message,
},
finalized: false,
inProgress: false,
}
default:
return state
}
}
const txForm = function (
state: TxForm = initialState.txForm,
action: Action,
): TxForm {
switch (action.type) {
case 'TX_FORM_SET_FROM_LINK':
return {
...initialState.txForm,
amount: action.amount,
textAmount: action.textAmount,
address: action.url,
message: action.message,
}
case 'TX_FORM_SET_AMOUNT':
return { ...state, amount: action.amount, textAmount: action.textAmount }
case 'TX_FORM_SET_ADDRESS':
return { ...state, address: action.address }
case 'TX_FORM_SET_OUTPUT_STRATEGY':
return { ...state, outputStrategy: action.outputStrategy }
case 'TX_FORM_OUTPUT_STRATEGIES_REQUEST':
return {
...state,
outputStrategies_inProgress: true,
outputStrategies_error: '',
outputStrategies: [],
outputStrategy: null,
}
case 'TX_FORM_OUTPUT_STRATEGIES_FAILURE':
return {
...state,
outputStrategies_inProgress: false,
outputStrategies_error: action.message,
outputStrategies: [],
outputStrategy: null,
}
case 'TX_FORM_OUTPUT_STRATEGIES_SUCCESS': {
const strategies =
action.outputStrategies.length == 2 &&
action.outputStrategies[0].fee === action.outputStrategies[1].fee &&
action.outputStrategies[0].total == action.outputStrategies[1].total
? [action.outputStrategies[0]]
: action.outputStrategies
const outputStrategies = strategies
.map(mapRustOutputStrategy)
.sort((a: OutputStrategy, b: OutputStrategy) => {
return new BigNumber(a.fee).minus(b.fee).toNumber()
})
return {
...state,
outputStrategies,
outputStrategy: outputStrategies.length ? outputStrategies[0] : null,
outputStrategies_inProgress: false,
outputStrategies_error: '',
}
}
case 'TX_FORM_SET_MESSAGE':
return { ...state, message: action.message }
case 'TX_FORM_RESET':
return { ...initialState.txForm }
default:
return state
}
}
const listPersistConfig = {
key: 'list',
storage: AsyncStorage,
whitelist: ['data'],
}
export const isTxFormInvalid = (txForm: TxForm, transferMethod: string) => {
const { address, amount, outputStrategy } = txForm
if (
!amount ||
!outputStrategy ||
(transferMethod === ADDRESS_TRANSPORT_METHOD &&
address.toLowerCase().indexOf('grin') === -1)
) {
return true
}
return false
}
export const reducer = combineReducers({
list: persistReducer(listPersistConfig, list) as typeof list,
txCreate,
txSend,
txPost,
txGet,
txCancel,
txReceive,
txFinalize,
txForm,
})
export const txListSelector = (state: RootState) => state.tx.list.data | the_stack |
import {
INodeProperties,
} from 'n8n-workflow';
export const fileOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'file',
],
},
},
options: [
{
name: 'Copy',
value: 'copy',
description: 'Copy a file',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a file',
},
{
name: 'Download',
value: 'download',
description: 'Download a file',
},
{
name: 'Get',
value: 'get',
description: 'Get a file',
},
{
name: 'Search',
value: 'search',
description: 'Search files',
},
{
name: 'Share',
value: 'share',
description: 'Share a file',
},
{
name: 'Upload',
value: 'upload',
description: 'Upload a file',
},
],
default: 'upload',
description: 'The operation to perform.',
},
];
export const fileFields: INodeProperties[] = [
/* -------------------------------------------------------------------------- */
/* file:copy */
/* -------------------------------------------------------------------------- */
{
displayName: 'File ID',
name: 'fileId',
type: 'string',
required: true,
displayOptions: {
show: {
operation: [
'copy',
],
resource: [
'file',
],
},
},
default: '',
description: 'File ID',
},
{
displayName: 'Parent ID',
name: 'parentId',
type: 'string',
default: '',
displayOptions: {
show: {
operation: [
'copy',
],
resource: [
'file',
],
},
},
description: 'The ID of folder to copy the file to. If not defined will be copied to the root folder',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
displayOptions: {
show: {
operation: [
'copy',
],
resource: [
'file',
],
},
},
default: {},
options: [
{
displayName: 'Fields',
name: 'fields',
type: 'string',
default: '',
description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response.',
},
{
displayName: 'Name',
name: 'name',
type: 'string',
default: '',
description: 'An optional new name for the copied file.',
},
{
displayName: 'Version',
name: 'version',
type: 'string',
default: '',
description: 'An optional ID of the specific file version to copy.',
},
],
},
/* -------------------------------------------------------------------------- */
/* file:delete */
/* -------------------------------------------------------------------------- */
{
displayName: 'File ID',
name: 'fileId',
type: 'string',
displayOptions: {
show: {
operation: [
'delete',
],
resource: [
'file',
],
},
},
default: '',
description: 'Field ID',
},
/* -------------------------------------------------------------------------- */
/* file:download */
/* -------------------------------------------------------------------------- */
{
displayName: 'File ID',
name: 'fileId',
type: 'string',
displayOptions: {
show: {
operation: [
'download',
],
resource: [
'file',
],
},
},
default: '',
description: 'File ID',
},
{
displayName: 'Binary Property',
name: 'binaryPropertyName',
type: 'string',
required: true,
default: 'data',
displayOptions: {
show: {
operation: [
'download',
],
resource: [
'file',
],
},
},
description: 'Name of the binary property to which to write the data of the read file.',
},
/* -------------------------------------------------------------------------- */
/* file:get */
/* -------------------------------------------------------------------------- */
{
displayName: 'File ID',
name: 'fileId',
type: 'string',
displayOptions: {
show: {
operation: [
'get',
],
resource: [
'file',
],
},
},
default: '',
description: 'Field ID',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
displayOptions: {
show: {
operation: [
'get',
],
resource: [
'file',
],
},
},
default: {},
options: [
{
displayName: 'Fields',
name: 'fields',
type: 'string',
default: '',
description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response.',
},
],
},
/* -------------------------------------------------------------------------- */
/* file:search */
/* -------------------------------------------------------------------------- */
{
displayName: 'Query',
name: 'query',
type: 'string',
displayOptions: {
show: {
operation: [
'search',
],
resource: [
'file',
],
},
},
default: '',
description: 'The string to search for. This query is matched against item names, descriptions, text content of files, and various other fields of the different item types.',
},
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
displayOptions: {
show: {
operation: [
'search',
],
resource: [
'file',
],
},
},
default: false,
description: 'If all results should be returned or only up to a given limit.',
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
displayOptions: {
show: {
operation: [
'search',
],
resource: [
'file',
],
returnAll: [
false,
],
},
},
typeOptions: {
minValue: 1,
maxValue: 500,
},
default: 100,
description: 'How many results to return.',
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
displayOptions: {
show: {
operation: [
'search',
],
resource: [
'file',
],
},
},
default: {},
options: [
{
displayName: 'Content Types',
name: 'contet_types',
type: 'string',
default: '',
description: `Limits search results to items with the given content types. Content types are defined as a comma separated lists of Box recognized content types.`,
},
{
displayName: 'Created At Range',
name: 'createdRangeUi',
type: 'fixedCollection',
typeOptions: {
multipleValues: false,
},
placeholder: 'Add Range',
default: {},
options: [
{
displayName: 'Range',
name: 'createdRangeValuesUi',
values: [
{
displayName: 'From',
name: 'from',
type: 'dateTime',
default: '',
},
{
displayName: 'To',
name: 'to',
type: 'dateTime',
default: '',
},
],
},
],
},
{
displayName: 'Direction',
name: 'direction',
type: 'options',
options: [
{
name: 'ASC',
value: 'ASC',
},
{
name: 'DESC',
value: 'DESC',
},
],
default: '',
description: 'Defines the direction in which search results are ordered. Default value is DESC.',
},
{
displayName: 'Fields',
name: 'fields',
type: 'string',
default: '',
description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response.',
},
{
displayName: 'File Extensions',
name: 'file_extensions',
type: 'string',
default: '',
placeholder: 'pdf,png,gif',
description: 'Limits search results to a comma-separated list of file extensions.',
},
{
displayName: 'Folder IDs',
name: 'ancestor_folder_ids',
type: 'string',
default: '',
description: `Limits search results to items within the given list of folders. Folders are defined as a comma separated lists of folder IDs.`,
},
{
displayName: 'Scope',
name: 'scope',
type: 'options',
options: [
{
name: 'User Content',
value: 'user_content',
},
{
name: 'Enterprise Content',
value: 'enterprise_content',
},
],
default: '',
description: 'Limits search results to a user scope.',
},
{
displayName: 'Size Range',
name: 'size_range',
type: 'string',
default: '',
placeholder: '1000000,5000000',
description: `Limits search results to items within a given file size range. File size ranges are defined as comma separated byte sizes.`,
},
{
displayName: 'Sort',
name: 'sort',
type: 'options',
options: [
{
name: 'Relevance',
value: 'relevance',
},
{
name: 'Modified At',
value: 'modified_at',
},
],
default: 'relevance',
description: 'returns the results ordered in descending order by date at which the item was last modified.',
},
{
displayName: 'Trash Content',
name: 'trash_content',
type: 'options',
options: [
{
name: 'Non Trashed Only',
value: 'non_trashed_only',
},
{
name: 'Trashed Only',
value: 'trashed_only',
},
],
default: 'non_trashed_only',
description: 'Controls if search results include the trash.',
},
{
displayName: 'Update At Range',
name: 'updatedRangeUi',
type: 'fixedCollection',
typeOptions: {
multipleValues: false,
},
placeholder: 'Add Range',
default: {},
options: [
{
displayName: 'Range',
name: 'updatedRangeValuesUi',
values: [
{
displayName: 'From',
name: 'from',
type: 'dateTime',
default: '',
},
{
displayName: 'To',
name: 'to',
type: 'dateTime',
default: '',
},
],
},
],
},
{
displayName: 'User IDs',
name: 'owner_user_ids',
type: 'string',
default: '',
description: `Limits search results to items owned by the given list of owners. Owners are defined as a comma separated list of user IDs.`,
},
],
},
/* -------------------------------------------------------------------------- */
/* file:share */
/* -------------------------------------------------------------------------- */
{
displayName: 'File ID',
name: 'fileId',
type: 'string',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
},
},
default: '',
description: 'The ID of the file to share.',
},
{
displayName: 'Accessible By',
name: 'accessibleBy',
type: 'options',
options: [
{
name: 'Group',
value: 'group',
},
{
name: 'User',
value: 'user',
},
],
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
},
},
default: '',
description: 'The type of object the file will be shared with.',
},
{
displayName: 'Use Email',
name: 'useEmail',
type: 'boolean',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
accessibleBy: [
'user',
],
},
},
default: true,
description: 'Whether identify the user by email or ID.',
},
{
displayName: 'Email',
name: 'email',
type: 'string',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
useEmail: [
true,
],
accessibleBy: [
'user',
],
},
},
default: '',
description: `The user's email address to share the file with.`,
},
{
displayName: 'User ID',
name: 'userId',
type: 'string',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
useEmail: [
false,
],
accessibleBy: [
'user',
],
},
},
default: '',
description: `The user's ID to share the file with.`,
},
{
displayName: 'Group ID',
name: 'groupId',
type: 'string',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
accessibleBy: [
'group',
],
},
},
default: '',
description: `The group's ID to share the file with.`,
},
{
displayName: 'Role',
name: 'role',
type: 'options',
options: [
{
name: 'Co-Owner',
value: 'coOwner',
description: 'A Co-owner has all of functional read/write access that an editor does',
},
{
name: 'Editor',
value: 'editor',
description: 'An editor has full read/write access to a folder or file',
},
{
name: 'Previewer',
value: 'previewer',
description: 'A previewer has limited read access',
},
{
name: 'Previewer Uploader',
value: 'previewerUploader',
description: 'This access level is a combination of Previewer and Uploader',
},
{
name: 'Uploader',
value: 'uploader',
description: 'An uploader has limited write access',
},
{
name: 'Viewer',
value: 'viewer',
description: 'A viewer has read access to a folder or file',
},
{
name: 'Viewer Uploader',
value: 'viewerUploader',
description: 'This access level is a combination of Viewer and Uploader',
},
],
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
},
},
default: 'editor',
description: 'The level of access granted.',
},
{
displayName: 'Options',
name: 'options',
type: 'collection',
placeholder: 'Add Option',
displayOptions: {
show: {
operation: [
'share',
],
resource: [
'file',
],
},
},
default: {},
options: [
{
displayName: 'Can View Path',
name: 'can_view_path',
type: 'boolean',
default: false,
description: `Whether the invited users can see the entire parent path to the associated folder. The user will not gain privileges in any parent folder and therefore cannot see content the user is not collaborated on.`,
},
{
displayName: 'Expires At',
name: 'expires_at',
type: 'dateTime',
default: '',
description: 'Set the expiration date for the collaboration. At this date, the collaboration will be automatically removed from the item.',
},
{
displayName: 'Fields',
name: 'fields',
type: 'string',
default: '',
description: 'A comma-separated list of attributes to include in the response. This can be used to request fields that are not normally returned in a standard response.',
},
{
displayName: 'Notify',
name: 'notify',
type: 'boolean',
default: false,
description: 'Whether if users should receive email notification for the action performed.',
},
],
},
/* -------------------------------------------------------------------------- */
/* file:upload */
/* -------------------------------------------------------------------------- */
{
displayName: 'File Name',
name: 'fileName',
type: 'string',
placeholder: 'photo.png',
displayOptions: {
show: {
operation: [
'upload',
],
resource: [
'file',
],
},
},
default: '',
description: 'The name the file should be saved as.',
},
{
displayName: 'Binary Data',
name: 'binaryData',
type: 'boolean',
default: false,
required: true,
displayOptions: {
show: {
operation: [
'upload',
],
resource: [
'file',
],
},
},
description: 'If the data to upload should be taken from binary field.',
},
{
displayName: 'File Content',
name: 'fileContent',
type: 'string',
default: '',
required: true,
displayOptions: {
show: {
binaryData: [
false,
],
operation: [
'upload',
],
resource: [
'file',
],
},
},
description: 'The text content of the file.',
},
{
displayName: 'Binary Property',
name: 'binaryPropertyName',
type: 'string',
default: 'data',
required: true,
displayOptions: {
show: {
binaryData: [
true,
],
operation: [
'upload',
],
resource: [
'file',
],
},
},
description: 'Name of the binary property which contains the data for the file.',
},
{
displayName: 'Parent ID',
name: 'parentId',
type: 'string',
displayOptions: {
show: {
operation: [
'upload',
],
resource: [
'file',
],
},
},
default: '',
description: 'ID of the parent folder that will contain the file. If not it will be uploaded to the root folder',
},
]; | the_stack |
//typescript declarations
declare var MarkerClusterer: any;
declare var MarkerWithLabel: any;
declare var plugin: any;
interface MVCObject {
visualRefresh: any;
}
module google.maps {
var visualRefresh: any;
}
function OCM_CommonUI() {
this.enablePOIMap = true;
if (typeof OCM !== 'undefined') {
if (typeof OCM.Mapping !== 'undefined') {
this.mappingManager = new OCM.Mapping();
}
}
this.isRunningUnderCordova = false;
this.uiLocalizationManager = new OCM.i18n();
}
OCM_CommonUI.prototype.getLocalisation = function (resourceKey, defaultValue, isTestMode) {
if (typeof localisation_dictionary != 'undefined' || isTestMode == true) {
return this.uiLocalizationManager.getTranslation(resourceKey, defaultValue, null, null);
} else {
//localisation not in use
if (isTestMode == true) {
return "[" + resourceKey + "]";
} else {
return defaultValue;
}
}
};
OCM_CommonUI.prototype.getTranslation = function (resourceKey, defaultValue, params, targetElement: HTMLElement) {
return this.uiLocalizationManager.getTranslation(resourceKey, defaultValue, params, targetElement);
};
OCM_CommonUI.prototype.applyLocalisation = function (isTestMode) {
return this.uiLocalizationManager.applyLocalisation(isTestMode);
};
OCM_CommonUI.prototype.fixJSONDate = function (val) {
if (val == null) return null;
if (val.indexOf("/") == 0) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(val);
val = new Date(parseFloat(results[1]));
} else {
val = new Date(val);
}
return val;
};
OCM_CommonUI.prototype.showPOIOnStaticMap = function (mapcanvasID, poi, includeMapLink) {
var mapCanvas = document.getElementById(mapcanvasID);
if (mapCanvas != null) {
var title = poi.AddressInfo.Title;
var lat = poi.AddressInfo.Latitude;
var lon = poi.AddressInfo.Longitude;
var width = 200;
var height = 200;
var mapImageURL = "https://maps.googleapis.com/maps/api/staticmap?key=AIzaSyASE98mCjV1bqG4u2AUHqftB8Vz3zr2sEg¢er=" + lat + "," + lon + "&zoom=14&size=" + width + "x" + height + "&maptype=roadmap&markers=color:blue%7Clabel:A%7C" + lat + "," + lon + "&sensor=false";
var mapHTML = "";
if (includeMapLink == true) {
mapHTML += "<div>" + this.formatMapLink(poi, "<div><img width=\"" + width + "\" height=\"" + height + "\" src=\"" + mapImageURL + "\" /></div>") + "</div>";
} else {
mapHTML += "<div><img width=\"" + width + "\" height=\"" + height + "\" src=\"" + mapImageURL + "\" /></div>";
}
mapCanvas.innerHTML = mapHTML;
}
};
OCM_CommonUI.prototype.showPOIOnMap = function (mapcanvasID, poi) {
var mapCanvas = document.getElementById(mapcanvasID);
if (mapCanvas != null) {
var title = poi.AddressInfo.Title;
var lat = poi.AddressInfo.Latitude;
var lon = poi.AddressInfo.Longitude;
//map item if possible:
var markerLatlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 14,
center: markerLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapCanvas, myOptions);
var marker = new google.maps.Marker({
position: markerLatlng,
map: map,
title: title
});
map.setCenter(markerLatlng);
google.maps.event.trigger(map, 'resize');
}
};
OCM_CommonUI.prototype.isMobileBrowser = function () {
var useragent = navigator.userAgent;
if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 || useragent.indexOf('Windows Phone') != -1) {
return true;
} else {
return false;
}
};
OCM_CommonUI.prototype.getMaxLevelOfPOI = function (poi) {
var level = 0;
if (poi.Connections != null) {
for (var c = 0; c < poi.Connections.length; c++) {
if (poi.Connections[c].Level != null && poi.Connections[c].Level.ID > level) {
level = poi.Connections[c].Level.ID;
}
}
}
if (level == 4) level = 2; //lvl 1&2
if (level > 4) level = 3; //lvl 2&3 etc
return level;
};
OCM_CommonUI.prototype.showPOIListOnMap = function (mapcanvasID, poiList, appcontext, anchorElement) {
var mapCanvas = document.getElementById(mapcanvasID);
if (mapCanvas != null) {
//if (this.isMobileBrowser()) {
mapCanvas.style.width = '90%';
mapCanvas.style.height = '80%';
//}
//create map
var mapOptions = {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var bounds = new google.maps.LatLngBounds();
//clear existing markers
if (this.ocm_markers != null) {
for (var i = 0; i < this.ocm_markers.length; i++) {
if (this.ocm_markers[i]) {
this.ocm_markers[i].setMap(null);
}
}
}
this.ocm_markers = new Array();
if (poiList != null) {
//render poi markers
for (var i = 0; i < poiList.length; i++) {
if (poiList[i].AddressInfo != null) {
if (poiList[i].AddressInfo.Latitude != null && poiList[i].AddressInfo.Longitude != null) {
var poi = poiList[i];
this.ocm_markers[i] = new google.maps.Marker({
position: new google.maps.LatLng(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude),
map: map,
icon: "https://openchargemap.org/api/widgets/map/icons/green-circle.png",
title: poi.AddressInfo.Title
});
this.ocm_markers[i].poi = poi;
google.maps.event.addListener(this.ocm_markers[i], 'click', function () {
appcontext.showDetailsView(anchorElement, this.poi);
});
bounds.extend(this.ocm_markers[i].position);
}
}
}
}
//include centre search location in bounds of map zoom
if (this.ocm_searchmarker != null) bounds.extend(this.ocm_searchmarker.position);
map.fitBounds(bounds);
}
};
///Begin Standard data formatting methods ///
OCM_CommonUI.prototype.formatMapLinkFromPosition = function (poi, searchLatitude, searchLongitude, distance, distanceunit) {
return '<a href="https://maps.google.com/maps?saddr=' + searchLatitude + ',' + searchLongitude + '&daddr=' + poi.AddressInfo.Latitude + ',' + poi.AddressInfo.Longitude + '">Map (' + Math.ceil(distance) + ' ' + distanceunit + ')</a>';
};
OCM_CommonUI.prototype.formatSystemWebLink = function (linkURL, linkTitle) {
return "<a href='#' onclick=\"window.open('" + linkURL + "', '_system');return false;\">" + linkTitle + "</a>";
};
OCM_CommonUI.prototype.formatMapLink = function (poi, linkContent) {
if (this.isRunningUnderCordova) {
if (device && device.platform == "WinCE") {
return this.formatSystemWebLink("maps:" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude, linkContent);
//return "<a target=\"_system\" data-role=\"button\" data-icon=\"grid\" href=\"maps:" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude + "\">" + linkContent + "</a>";
} else if (device && device.platform == "iOS") {
return this.formatSystemWebLink("https://maps.apple.com/?q=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude, linkContent);
//return "<a target=\"_system\" data-role=\"button\" data-icon=\"grid\" href=\"http://maps.apple.com/?q=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude + "\">" + linkContent + "</a>";
} else {
return this.formatSystemWebLink("https://maps.google.com/maps?q=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude, linkContent);
}
}
//default to google maps online link
return "<a target=\"_blank\" href=\"https://maps.google.com/maps?q=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude + "\">" + linkContent + "</a>";
};
OCM_CommonUI.prototype.formatURL = function (url, title) {
if (url == null || url == "") return "";
if (url.indexOf("http") == -1) url = "http://" + url;
return '<a target="_blank" href="' + url + '">' + (title != null ? title : url) + '</a>';
};
OCM_CommonUI.prototype.formatPOIAddress = function (poi) {
var output = "";
output = "" + this.formatTextField(poi.AddressInfo.AddressLine1) +
this.formatTextField(poi.AddressInfo.AddressLine2) +
this.formatTextField(poi.AddressInfo.Town) +
this.formatTextField(poi.AddressInfo.StateOrProvince) +
this.formatTextField(poi.AddressInfo.Postcode) +
(poi.AddressInfo.Country != null ? this.formatTextField(poi.AddressInfo.Country.Title) : "");
if (this.enablePOIMap == true) {
output += "<div id='info_map'></div>";
}
return output;
};
OCM_CommonUI.prototype.formatString = function (val) {
if (val == null) return "";
return val.toString();
};
OCM_CommonUI.prototype.formatTextField = function (val, label, newlineAfterLabel, paragraph, resourceKey) {
if (val == null || val == "" || val == undefined) return "";
var output = (label != null ? "<strong class='ocm-label' " + (resourceKey != null ? "data-localize='" + resourceKey + "' " : "") + ">" + label + "</strong>: " : "") + (newlineAfterLabel ? "<br/>" : "") + (val.toString().replace("\n", "<br/>")) + "<br/>";
if (paragraph == true) output = "<p>" + output + "</p>";
return output;
};
OCM_CommonUI.prototype.formatEmailAddress = function (email) {
if (email != undefined && email != null && email != "") {
return "<i class='icon-envelope'></i> <a href=\"mailto:" + email + "\">" + email + "</a><br/>";
} else {
return "";
}
};
OCM_CommonUI.prototype.formatPhone = function (phone, labeltitle) {
if (phone != undefined && phone != null && phone != "") {
if (labeltitle == null) labeltitle = "<i class='icon-phone'></i> ";
else labeltitle += ": ";
return labeltitle + "<a href=\"tel:" + phone + "\">" + phone + "</a><br/>";
} else {
return "";
}
};
OCM_CommonUI.prototype.formatPOIDetails = function (poi, fullDetailsMode) {
var dayInMilliseconds = 86400000;
var currentDate = new Date();
if (fullDetailsMode == null) fullDetailsMode = false;
var addressInfo = this.formatPOIAddress(poi, false);
var contactInfo = "";
if (poi.AddressInfo.Distance != null) {
var directionsUrl = "https://maps.google.com/maps?saddr=&daddr=" + poi.AddressInfo.Latitude + "," + poi.AddressInfo.Longitude;
contactInfo += "<strong id='addr_distance'><span data-localize='ocm.details.approxDistance'>Distance</span>: " + poi.AddressInfo.Distance.toFixed(1) + " " + (poi.AddressInfo.DistanceUnit == 2 ? "Miles" : "KM") + "</strong>";
contactInfo += " <br/><i class='icon-road'></i> " + this.formatSystemWebLink(directionsUrl, "Get Directions") + "<br/>";
}
contactInfo += this.formatPhone(poi.AddressInfo.ContactTelephone1);
contactInfo += this.formatPhone(poi.AddressInfo.ContactTelephone2);
contactInfo += this.formatEmailAddress(poi.AddressInfo.ContactEmail);
if (poi.AddressInfo.RelatedURL != null && poi.AddressInfo.RelatedURL != "") {
var displayUrl = poi.AddressInfo.RelatedURL;
//remove protocol from url
displayUrl = displayUrl.replace(/.*?:\/\//g, "");
//shorten url if over 40 characters
if (displayUrl.length > 40) displayUrl = displayUrl.substr(0, 40) + "..";
contactInfo += "<i class='icon-external-link'></i> " + this.formatURL(poi.AddressInfo.RelatedURL, "<span data-localize='ocm.details.addressRelatedURL'>" + displayUrl + "</span>");
}
var comments = this.formatTextField(poi.GeneralComments, "Comments", true, true, "ocm.details.generalComments") +
this.formatTextField(poi.AddressInfo.AccessComments, "Access", true, true, "ocm.details.accessComments");
var additionalInfo = "";
if (poi.NumberOfPoints != null) {
additionalInfo += this.formatTextField(poi.NumberOfPoints, "Number Of Points", false, false, "ocm.details.numberOfPoints");
}
if (poi.UsageType != null) {
additionalInfo += this.formatTextField(poi.UsageType.Title, "Usage", false, false, "ocm.details.usageType");
}
if (poi.UsageCost != null) {
additionalInfo += this.formatTextField(poi.UsageCost, "Usage Cost", false, false, "ocm.details.usageCost");
}
if (poi.OperatorInfo != null) {
if (poi.OperatorInfo.ID != 1) { //skip unknown operators
additionalInfo += this.formatTextField(poi.OperatorInfo.Title, "Operator", false, false, "ocm.details.operatorTitle");
if (poi.OperatorInfo.WebsiteURL != null) {
advancedInfo += this.formatTextField(this.formatURL(poi.OperatorInfo.WebsiteURL), "Operator Website", true, false, "ocm.details.operatorWebsite");
}
}
}
var equipmentInfo = "";
if (poi.StatusType != null) {
equipmentInfo += this.formatTextField(poi.StatusType.Title, "Status", false, false, "ocm.details.operationalStatus");
if (poi.DateLastStatusUpdate != null) {
equipmentInfo += this.formatTextField(Math.round(((<any>currentDate - <any>this.fixJSONDate(poi.DateLastStatusUpdate)) / dayInMilliseconds)) + " days ago", "Last Updated", false, false, "ocm.details.lastUpdated");
}
}
//output table of connection info
if (poi.Connections != null) {
if (poi.Connections.length > 0) {
equipmentInfo += "<table class='datatable'>";
equipmentInfo += "<tr><th data-localize='ocm.details.equipment.connectionType'>Connection</th><th data-localize='ocm.details.equipment.powerLevel'>Power Level</th><th data-localize='ocm.details.operationalStatus'>Status</th><th data-localize='ocm.details.equipment.quantity'>Qty</th></tr>";
for (var c = 0; c < poi.Connections.length; c++) {
var con = poi.Connections[c];
if (con.Amps == "") con.Amps = null;
if (con.Voltage == "") con.Voltage = null;
if (con.Quantity == "") con.Quantity = null;
if (con.PowerKW == "") con.PowerKW = null;
equipmentInfo += "<tr>" +
"<td>" + (con.ConnectionType != null ? con.ConnectionType.Title : "") + "</td>" +
"<td>" + (con.Level != null ? "<strong>" + con.Level.Title + "</strong><br/>" : "") +
(con.Amps != null ? this.formatString(con.Amps) + "A/ " : "") +
(con.Voltage != null ? this.formatString(con.Voltage) + "V/ " : "") +
(con.PowerKW != null ? this.formatString(con.PowerKW) + "kW <br/>" : "") +
(con.CurrentType != null ? con.CurrentType.Title : "") +
"</td>" +
"<td>" + (con.StatusType != null ? con.StatusType.Title : "-") + "</td>" +
"<td>" + (con.Quantity != null ? this.formatString(con.Quantity) : "1") + "</td>" +
"</tr>";
}
equipmentInfo += "</table>";
}
}
var advancedInfo = "";
advancedInfo += this.formatTextField("<a target='_blank' href='https://openchargemap.org/site/poi/details/" + poi.ID + "'>OCM-" + poi.ID + "</a>", "OpenChargeMap Ref", false, false, "ocm.details.refNumber");
if (poi.DataProvider != null) {
advancedInfo += this.formatTextField(poi.DataProvider.Title, "Data Provider", false, false, "ocm.details.dataProviderTitle");
if (poi.DataProvider.WebsiteURL != null) {
advancedInfo += this.formatTextField(this.formatURL(poi.DataProvider.WebsiteURL), "Website", false, false, "ocm.details.dataProviderWebsite");
}
}
var output = {
"address": addressInfo,
"contactInfo": contactInfo,
"additionalInfo": comments + additionalInfo + equipmentInfo,
"advancedInfo": advancedInfo
};
return output;
};
/// End Standard Data Formatting methods /// | the_stack |
import * as fs from "fs";
import * as should from "should";
import { nodesets } from "node-opcua-nodesets";
import {
EventFilter,
FilterOperator,
LiteralOperand,
ContentFilter,
SimpleAttributeOperand,
ElementOperand
} from "node-opcua-types";
import { coerceQualifiedName, AttributeIds } from "node-opcua-data-model";
import { coerceNodeId, resolveNodeId, NodeId } from "node-opcua-nodeid";
import { Variant, DataType } from "node-opcua-variant";
import {
AddressSpace,
extractEventFields,
UAObject,
SessionContext,
checkWhereClause,
RaiseEventData,
UAEventType,
UAVariable
} from "../..";
import { generateAddressSpace } from "../../nodeJS";
interface This extends Mocha.Suite {
variableWithAlarm: UAVariable;
setpointNodeNode: UAVariable;
addressSpace: AddressSpace;
source: UAObject;
green: UAObject;
}
describe("Testing extract EventField", function (this: Mocha.Suite) {
let addressSpace: AddressSpace;
let source: UAObject;
const test = this as This;
before(async () => {
addressSpace = AddressSpace.create();
addressSpace.registerNamespace("PRIVATE_NAMESPACE");
const xml_file = nodesets.standard;
fs.existsSync(xml_file).should.be.eql(true);
await generateAddressSpace(addressSpace, xml_file);
const namespace = addressSpace.getOwnNamespace();
addressSpace.installAlarmsAndConditionsService();
const green = namespace.addObject({
browseName: "Green",
eventNotifier: 0x1,
notifierOf: addressSpace.rootFolder.objects.server,
organizedBy: addressSpace.rootFolder.objects
});
source = namespace.addObject({
browseName: "Motor.RPM",
componentOf: green,
eventSourceOf: green
});
test.variableWithAlarm = namespace.addVariable({
browseName: "VariableWithLimit",
dataType: "Double",
propertyOf: source
});
test.setpointNodeNode = namespace.addVariable({
browseName: "SetPointValue",
dataType: "Double",
propertyOf: source
});
test.addressSpace = addressSpace;
test.source = source;
test.green = green;
});
after(() => {
addressSpace.dispose();
});
function createEventData(eventTypeName: string) {
const eventTypeNode = addressSpace.findNode(eventTypeName)! as UAEventType;
should.exist(eventTypeNode);
const data: RaiseEventData = {};
data.$eventDataSource = eventTypeNode;
data.sourceNode = {
dataType: DataType.NodeId,
value: test.source.nodeId
};
const eventData = addressSpace.constructEventData(eventTypeNode, data);
return eventData;
}
it("EVF1- EventFilter", () => {
const eventFilter = new EventFilter({
selectClauses /* SimpleAttributeOp[] */: [
{
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("Changes")],
typeDefinitionId: coerceNodeId("ns=0;i=2041")
},
{
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("EventType")],
typeDefinitionId: coerceNodeId("ns=0;i=2041")
},
{
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("SourceNode")],
typeDefinitionId: coerceNodeId("ns=0;i=2041")
}
],
whereClause: new ContentFilter({
elements /* ContentFilterElem[] */: [
{
filterOperator /* FilterOperator */: FilterOperator.OfType,
filterOperands /* ExtensionObject [] */: [
new LiteralOperand({
value: new Variant({
dataType: DataType.NodeId,
value: coerceNodeId("ns=0;i=2132")
})
})
]
}
]
})
});
const sessionContext = SessionContext.defaultContext;
const eventData = createEventData("EventQueueOverflowEventType");
const result = extractEventFields(sessionContext, eventFilter.selectClauses || [], eventData);
result[0].dataType.should.eql(DataType.Null);
result[1].dataType.should.eql(DataType.NodeId);
result[2].dataType.should.eql(DataType.NodeId);
result[1].value.toString().should.eql(resolveNodeId("EventQueueOverflowEventType").toString());
result[2].value.toString().should.eql(test.source.nodeId.toString());
});
it("EVF1b ", () => {
const selectClauses = [
new SimpleAttributeOperand({
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("EventType")]
})
];
const sessionContext = SessionContext.defaultContext;
const eventData = createEventData("EventQueueOverflowEventType");
const result = extractEventFields(sessionContext, selectClauses, eventData);
result[0].dataType.should.eql(DataType.NodeId);
result[0].value.toString().should.eql(resolveNodeId("EventQueueOverflowEventType").toString());
});
it("EVF2- check Where Clause OfType", () => {
const whereClause = new ContentFilter({
elements /* ContentFilterElem[] */: [
{
filterOperator /* FilterOperator */: FilterOperator.OfType,
filterOperands /* ExtensionObject [] */: [
new LiteralOperand({
value: new Variant({
dataType: DataType.NodeId,
value: resolveNodeId("SystemEventType")
})
})
]
}
]
});
const sessionContext = SessionContext.defaultContext;
{
const eventData = createEventData("DeviceFailureEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData).should.eql(true);
}
{
const eventData = createEventData("SystemEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData).should.eql(true);
}
{
const eventData = createEventData("EventQueueOverflowEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData).should.eql(false);
}
});
it("EVF3- check Where Clause InList OfType", () => {
const whereClause = new ContentFilter({
elements /* ContentFilterElem[] */: [
{
filterOperator /* FilterOperator */: FilterOperator.InList,
filterOperands /* ExtensionObject [] */: [
new SimpleAttributeOperand({
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("EventType")],
typeDefinitionId: NodeId.nullNodeId
}),
new LiteralOperand({
value: new Variant({
dataType: DataType.NodeId,
value: resolveNodeId("AuditCertificateExpiredEventType")
})
}),
new LiteralOperand({
value: new Variant({
dataType: DataType.NodeId,
value: resolveNodeId("AuditHistoryDeleteEventType")
})
})
]
}
]
});
const sessionContext = SessionContext.defaultContext;
const op = new SimpleAttributeOperand({
attributeId: AttributeIds.Value,
browsePath: [coerceQualifiedName("EventType")],
typeDefinitionId: NodeId.nullNodeId
});
{
const eventData1 = createEventData("AuditCertificateExpiredEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(true);
}
{
const eventData1 = createEventData("AuditHistoryDeleteEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(true);
}
{
const eventData1 = createEventData("DeviceFailureEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(false);
}
{
const eventData1 = createEventData("SystemEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(false);
}
{
const eventData1 = createEventData("EventQueueOverflowEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(false);
}
});
it("EVF4- check WhereClause with Not Operand #810", () => {
const whereClause = new ContentFilter({
elements /* ContentFilterElem[] */: [
{
/*0*/ filterOperator /* FilterOperator */: FilterOperator.Not,
filterOperands /* ExtensionObject [] */: [
new ElementOperand({
index /* UInt32*/: 1
})
]
},
{
filterOperator: FilterOperator.OfType,
filterOperands: [
new LiteralOperand({
value: new Variant({
dataType: DataType.NodeId,
value: resolveNodeId("GeneralModelChangeEventType") // (ns = 0; i=2133))
})
})
]
}
]
});
const sessionContext = SessionContext.defaultContext;
{
const eventData1 = createEventData("AuditCertificateExpiredEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(true);
}
{
const eventData1 = createEventData("GeneralModelChangeEventType");
checkWhereClause(addressSpace, sessionContext, whereClause, eventData1).should.eql(false);
}
});
}); | the_stack |
import ms from 'ms';
import fs from 'fs-extra';
import { isIP } from 'net';
import { join } from 'path';
const {
fetch,
sleep,
fixture,
testFixture,
testFixtureStdio,
validateResponseHeaders,
} = require('./utils.js');
test(
'[vercel dev] temporary directory listing',
testFixtureStdio(
'temporary-directory-listing',
async (_testPath: any, port: any) => {
const directory = fixture('temporary-directory-listing');
await fs.unlink(join(directory, 'index.txt')).catch(() => null);
await sleep(ms('20s'));
const firstResponse = await fetch(`http://localhost:${port}`);
validateResponseHeaders(firstResponse);
const body = await firstResponse.text();
console.log(body);
expect(firstResponse.status).toBe(404);
await fs.writeFile(join(directory, 'index.txt'), 'hello');
for (let i = 0; i < 20; i++) {
const response = await fetch(`http://localhost:${port}`);
validateResponseHeaders(response);
if (response.status === 200) {
const body = await response.text();
expect(body).toBe('hello');
}
await sleep(ms('1s'));
}
},
{ skipDeploy: true }
)
);
test('[vercel dev] add a `package.json` to trigger `@vercel/static-build`', async () => {
const directory = fixture('trigger-static-build');
await fs.unlink(join(directory, 'package.json')).catch(() => null);
await fs.unlink(join(directory, 'public', 'index.txt')).catch(() => null);
await fs.rmdir(join(directory, 'public')).catch(() => null);
const tester = testFixtureStdio(
'trigger-static-build',
async (_testPath: any, port: any) => {
{
const response = await fetch(`http://localhost:${port}`);
validateResponseHeaders(response);
const body = await response.text();
expect(body.trim()).toBe('hello:index.txt');
}
const rnd = Math.random().toString();
const pkg = {
private: true,
scripts: { build: `mkdir -p public && echo ${rnd} > public/index.txt` },
};
await fs.writeFile(join(directory, 'package.json'), JSON.stringify(pkg));
// Wait until file events have been processed
await sleep(ms('2s'));
{
const response = await fetch(`http://localhost:${port}`);
validateResponseHeaders(response);
const body = await response.text();
expect(body.trim()).toBe(rnd);
}
},
{ skipDeploy: true }
);
await tester();
});
test('[vercel dev] no build matches warning', async () => {
const directory = fixture('no-build-matches');
const { dev } = await testFixture(directory, {
stdio: ['ignore', 'pipe', 'pipe'],
});
try {
// start `vercel dev` detached in child_process
dev.unref();
dev.stderr.setEncoding('utf8');
await new Promise<void>(resolve => {
dev.stderr.on('data', (str: string) => {
if (str.includes('did not match any source files')) {
resolve();
}
});
});
} finally {
dev.kill('SIGTERM');
}
});
test(
'[vercel dev] do not recursivly check the path',
testFixtureStdio('handle-filesystem-missing', async (testPath: any) => {
await testPath(200, '/', /hello/m);
await testPath(404, '/favicon.txt');
})
);
test('[vercel dev] render warning for empty cwd dir', async () => {
const directory = fixture('empty');
const { dev, port } = await testFixture(directory, {
stdio: ['ignore', 'pipe', 'pipe'],
});
try {
dev.unref();
// Monitor `stderr` for the warning
dev.stderr.setEncoding('utf8');
const msg = 'There are no files inside your deployment.';
await new Promise<void>(resolve => {
dev.stderr.on('data', (str: string) => {
if (str.includes(msg)) {
resolve();
}
});
});
// Issue a request to ensure a 404 response
await sleep(ms('3s'));
const response = await fetch(`http://localhost:${port}`);
validateResponseHeaders(response);
expect(response.status).toBe(404);
} finally {
dev.kill('SIGTERM');
}
});
test('[vercel dev] do not rebuild for changes in the output directory', async () => {
const directory = fixture('output-is-source');
const { dev, port } = await testFixture(directory, {
stdio: ['ignore', 'pipe', 'pipe'],
});
try {
dev.unref();
let stderr: any = [];
const start = Date.now();
dev.stderr.on('data', (str: any) => stderr.push(str));
while (stderr.join('').includes('Ready') === false) {
await sleep(ms('3s'));
if (Date.now() - start > ms('30s')) {
console.log('stderr:', stderr.join(''));
break;
}
}
const resp1 = await fetch(`http://localhost:${port}`);
const text1 = await resp1.text();
expect(text1.trim()).toBe('hello first');
await fs.writeFile(join(directory, 'public', 'index.html'), 'hello second');
await sleep(ms('3s'));
const resp2 = await fetch(`http://localhost:${port}`);
const text2 = await resp2.text();
expect(text2.trim()).toBe('hello second');
} finally {
dev.kill('SIGTERM');
}
});
test(
'[vercel dev] 25-nextjs-src-dir',
testFixtureStdio('25-nextjs-src-dir', async (testPath: any) => {
await testPath(200, '/', /Next.js \+ Node.js API/m);
})
);
test(
'[vercel dev] 27-zero-config-env',
testFixtureStdio(
'27-zero-config-env',
async (testPath: any) => {
await testPath(200, '/api/print', /build-and-runtime/m);
await testPath(200, '/', /build-and-runtime/m);
},
{ skipDeploy: true }
)
);
test(
'[vercel dev] 28-vercel-json-and-ignore',
testFixtureStdio('28-vercel-json-and-ignore', async (testPath: any) => {
await testPath(200, '/api/one', 'One');
await testPath(404, '/api/two');
await testPath(200, '/api/three', 'One');
})
);
test(
'[vercel dev] 30-next-image-optimization',
testFixtureStdio('30-next-image-optimization', async (testPath: any) => {
const toUrl = (url: any, w: any, q: any) => {
// @ts-ignore
const query = new URLSearchParams();
query.append('url', url);
query.append('w', w);
query.append('q', q);
return `/_next/image?${query}`;
};
const expectHeader = (accept: any) => ({
'content-type': accept,
'cache-control': 'public, max-age=0, must-revalidate',
});
const fetchOpts = (accept: any) => ({ method: 'GET', headers: { accept } });
await testPath(200, '/', /Home Page/m);
await testPath(
200,
toUrl('/test.jpg', 64, 100),
null,
expectHeader('image/webp'),
fetchOpts('image/webp')
);
await testPath(
200,
toUrl('/test.png', 64, 90),
null,
expectHeader('image/webp'),
fetchOpts('image/webp')
);
/*
* Disabled gif in https://github.com/vercel/next.js/pull/22253
* Eventually we should enable again when `next dev` supports it
await testPath(
200,
toUrl('/test.gif', 64, 80),
null,
expectHeader('image/webp'),
fetchOpts('image/webp')
);
*/
/*
* Disabled svg in https://github.com/vercel/next.js/pull/34431
* We can test for 400 status since config option is not enabled.
*/
await testPath(400, toUrl('/test.svg', 64, 70));
/* Disabled bmp because `next dev` bypasses
* and production will convert. Eventually
* we can enable once `next dev` supports it.
await testPath(
200,
toUrl('/test.bmp', 64, 50),
null,
expectHeader('image/bmp'),
fetchOpts('image/webp')
);
*/
// animated gif should bypass: serve as-is
await testPath(
200,
toUrl('/animated.gif', 64, 60),
null,
expectHeader('image/gif'),
fetchOpts('image/webp')
);
})
);
test(
'[vercel dev] 40-mixed-modules',
testFixtureStdio('40-mixed-modules', async (testPath: any) => {
await testPath(200, '/entrypoint.js', 'mixed-modules:js');
await testPath(200, '/entrypoint.mjs', 'mixed-modules:mjs');
await testPath(200, '/entrypoint.ts', 'mixed-modules:ts');
await testPath(
200,
'/type-module-package-json/auto.js',
'mixed-modules:auto'
);
await testPath(
200,
'/type-module-package-json/nested/also.js',
'mixed-modules:also'
);
})
);
test(
'[vercel dev] 41-tsconfig-jsx',
testFixtureStdio('41-tsconfig-jsx', async (testPath: any) => {
await testPath(200, '/', /Solid App/m);
await testPath(200, '/api/test', 'working');
})
);
test(
'[vercel dev] 42-dynamic-esm-ext',
testFixtureStdio('42-dynamic-esm-ext', async (testPath: any) => {
await testPath(200, '/api/cjs/foo', 'found .js');
await testPath(200, '/api/esm/foo', 'found .mjs');
})
);
test(
'[vercel dev] Use `@vercel/python` with Flask requirements.txt',
testFixtureStdio('python-flask', async (testPath: any) => {
const name = 'Alice';
const year = new Date().getFullYear();
await testPath(200, `/api/user?name=${name}`, new RegExp(`Hello ${name}`));
await testPath(200, `/api/date`, new RegExp(`Current date is ${year}`));
await testPath(200, `/api/date.py`, new RegExp(`Current date is ${year}`));
await testPath(200, `/api/headers`, (body: any, res: any) => {
// @ts-ignore
const { host } = new URL(res.url);
expect(body).toBe(host);
});
})
);
test(
'[vercel dev] Use custom runtime from the "functions" property',
testFixtureStdio('custom-runtime', async (testPath: any) => {
await testPath(200, `/api/user`, /Hello, from Bash!/m);
await testPath(200, `/api/user.sh`, /Hello, from Bash!/m);
})
);
test(
'[vercel dev] Should work with nested `tsconfig.json` files',
testFixtureStdio('nested-tsconfig', async (testPath: any) => {
await testPath(200, `/`, /Nested tsconfig.json test page/);
await testPath(200, `/api`, 'Nested `tsconfig.json` API endpoint');
})
);
test(
'[vercel dev] Should force `tsc` option "module: commonjs" for `startDevServer()`',
testFixtureStdio('force-module-commonjs', async (testPath: any) => {
await testPath(200, `/`, /Force "module: commonjs" test page/);
await testPath(
200,
`/api`,
'Force "module: commonjs" JavaScript with ES Modules API endpoint'
);
await testPath(
200,
`/api/ts`,
'Force "module: commonjs" TypeScript API endpoint'
);
})
);
test(
'[vercel dev] should prioritize index.html over other file named index.*',
testFixtureStdio('index-html-priority', async (testPath: any) => {
await testPath(200, '/', 'This is index.html');
await testPath(200, '/index.css', 'This is index.css');
})
);
test(
'[vercel dev] Should support `*.go` API serverless functions',
testFixtureStdio('go', async (testPath: any) => {
await testPath(200, `/api`, 'This is the index page');
await testPath(200, `/api/index`, 'This is the index page');
await testPath(200, `/api/index.go`, 'This is the index page');
await testPath(200, `/api/another`, 'This is another page');
await testPath(200, '/api/another.go', 'This is another page');
await testPath(200, `/api/foo`, 'Req Path: /api/foo');
await testPath(200, `/api/bar`, 'Req Path: /api/bar');
})
);
test(
'[vercel dev] Should set the `ts-node` "target" to match Node.js version',
testFixtureStdio('node-ts-node-target', async (testPath: any) => {
await testPath(200, `/api/subclass`, '{"ok":true}');
await testPath(
200,
`/api/array`,
'{"months":[1,2,3,4,5,6,7,8,9,10,11,12]}'
);
await testPath(200, `/api/dump`, (body: any, res: any, isDev: any) => {
// @ts-ignore
const { host } = new URL(res.url);
const { env, headers } = JSON.parse(body);
// Test that the API endpoint receives the Vercel proxy request headers
expect(headers['x-forwarded-host']).toBe(host);
expect(headers['x-vercel-deployment-url']).toBe(host);
expect(isIP(headers['x-real-ip'])).toBeTruthy();
expect(isIP(headers['x-forwarded-for'])).toBeTruthy();
expect(isIP(headers['x-vercel-forwarded-for'])).toBeTruthy();
// Test that the API endpoint has the Vercel platform env vars defined.
expect(env.NOW_REGION).toMatch(/^[a-z]{3}\d$/);
if (isDev) {
// Only dev is tested because in production these are opt-in.
expect(env.VERCEL_URL).toBe(host);
expect(env.VERCEL_REGION).toBe('dev1');
}
});
})
);
test(
'[vercel dev] Do not fail if `src` is missing',
testFixtureStdio('missing-src-property', async (testPath: any) => {
await testPath(200, '/', /hello:index.txt/m);
await testPath(404, '/i-do-not-exist');
})
); | the_stack |
import isEqual from "lodash/isEqual";
import { BigNumber } from "bignumber.js";
import { sameOp } from "./bridge/jsHelpers";
import type {
Operation,
OperationRaw,
Account,
AccountLike,
AccountRaw,
SubAccount,
SubAccountRaw,
BalanceHistoryCache,
BalanceHistoryRawMap,
} from "./types";
import {
fromAccountRaw,
fromOperationRaw,
fromSubAccountRaw,
fromTronResourcesRaw,
fromCosmosResourcesRaw,
fromBitcoinResourcesRaw,
fromBalanceHistoryRawMap,
fromAlgorandResourcesRaw,
fromPolkadotResourcesRaw,
fromTezosResourcesRaw,
fromElrondResourcesRaw,
fromCryptoOrgResourcesRaw,
} from "./account";
import consoleWarnExpectToEqual from "./consoleWarnExpectToEqual";
// aim to build operations with the minimal diff & call to libcore possible
export async function minimalOperationsBuilder<CO>(
existingOperations: Operation[],
coreOperations: CO[],
buildOp: (coreOperation: CO) => Promise<Operation | null | undefined>, // if defined, allows to merge some consecutive operation that have same hash
mergeSameHashOps?: (arg0: Operation[]) => Operation
): Promise<Operation[]> {
if (existingOperations.length === 0 && coreOperations.length === 0) {
return existingOperations;
}
const state: StepBuilderState = {
finished: false,
operations: [],
existingOps: existingOperations || [],
immutableOpCmpDoneOnce: false,
};
let operationWithSameHash: Operation[] = [];
for (let i = coreOperations.length - 1; i >= 0; i--) {
const coreOperation = coreOperations[i];
const op = await buildOp(coreOperation);
if (!op) continue; // some operation can be skipped by implementation
let newOp;
if (mergeSameHashOps) {
if (
operationWithSameHash.length === 0 ||
operationWithSameHash[0].hash === op.hash
) {
// we accumulate consecutive op of same hash in operationWithSameHash
operationWithSameHash.push(op);
continue;
}
// when the new op no longer matches the one accumulated,
// we can "release" one operation resulting of merging the accumulation
newOp = mergeSameHashOps(operationWithSameHash);
operationWithSameHash = [op];
} else {
// mergeSameHashOps not used = normal iteration
newOp = op;
}
stepBuilder(state, newOp, i);
if (state.finished) {
return state.operations;
}
}
if (mergeSameHashOps && operationWithSameHash.length) {
stepBuilder(state, mergeSameHashOps(operationWithSameHash), 0);
}
return state.operations;
}
export function minimalOperationsBuilderSync<CO>(
existingOperations: Operation[],
coreOperations: CO[],
buildOp: (coreOperation: CO) => Operation | null | undefined
): Operation[] {
if (existingOperations.length === 0 && coreOperations.length === 0) {
return existingOperations;
}
const state: StepBuilderState = {
finished: false,
operations: [],
existingOps: existingOperations || [],
immutableOpCmpDoneOnce: false,
};
for (let i = coreOperations.length - 1; i >= 0; i--) {
const coreOperation = coreOperations[i];
const newOp = buildOp(coreOperation);
if (!newOp) continue;
stepBuilder(state, newOp, i);
if (state.finished) {
return state.operations;
}
}
return state.operations;
}
const shouldRefreshBalanceHistoryCache = (
balanceHistoryCache: BalanceHistoryCache,
account: AccountLike
): boolean => {
const oldH = account.balanceHistoryCache.HOUR;
const newH = balanceHistoryCache.HOUR;
if (oldH.latestDate !== newH.latestDate) return true; // date have changed, need to refresh the array
if (oldH.balances.length !== newH.balances.length) return true; // balances length changes (new ops for instance)
const length = newH.balances.length;
if (length === 0) return false;
if (oldH.balances[length - 1] !== newH.balances[length - 1]) return true; // latest datapoint changes.
return false;
};
// FIXME DEPRECATED post portfolio v2
const shouldRefreshBalanceHistory = (
balanceHistory: BalanceHistoryRawMap,
account: Account
): boolean => {
const { week } = balanceHistory;
const accountWeek = account.balanceHistory && account.balanceHistory.week;
if (!week || !accountWeek) return true; // there is no week yet || there were no balance history yet
const [firstDate] = week[0];
const [, lastValue] = week[week.length - 1];
const { date: firstAccountDate } = accountWeek[0];
const { value: lastAccountValue } = accountWeek[accountWeek.length - 1];
const isSameDate = firstDate === firstAccountDate.toISOString();
return (
!isSameDate || // start date of the range has changed
lastValue !== lastAccountValue.toString() || // final balance has changed
week.length !== accountWeek.length // number of endpoints has changed
);
};
function shouldRefreshBitcoinResources(
updatedRaw: AccountRaw,
account: Account
) {
if (!updatedRaw.bitcoinResources) return false;
if (!account.bitcoinResources) return true;
if (updatedRaw.blockHeight !== account.blockHeight) return true;
if (updatedRaw.operations.length !== account.operations.length) return true;
const { bitcoinResources: existing } = account;
const { bitcoinResources: raw } = updatedRaw;
// FIXME Need more typing in wallet-btc to have a meaningful comparison
//if (!isEqual(raw.walletAccount?.xpub?.data, existing.walletAccount?.xpub?.data)) return true;
return raw.utxos.length !== existing.utxos.length;
}
export function patchAccount(
account: Account,
updatedRaw: AccountRaw
): Account {
// id can change after a sync typically if changing the version or filling more info. in that case we consider all changes.
if (account.id !== updatedRaw.id) return fromAccountRaw(updatedRaw);
let subAccounts;
if (updatedRaw.subAccounts) {
const existingSubAccounts = account.subAccounts || [];
let subAccountsChanged =
updatedRaw.subAccounts.length !== existingSubAccounts.length;
subAccounts = updatedRaw.subAccounts.map((ta) => {
const existing = existingSubAccounts.find((t) => t.id === ta.id);
const patched = patchSubAccount(existing, ta);
if (patched !== existing) {
subAccountsChanged = true;
}
return patched;
});
if (!subAccountsChanged) {
subAccounts = existingSubAccounts;
}
}
const operations = patchOperations(
account.operations,
updatedRaw.operations,
updatedRaw.id,
subAccounts
);
const pendingOperations = patchOperations(
account.pendingOperations,
updatedRaw.pendingOperations,
updatedRaw.id,
subAccounts
);
const next: Account = { ...account };
let changed = false;
if (subAccounts && account.subAccounts !== subAccounts) {
next.subAccounts = subAccounts;
changed = true;
}
if (account.operations !== operations) {
next.operations = operations;
changed = true;
}
if (
account.operationsCount !== updatedRaw.operationsCount &&
updatedRaw.operationsCount
) {
next.operationsCount = updatedRaw.operationsCount;
changed = true;
}
if (account.pendingOperations !== pendingOperations) {
next.pendingOperations = pendingOperations;
changed = true;
}
if (updatedRaw.balance !== account.balance.toString()) {
next.balance = new BigNumber(updatedRaw.balance);
changed = true;
}
// DEPRECATED post portfolio v2
const { balanceHistory } = updatedRaw;
if (balanceHistory) {
if (shouldRefreshBalanceHistory(balanceHistory, account)) {
next.balanceHistory = fromBalanceHistoryRawMap(balanceHistory);
changed = true;
}
} else if (next.balanceHistory) {
delete next.balanceHistory;
changed = true;
}
if (updatedRaw.spendableBalance !== account.spendableBalance.toString()) {
next.spendableBalance = new BigNumber(
updatedRaw.spendableBalance || updatedRaw.balance
);
changed = true;
}
if (updatedRaw.lastSyncDate !== account.lastSyncDate.toISOString()) {
next.lastSyncDate = new Date(updatedRaw.lastSyncDate);
changed = true;
}
if (
updatedRaw.creationDate &&
updatedRaw.creationDate !== account.creationDate.toISOString()
) {
next.creationDate = new Date(updatedRaw.creationDate);
changed = true;
}
if (account.freshAddress !== updatedRaw.freshAddress) {
next.freshAddress = updatedRaw.freshAddress;
changed = true;
}
if (account.freshAddressPath !== updatedRaw.freshAddressPath) {
next.freshAddressPath = updatedRaw.freshAddressPath;
changed = true;
}
if (account.blockHeight !== updatedRaw.blockHeight) {
next.blockHeight = updatedRaw.blockHeight;
changed = true;
}
if (account.syncHash !== updatedRaw.syncHash) {
next.syncHash = updatedRaw.syncHash;
changed = true;
}
const { balanceHistoryCache } = updatedRaw;
if (balanceHistoryCache) {
if (shouldRefreshBalanceHistoryCache(balanceHistoryCache, account)) {
next.balanceHistoryCache = balanceHistoryCache;
changed = true;
}
}
if (
updatedRaw.tronResources &&
// @ts-expect-error check if this is valid for deep equal check
account.tronResources !== updatedRaw.tronResources
) {
next.tronResources = fromTronResourcesRaw(updatedRaw.tronResources);
changed = true;
}
if (
updatedRaw.cosmosResources &&
// @ts-expect-error check if this is valid for deep equal check
account.cosmosResources !== updatedRaw.cosmosResources
) {
next.cosmosResources = fromCosmosResourcesRaw(updatedRaw.cosmosResources);
changed = true;
}
if (
updatedRaw.algorandResources &&
// @ts-expect-error check if this is valid for deep equal check
account.algorandResources !== updatedRaw.algorandResources
) {
next.algorandResources = fromAlgorandResourcesRaw(
updatedRaw.algorandResources
);
changed = true;
}
if (
updatedRaw.bitcoinResources &&
shouldRefreshBitcoinResources(updatedRaw, account)
) {
next.bitcoinResources = fromBitcoinResourcesRaw(
updatedRaw.bitcoinResources
);
changed = true;
}
if (
updatedRaw.polkadotResources &&
// @ts-expect-error check if this is valid for deep equal check
account.polkadotResources !== updatedRaw.polkadotResources
) {
next.polkadotResources = fromPolkadotResourcesRaw(
updatedRaw.polkadotResources
);
changed = true;
}
if (
updatedRaw.tezosResources &&
account.tezosResources !== updatedRaw.tezosResources
) {
next.tezosResources = fromTezosResourcesRaw(updatedRaw.tezosResources);
changed = true;
}
if (
updatedRaw.elrondResources &&
account.elrondResources !== updatedRaw.elrondResources
) {
next.elrondResources = fromElrondResourcesRaw(updatedRaw.elrondResources);
changed = true;
}
if (
updatedRaw.cryptoOrgResources &&
// @ts-expect-error types don't overlap ¯\_(ツ)_/¯
account.cryptoOrgResources !== updatedRaw.cryptoOrgResources
) {
next.cryptoOrgResources = fromCryptoOrgResourcesRaw(
updatedRaw.cryptoOrgResources
);
changed = true;
}
if (!changed) return account; // nothing changed at all
return next;
}
export function patchSubAccount(
account: SubAccount | null | undefined,
updatedRaw: SubAccountRaw
): SubAccount {
// id can change after a sync typically if changing the version or filling more info. in that case we consider all changes.
if (
!account ||
account.id !== updatedRaw.id ||
account.parentId !== updatedRaw.parentId
) {
return fromSubAccountRaw(updatedRaw);
}
const operations = patchOperations(
account.operations,
updatedRaw.operations,
updatedRaw.id,
undefined
);
const pendingOperations = patchOperations(
account.pendingOperations,
updatedRaw.pendingOperations,
updatedRaw.id,
undefined
);
// $FlowFixMe destructing union type?
const next: SubAccount = { ...account };
let changed = false;
if (
account.operationsCount !== updatedRaw.operationsCount &&
updatedRaw.operationsCount
) {
next.operationsCount = updatedRaw.operationsCount;
changed = true;
}
if (
updatedRaw.creationDate &&
updatedRaw.creationDate !== account.creationDate.toISOString()
) {
next.creationDate = new Date(updatedRaw.creationDate);
changed = true;
}
if (account.operations !== operations) {
next.operations = operations;
changed = true;
}
if (account.pendingOperations !== pendingOperations) {
next.pendingOperations = pendingOperations;
changed = true;
}
if (updatedRaw.balance !== account.balance.toString()) {
next.balance = new BigNumber(updatedRaw.balance);
changed = true;
}
if (
next.type === "TokenAccount" &&
account.type === "TokenAccount" &&
updatedRaw.type === "TokenAccountRaw"
) {
if (updatedRaw.spendableBalance !== account.spendableBalance.toString()) {
next.spendableBalance = new BigNumber(
updatedRaw.spendableBalance || updatedRaw.balance
);
changed = true;
}
if (updatedRaw.compoundBalance !== account.compoundBalance?.toString()) {
next.compoundBalance = updatedRaw.compoundBalance
? new BigNumber(updatedRaw.compoundBalance)
: undefined;
changed = true;
}
if (
updatedRaw.approvals &&
!isEqual(updatedRaw.approvals, account.approvals)
) {
next.approvals = updatedRaw.approvals;
changed = true;
}
}
const { balanceHistoryCache } = updatedRaw;
if (balanceHistoryCache) {
if (shouldRefreshBalanceHistoryCache(balanceHistoryCache, account)) {
next.balanceHistoryCache = balanceHistoryCache;
changed = true;
}
}
if (!changed) return account; // nothing changed at all
return next;
}
export function patchOperations(
operations: Operation[],
updated: OperationRaw[],
accountId: string,
subAccounts: SubAccount[] | null | undefined
): Operation[] {
return minimalOperationsBuilderSync(
operations,
updated.slice(0).reverse(),
(raw) => fromOperationRaw(raw, accountId, subAccounts)
);
}
function findExistingOp(ops, op) {
return ops.find((o) => o.id === op.id);
}
type StepBuilderState = {
operations: Operation[];
existingOps: Operation[];
immutableOpCmpDoneOnce: boolean;
finished: boolean;
};
// This is one step of the logic of minimalOperationsBuilder
// it implements an heuristic to skip prematurely the operations loop
// as soon as we find an existing operation that matches newOp
function stepBuilder(state, newOp, i) {
const existingOp = findExistingOp(state.existingOps, newOp);
if (existingOp && !state.immutableOpCmpDoneOnce) {
// an Operation is supposedly immutable.
if (existingOp.blockHeight !== newOp.blockHeight) {
// except for blockHeight that can temporarily be null
state.operations.push(newOp);
return;
} else {
state.immutableOpCmpDoneOnce = true;
// we still check the first existing op we meet...
if (!sameOp(existingOp, newOp)) {
// this implement a failsafe in case an op changes (when we fix bugs)
// trade-off: in such case, we assume all existingOps are to trash
consoleWarnExpectToEqual(
newOp,
existingOp,
"op mismatch. doing a full clear cache."
);
state.existingOps = [];
state.operations.push(newOp);
return;
}
}
}
if (existingOp) {
// as soon as we've found a first matching op in old op list,
const j = state.existingOps.indexOf(existingOp);
const rest = state.existingOps.slice(j);
if (rest.length > i + 1) {
// if libcore happen to have less ops that what we had,
// we actually need to continue because we don't know where hole will be,
// but we can keep existingOp
state.operations.push(existingOp);
} else {
// otherwise we stop the libcore iteration and continue with previous data
// and we're done on the iteration
if (state.operations.length === 0 && j === 0) {
// special case: we preserve the operations array as much as possible
state.operations = state.existingOps;
} else {
state.operations = state.operations.concat(rest);
}
state.finished = true;
return;
}
} else {
// otherwise it's a new op
state.operations.push(newOp);
}
} | the_stack |
import { ContractFunctionObj } from '@0x/base-contract';
import { BlockchainLifecycle, devConstants, web3Factory } from '@0x/dev-utils';
import { Web3ProviderEngine } from '@0x/subproviders';
import { BigNumber, providerUtils, StringRevertError } from '@0x/utils';
import { BlockParamLiteral, Web3Wrapper } from '@0x/web3-wrapper';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as ChaiBigNumber from 'chai-bignumber';
import * as dirtyChai from 'dirty-chai';
import * as Sinon from 'sinon';
import {
AbiGenDummyContract,
AbiGenDummyEvents,
AbiGenDummyWithdrawalEventArgs,
artifacts,
TestLibDummyContract,
} from '../src';
const txDefaults = {
from: devConstants.TESTRPC_FIRST_ADDRESS,
gas: devConstants.GAS_LIMIT,
};
const provider: Web3ProviderEngine = web3Factory.getRpcProvider({ shouldUseInProcessGanache: true });
const web3Wrapper = new Web3Wrapper(provider);
chai.config.includeStack = true;
chai.use(ChaiBigNumber());
chai.use(dirtyChai);
chai.use(chaiAsPromised);
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);
describe('AbiGenDummy Contract', () => {
let abiGenDummy: AbiGenDummyContract;
const runTestAsync = async (
contractMethodName: string,
contractMethod: ContractFunctionObj<any>,
input: any,
output: any,
) => {
const transaction = contractMethod.getABIEncodedTransactionData();
// try decoding transaction
const decodedInput = abiGenDummy.getABIDecodedTransactionData(contractMethodName, transaction);
expect(decodedInput, 'decoded input').to.be.deep.equal(input);
// execute transaction
const rawOutput = await web3Wrapper.callAsync({
to: abiGenDummy.address,
data: transaction,
});
// try decoding output
const decodedOutput = abiGenDummy.getABIDecodedReturnData(contractMethodName, rawOutput);
expect(decodedOutput, 'decoded output').to.be.deep.equal(output);
};
before(async () => {
providerUtils.startProviderEngine(provider);
abiGenDummy = await AbiGenDummyContract.deployFrom0xArtifactAsync(
artifacts.AbiGenDummy,
provider,
txDefaults,
artifacts,
);
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
describe('simplePureFunction', () => {
it('can get the function selector', () => {
const selector = abiGenDummy.simplePureFunction().selector;
expect(selector).to.equal('0xa3c2f6b6');
});
it('should call simplePureFunction', async () => {
const result = await abiGenDummy.simplePureFunction().callAsync();
expect(result).to.deep.equal(new BigNumber(1));
});
});
describe('simplePureFunctionWithInput', () => {
it('should call simplePureFunctionWithInput', async () => {
const result = await abiGenDummy.simplePureFunctionWithInput(new BigNumber(5)).callAsync();
expect(result).to.deep.equal(new BigNumber(6));
});
});
describe('pureFunctionWithConstant', () => {
it('should call pureFunctionWithConstant', async () => {
const result = await abiGenDummy.pureFunctionWithConstant().callAsync();
expect(result).to.deep.equal(new BigNumber(1234));
});
});
describe('simpleRevert', () => {
it('should call simpleRevert', async () => {
expect(abiGenDummy.simpleRevert().callAsync())
.to.eventually.be.rejectedWith(StringRevertError)
.and.deep.equal(new StringRevertError('SIMPLE_REVERT'));
});
});
describe('revertWithConstant', () => {
it('should call revertWithConstant', async () => {
expect(abiGenDummy.revertWithConstant().callAsync())
.to.eventually.be.rejectedWith(StringRevertError)
.and.deep.equal(new StringRevertError('REVERT_WITH_CONSTANT'));
});
});
describe('simpleRequire', () => {
it('should call simpleRequire', async () => {
expect(abiGenDummy.simpleRequire().callAsync())
.to.eventually.be.rejectedWith(StringRevertError)
.and.deep.equal(new StringRevertError('SIMPLE_REQUIRE'));
});
});
describe('requireWithConstant', () => {
it('should call requireWithConstant', async () => {
expect(abiGenDummy.requireWithConstant().callAsync())
.to.eventually.be.rejectedWith(StringRevertError)
.and.deep.equal(new StringRevertError('REQUIRE_WITH_CONSTANT'));
});
});
describe('struct handling', () => {
const sampleStruct = {
aDynamicArrayOfBytes: ['0x3078313233', '0x3078333231'],
anInteger: new BigNumber(5),
aString: 'abc',
someBytes: '0x3078313233',
};
it('should be able to handle struct output', async () => {
const result = await abiGenDummy.structOutput().callAsync();
expect(result).to.deep.equal(sampleStruct);
});
});
describe('ecrecoverFn', () => {
it('should implement ecrecover', async () => {
const signerAddress = devConstants.TESTRPC_FIRST_ADDRESS;
const message = '0x6927e990021d23b1eb7b8789f6a6feaf98fe104bb0cf8259421b79f9a34222b0';
const signature = await web3Wrapper.signMessageAsync(signerAddress, message);
// tslint:disable:custom-no-magic-numbers
const r = `0x${signature.slice(2, 66)}`;
const s = `0x${signature.slice(66, 130)}`;
const v = signature.slice(130, 132);
const v_decimal = parseInt(v, 16) + 27; // v: (0 or 1) => (27 or 28)
// tslint:enable:custom-no-magic-numbers
const result = await abiGenDummy.ecrecoverFn(message, v_decimal, r, s).callAsync();
expect(result).to.equal(signerAddress);
});
});
describe('event subscription', () => {
const indexFilterValues = {};
const emptyCallback = () => {}; // tslint:disable-line:no-empty
let stubs: Sinon.SinonStub[] = [];
afterEach(() => {
stubs.forEach(s => s.restore());
stubs = [];
});
it('should return a subscription token', done => {
const subscriptionToken = abiGenDummy.subscribe(
AbiGenDummyEvents.Withdrawal,
indexFilterValues,
emptyCallback,
);
expect(subscriptionToken).to.be.a('string');
done();
});
it('should allow unsubscribeAll to be called successfully after an error', done => {
abiGenDummy.subscribe(AbiGenDummyEvents.Withdrawal, indexFilterValues, emptyCallback);
stubs.push(
Sinon.stub((abiGenDummy as any)._web3Wrapper, 'getBlockIfExistsAsync').throws(
new Error('JSON RPC error'),
),
);
abiGenDummy.unsubscribeAll();
done();
});
});
describe('getLogsAsync', () => {
const blockRange = {
fromBlock: 0,
toBlock: BlockParamLiteral.Latest,
};
it('should get logs with decoded args emitted by EventWithStruct', async () => {
await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync();
const eventName = AbiGenDummyEvents.SimpleEvent;
const indexFilterValues = {};
const logs = await abiGenDummy.getLogsAsync(eventName, blockRange, indexFilterValues);
expect(logs).to.have.length(1);
expect(logs[0].event).to.be.equal(eventName);
});
it('should only get the logs with the correct event name', async () => {
await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync();
const differentEventName = AbiGenDummyEvents.Withdrawal;
const indexFilterValues = {};
const logs = await abiGenDummy.getLogsAsync(differentEventName, blockRange, indexFilterValues);
expect(logs).to.have.length(0);
});
it('should only get the logs with the correct indexed fields', async () => {
const [addressOne, addressTwo] = await web3Wrapper.getAvailableAddressesAsync();
await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressOne });
await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressTwo });
const eventName = AbiGenDummyEvents.Withdrawal;
const indexFilterValues = {
_owner: addressOne,
};
const logs = await abiGenDummy.getLogsAsync<AbiGenDummyWithdrawalEventArgs>(
eventName,
blockRange,
indexFilterValues,
);
expect(logs).to.have.length(1);
const args = logs[0].args;
expect(args._owner).to.be.equal(addressOne);
});
});
describe('withAddressInput', () => {
it('should normalize address inputs to lowercase', async () => {
const xAddress = devConstants.TESTRPC_FIRST_ADDRESS.toUpperCase();
const yAddress = devConstants.TESTRPC_FIRST_ADDRESS;
const a = new BigNumber(1);
const b = new BigNumber(2);
const c = new BigNumber(3);
const output = await abiGenDummy.withAddressInput(xAddress, a, b, yAddress, c).callAsync();
expect(output).to.equal(xAddress.toLowerCase());
});
});
describe('Encoding/Decoding Transaction Data and Return Values', () => {
it('should successfully encode/decode (no input / no output)', async () => {
const input = undefined;
const output = undefined;
await runTestAsync('noInputNoOutput', abiGenDummy.noInputNoOutput(), input, output);
});
it('should successfully encode/decode (no input / simple output)', async () => {
const input = undefined;
const output = new BigNumber(1991);
await runTestAsync('noInputSimpleOutput', abiGenDummy.noInputSimpleOutput(), input, output);
});
it('should successfully encode/decode (simple input / no output)', async () => {
const input = new BigNumber(1991);
const output = undefined;
await runTestAsync('simpleInputNoOutput', abiGenDummy.simpleInputNoOutput(input), input, output);
});
it('should successfully encode/decode (simple input / simple output)', async () => {
const input = new BigNumber(16);
const output = new BigNumber(1991);
await runTestAsync('simpleInputSimpleOutput', abiGenDummy.simpleInputSimpleOutput(input), input, output);
});
it('should successfully encode/decode (complex input / complex output)', async () => {
const input = {
foo: new BigNumber(1991),
bar: '0x1234',
car: 'zoom zoom',
};
const output = {
input,
lorem: '0x12345678',
ipsum: '0x87654321',
dolor: 'amet',
};
await runTestAsync(
'complexInputComplexOutput',
abiGenDummy.complexInputComplexOutput(input),
input,
output,
);
});
it('should successfully encode/decode (multi-input / multi-output)', async () => {
const input = [new BigNumber(1991), '0x1234', 'zoom zoom'];
const output = ['0x12345678', '0x87654321', 'amet'];
const transaction = abiGenDummy
.multiInputMultiOutput(input[0] as BigNumber, input[1] as string, input[2] as string)
.getABIEncodedTransactionData();
// try decoding transaction
const decodedInput = abiGenDummy.getABIDecodedTransactionData('multiInputMultiOutput', transaction);
expect(decodedInput, 'decoded input').to.be.deep.equal(input);
// execute transaction
const rawOutput = await web3Wrapper.callAsync({
to: abiGenDummy.address,
data: transaction,
});
// try decoding output
const decodedOutput = abiGenDummy.getABIDecodedReturnData('multiInputMultiOutput', rawOutput);
expect(decodedOutput, 'decoded output').to.be.deep.equal(output);
});
});
describe('awaitTransactionSuccessAsync', async () => {
it('should successfully call the non pure function', async () => {
expect(
abiGenDummy.nonPureMethod().awaitTransactionSuccessAsync({}, { pollingIntervalMs: 10, timeoutMs: 100 }),
).to.be.fulfilled('');
});
});
});
describe('Lib dummy contract', () => {
let libDummy: TestLibDummyContract;
before(async () => {
await blockchainLifecycle.startAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
});
before(async () => {
libDummy = await TestLibDummyContract.deployFrom0xArtifactAsync(
artifacts.TestLibDummy,
provider,
txDefaults,
artifacts,
);
});
beforeEach(async () => {
await blockchainLifecycle.startAsync();
});
afterEach(async () => {
await blockchainLifecycle.revertAsync();
});
it('should call a library function', async () => {
const result = await libDummy.publicAddOne(new BigNumber(1)).callAsync();
expect(result).to.deep.equal(new BigNumber(2));
});
it('should call a library function referencing a constant', async () => {
const result = await libDummy.publicAddConstant(new BigNumber(1)).callAsync();
expect(result).to.deep.equal(new BigNumber(1235));
});
}); | the_stack |
import http from 'http'
import logger from '@wdio/logger'
import { validateConfig } from '@wdio/config'
import { runFnInFiberContext } from '@wdio/utils'
import detectBackend from '../src/utils/detectBackend'
import { remote, multiremote, attach, RemoteOptions } from '../src'
jest.mock('../src/utils/detectBackend', () => jest.fn())
jest.mock('webdriver', () => {
const WebDriverModule = jest.requireActual('webdriver')
const client = {
sessionId: 'foobar-123',
addCommand: jest.fn(),
overwriteCommand: jest.fn(),
strategies: new Map(),
isWebDriver: true
}
const newSessionMock = jest.fn()
newSessionMock.mockReturnValue(new Promise((resolve) => resolve(client)))
newSessionMock.mockImplementation((params, cb) => {
let result = cb(client, params)
// @ts-ignore mock feature
if (params.test_multiremote) {
result.options = { logLevel: 'error' }
}
return result
})
const module = {
newSession: newSessionMock,
attachToSession: jest.fn().mockReturnValue(client),
DEFAULTS: WebDriverModule.DEFAULTS
}
return {
...module,
default: module
}
})
jest.mock('devtools', () => {
const DevTools = jest.requireActual('devtools').default
const client = { sessionId: 'foobar-123', isDevTools: true }
const newSessionMock = jest.fn()
newSessionMock.mockReturnValue(new Promise((resolve) => resolve(client)))
newSessionMock.mockImplementation((params, cb) => {
let result = cb(client, params)
// @ts-ignore mock feature
if (params.test_multiremote) {
result.options = { logLevel: 'error' }
}
return result
})
const module = {
newSession: newSessionMock,
attachToSession: jest.fn().mockReturnValue(client),
SUPPORTED_BROWSER: ['chrome'],
DEFAULTS: DevTools.DEFAULTS
}
return {
...module,
default: module
}
})
jest.mock('@wdio/config', () => {
const validateConfigMock = {
validateConfig: jest.fn((_, args) => args),
detectBackend: jest.fn(),
}
return validateConfigMock
})
jest.mock('http', () => {
let response = { statusCode: 404 }
const reqCall = { on: jest.fn(), end: jest.fn() }
return {
request: jest.fn().mockImplementation((url, cb) => {
cb(response)
return reqCall
}),
setResonse: (res) => (response = res),
Agent: jest.fn()
}
})
const WebDriver = require('webdriver').default
describe('WebdriverIO module interface', () => {
beforeEach(() => {
WebDriver.newSession.mockClear()
;(detectBackend as jest.Mock).mockClear()
})
it('should provide remote and multiremote access', () => {
expect(typeof remote).toBe('function')
expect(typeof attach).toBe('function')
expect(typeof multiremote).toBe('function')
})
describe('remote function', () => {
it('creates a webdriver session', async () => {
const options: RemoteOptions = {
automationProtocol: 'webdriver',
capabilities: {},
logLevel: 'trace'
}
const browser = await remote(options)
expect(browser.sessionId).toBe('foobar-123')
expect(detectBackend).toBeCalledWith(options)
expect(logger.setLogLevelsConfig).toBeCalledWith(undefined, 'trace')
})
it('allows to propagate a modifier', async () => {
const browser = await remote({
automationProtocol: 'webdriver',
capabilities: {}
}, (client) => {
client.foobar = 'barfoo'
return client
})
expect(browser.sessionId).toBe('foobar-123')
// @ts-ignore mock feature
expect(browser.foobar).toBe('barfoo')
})
it('should try to detect the backend', async () => {
await remote({
user: 'foo',
key: 'bar',
capabilities: {}
})
expect(detectBackend).toBeCalled()
})
it('should properly detect automation protocol', async () => {
const devtoolsBrowser = await remote({ capabilities: { browserName: 'chrome' } })
expect(devtoolsBrowser.isDevTools).toBe(true)
// @ts-ignore mock feature
http.setResonse({ statusCode: 200 })
const webdriverBrowser = await remote({ capabilities: { browserName: 'chrome' } })
// @ts-ignore mock feature
expect(webdriverBrowser.isWebDriver).toBe(true)
const anotherWebdriverBrowser = await remote({
path: '/',
capabilities: { browserName: 'chrome' }
})
// @ts-ignore mock feature
expect(anotherWebdriverBrowser.isWebDriver).toBe(true)
})
it('should not wrap custom commands into fiber context if used as standalone', async () => {
const browser = await remote({
automationProtocol: 'webdriver',
capabilities: {}
})
const customCommand = jest.fn()
browser.addCommand('someCommand', customCommand)
expect(runFnInFiberContext).toBeCalledTimes(0)
browser.overwriteCommand('deleteCookies', customCommand)
expect(runFnInFiberContext).toBeCalledTimes(0)
})
it('should wrap custom commands into fiber context', async () => {
const browser = await remote({
automationProtocol: 'webdriver',
capabilities: {},
framework: 'mocha'
})
const customCommand = jest.fn()
browser.addCommand('someCommand', customCommand)
expect(runFnInFiberContext).toBeCalledTimes(1)
browser.overwriteCommand('deleteCookies', customCommand)
expect(runFnInFiberContext).toBeCalledTimes(2)
})
it('should attach custom locators to the strategies', async () => {
const browser = await remote({
automationProtocol: 'webdriver',
capabilities: {}
})
const fakeFn = () => { return 'test' as any as HTMLElement }
browser.addLocatorStrategy('test-strat', fakeFn)
expect(browser.strategies.get('test-strat').toString()).toBe(fakeFn.toString())
})
it('throws error if trying to overwrite locator strategy', async () => {
// @ts-ignore uses expect-webdriverio
expect.assertions(1)
const browser = await remote({
automationProtocol: 'webdriver',
capabilities: {}
})
try {
const fakeFn = () => { return 'test' as any as HTMLElement }
browser.addLocatorStrategy('test-strat', fakeFn)
} catch (error) {
browser.strategies.delete('test-strat')
expect(error.message).toBe('Strategy test-strat already exists')
}
})
it('should properly create stub instance', async () => {
(validateConfig as jest.Mock).mockReturnValueOnce({
automationProtocol: './protocol-stub'
})
const browser = await remote({ capabilities: { browserName: 'chrome' } })
expect(browser.sessionId).toBeUndefined()
expect(browser.capabilities).toEqual({ browserName: 'chrome', chrome: true })
// @ts-ignore test types
expect(() => browser.addCommand()).toThrow()
// @ts-ignore test types
expect(() => browser.overwriteCommand()).toThrow()
const flags = {}
Object.entries(browser).forEach(([key, value]) => {
if (key.startsWith('is')) {
flags[key] = value
}
})
expect(flags).toEqual({
isAndroid: false,
isChrome: true,
isFirefox: false,
isIOS: false,
isMobile: false,
isSauce: false
})
})
})
describe('multiremote', () => {
it('register multiple clients', async () => {
await multiremote({
browserA: {
// @ts-ignore mock feature
test_multiremote: true,
automationProtocol: 'webdriver',
capabilities: { browserName: 'chrome' }
},
browserB: {
// @ts-ignore mock feature
test_multiremote: true,
automationProtocol: 'webdriver',
capabilities: { browserName: 'firefox' }
}
})
expect(WebDriver.attachToSession).toBeCalled()
expect(WebDriver.newSession.mock.calls).toHaveLength(2)
})
it('should attach custom locators to the strategies', async () => {
const driver = await multiremote({
browserA: {
// @ts-ignore mock feature
test_multiremote: true,
capabilities: { browserName: 'chrome' }
},
browserB: {
// @ts-ignore mock feature
test_multiremote: true,
capabilities: { browserName: 'firefox' }
}
})
const fakeFn = () => { return 'test' as any as HTMLElement }
driver.addLocatorStrategy('test-strat', fakeFn)
expect(driver.strategies.get('test-strat').toString()).toBe(fakeFn.toString())
})
it('throws error if trying to overwrite locator strategy', async () => {
// @ts-ignore uses expect-webdriverio
expect.assertions(1)
const driver = await multiremote({
// @ts-ignore mock feature
browserA: { test_multiremote: true, capabilities: { browserName: 'chrome' } },
// @ts-ignore mock feature
browserB: { test_multiremote: true, capabilities: { browserName: 'firefox' } }
})
try {
const fakeFn = () => { return 'test' as any as HTMLElement }
driver.addLocatorStrategy('test-strat', fakeFn)
} catch (error) {
driver.strategies.delete('test-strat')
expect(error.message).toBe('Strategy test-strat already exists')
}
})
})
describe('attach', () => {
it('attaches', async () => {
const browser = {
sessionId: 'foobar',
capabilities: {
browserName: 'chrome',
platformName: 'MacOS'
},
requestedCapabilities: {
browserName: 'chrome'
}
}
await attach(browser)
expect(WebDriver.attachToSession).toBeCalledTimes(1)
expect(WebDriver.attachToSession.mock.calls[0][0]).toMatchSnapshot()
})
})
afterEach(() => {
WebDriver.attachToSession.mockClear()
WebDriver.newSession.mockClear()
})
}) | the_stack |
import { CreateAnimData } from '../../animation/CreateAnimData';
import { Frame } from '../../textures/Frame';
import { IAnimation } from '../../animation/IAnimation';
import { IAnimationData } from '../../animation/IAnimationData';
import { IAnimationFrame } from '../../animation/IAnimationFrame';
import { IGameObject } from '../IGameObject';
import { Sprite } from '../sprite/Sprite';
import { Texture } from '../../textures/Texture';
export class AnimatedSprite extends Sprite
{
currentAnimation: IAnimation;
currentFrame: IAnimationFrame;
animData: IAnimationData;
hasStarted: boolean = false;
forward: boolean = true;
inReverse: boolean = false;
private accumulator: number = 0;
private nextTick: number = 0;
private delayCounter: number = 0;
private repeatCounter: number = 0;
private pendingRepeat: boolean = false;
private paused: boolean = false;
private wasPlaying: boolean = false;
private pendingStop: number = 0;
private pendingStopValue: number = 0;
constructor (x: number, y: number, texture: string | Texture | Frame, frame?: string | number | Frame)
{
super(x, y, texture, frame);
this.animData = CreateAnimData();
}
private handleStart (): void
{
if (this.animData.showOnStart)
{
this.visible = true;
}
this.setCurrentFrame(this.currentFrame);
this.hasStarted = true;
// this.emitEvents(Events.ANIMATION_START);
}
private handleRepeat (): void
{
this.pendingRepeat = false;
// this.emitEvents(Events.ANIMATION_REPEAT);
}
private handleStop (): void
{
this.pendingStop = 0;
this.animData.isPlaying = false;
// this.emitEvents(Events.ANIMATION_STOP);
}
private handleComplete (): void
{
this.pendingStop = 0;
this.animData.isPlaying = false;
if (this.animData.hideOnComplete)
{
this.visible = false;
}
// this.emitEvents(Events.ANIMATION_COMPLETE, Events.ANIMATION_COMPLETE_KEY);
}
reverse (): this
{
if (this.isPlaying)
{
this.inReverse = !this.inReverse;
this.forward = !this.forward;
}
return this;
}
getProgress (): number
{
const frame = this.currentFrame;
if (!frame)
{
return 0;
}
let p = frame.progress;
if (this.inReverse)
{
p *= -1;
}
return p;
}
stop (): this
{
this.pendingStop = 0;
this.animData.isPlaying = false;
if (this.currentAnimation)
{
this.handleStop();
}
return this;
}
update (delta: number, now: number): void
{
super.update(delta, now);
const data = this.animData;
const anim = this.currentAnimation;
if (!anim || !data.isPlaying || anim.paused)
{
return;
}
this.accumulator += delta * data.timeScale;
if (this.pendingStop === 1)
{
this.pendingStopValue -= delta;
if (this.pendingStopValue <= 0)
{
this.stop();
return;
}
}
if (!this.hasStarted)
{
if (this.accumulator >= this.delayCounter)
{
this.accumulator -= this.delayCounter;
this.handleStart();
}
}
else if (this.accumulator >= this.nextTick)
{
// Process one frame advance as standard
if (this.forward)
{
this.nextFrame();
}
else
{
this.prevFrame();
}
// And only do more if we're skipping frames and have time left
if (data.isPlaying && this.pendingStop === 0 && anim.skipMissedFrames && this.accumulator > this.nextTick)
{
let safetyNet = 0;
do
{
if (this.forward)
{
this.nextFrame();
}
else
{
this.prevFrame();
}
safetyNet++;
} while (data.isPlaying && this.accumulator > this.nextTick && safetyNet < 60);
}
}
}
nextFrame (): this
{
const frame = this.currentFrame;
const data = this.animData;
if (frame.isLast)
{
// We're at the end of the animation
// Yoyo? (happens before repeat)
if (data.yoyo)
{
this.handleYoyoFrame(false);
}
else if (this.repeatCounter > 0)
{
// Repeat (happens before complete)
if (this.inReverse && this.forward)
{
this.forward = false;
}
else
{
this.repeatAnimation();
}
}
else
{
this.complete();
}
}
else
{
this.setCurrentFrame(this.currentFrame.nextFrame);
this.getNextTick();
}
return this;
}
repeatAnimation (): this
{
if (this.pendingStop === 2)
{
if (this.pendingStopValue === 0)
{
return this.stop();
}
else
{
this.pendingStopValue--;
}
}
const data = this.animData;
if (data.repeatDelay > 0 && !this.pendingRepeat)
{
this.pendingRepeat = true;
this.accumulator -= this.nextTick;
this.nextTick += data.repeatDelay;
}
else
{
this.repeatCounter--;
if (this.forward)
{
this.setCurrentFrame(this.currentFrame.nextFrame);
}
else
{
this.setCurrentFrame(this.currentFrame.prevFrame);
}
if (this.isPlaying)
{
this.getNextTick();
this.handleRepeat();
}
}
}
setCurrentFrame (animFrame: IAnimationFrame): void
{
this.currentFrame = animFrame;
this.setTexture(animFrame.texture, animFrame.frame);
}
getNextTick (): void
{
this.accumulator -= this.nextTick;
this.nextTick = this.currentAnimation.msPerFrame + this.currentFrame.duration;
}
handleYoyoFrame (isReverse: boolean = false): void
{
const animData = this.animData;
if (this.inReverse === !isReverse && this.repeatCounter > 0)
{
if (animData.repeatDelay === 0 || this.pendingRepeat)
{
this.forward = isReverse;
}
this.repeatAnimation();
return;
}
if (this.inReverse !== isReverse && this.repeatCounter === 0)
{
this.complete();
return;
}
this.forward = isReverse;
if (isReverse)
{
this.setCurrentFrame(this.currentFrame.nextFrame);
}
else
{
this.setCurrentFrame(this.currentFrame.prevFrame);
}
this.getNextTick();
}
prevFrame (): this
{
const frame = this.currentFrame;
const animData = this.animData;
if (frame.isFirst)
{
// We're at the start of the animation
if (animData.yoyo)
{
this.handleYoyoFrame(true);
}
else if (this.repeatCounter > 0)
{
if (this.inReverse && !this.forward)
{
this.repeatAnimation();
}
else
{
// Repeat (happens before complete)
this.forward = true;
this.repeatAnimation();
}
}
else
{
this.complete();
}
}
else
{
this.setCurrentFrame(frame.prevFrame);
this.getNextTick();
}
return this;
}
complete (): void
{
this.pendingStop = 0;
this.animData.isPlaying = false;
if (this.currentAnimation)
{
this.handleComplete();
}
}
play (): this
{
const data = this.animData;
if (data.repeat === -1)
{
// Should give us 9,007,199,254,740,991 safe repeats
this.repeatCounter = Number.MAX_VALUE;
}
data.isPlaying = true;
// If there is no start delay, we set the first frame immediately
if (data.delay === 0)
{
this.setTexture(this.currentFrame.texture, this.currentFrame.frame);
if (data.onStart)
{
data.onStart(this, this.currentAnimation);
}
}
else
{
data.pendingStart = true;
}
return this;
}
pause (atFrame: IAnimationFrame): this
{
if (!this.paused)
{
this.paused = true;
this.wasPlaying = this.isPlaying;
this.animData.isPlaying = false;
}
if (atFrame)
{
this.setCurrentFrame(atFrame);
}
return this;
}
resume (fromFrame: IAnimationFrame): this
{
if (this.paused)
{
this.paused = false;
this.animData.isPlaying = this.wasPlaying;
}
if (fromFrame)
{
this.setCurrentFrame(fromFrame);
}
return this;
}
get isPlaying (): boolean
{
return this.animData.isPlaying;
}
get isPlayingForward (): boolean
{
return (this.animData.isPlaying && this.forward);
}
destroy (reparentChildren?: IGameObject): void
{
super.destroy(reparentChildren);
this.animData = null;
}
} | the_stack |
namespace ts.projectSystem {
describe("unittests:: tsserver:: with project references and tsbuild source map", () => {
const dependecyLocation = `${tscWatch.projectRoot}/dependency`;
const dependecyDeclsLocation = `${tscWatch.projectRoot}/decls`;
const mainLocation = `${tscWatch.projectRoot}/main`;
const dependencyTs: File = {
path: `${dependecyLocation}/FnS.ts`,
content: `export function fn1() { }
export function fn2() { }
export function fn3() { }
export function fn4() { }
export function fn5() { }
`
};
const dependencyTsPath = dependencyTs.path.toLowerCase();
const dependencyConfig: File = {
path: `${dependecyLocation}/tsconfig.json`,
content: JSON.stringify({ compilerOptions: { composite: true, declarationMap: true, declarationDir: "../decls" } })
};
const mainTs: File = {
path: `${mainLocation}/main.ts`,
content: `import {
fn1,
fn2,
fn3,
fn4,
fn5
} from '../decls/fns'
fn1();
fn2();
fn3();
fn4();
fn5();
`
};
const mainConfig: File = {
path: `${mainLocation}/tsconfig.json`,
content: JSON.stringify({
compilerOptions: { composite: true, declarationMap: true },
references: [{ path: "../dependency" }]
})
};
const randomFile: File = {
path: `${tscWatch.projectRoot}/random/random.ts`,
content: "let a = 10;"
};
const randomConfig: File = {
path: `${tscWatch.projectRoot}/random/tsconfig.json`,
content: "{}"
};
const dtsLocation = `${dependecyDeclsLocation}/FnS.d.ts`;
const dtsPath = dtsLocation.toLowerCase() as Path;
const dtsMapLocation = `${dependecyDeclsLocation}/FnS.d.ts.map`;
const dtsMapPath = dtsMapLocation.toLowerCase() as Path;
const files = [dependencyTs, dependencyConfig, mainTs, mainConfig, libFile, randomFile, randomConfig];
function changeDtsFile(host: TestServerHost) {
host.writeFile(
dtsLocation,
host.readFile(dtsLocation)!.replace(
"//# sourceMappingURL=FnS.d.ts.map",
`export declare function fn6(): void;
//# sourceMappingURL=FnS.d.ts.map`
)
);
}
function changeDtsMapFile(host: TestServerHost) {
host.writeFile(
dtsMapLocation,
`{"version":3,"file":"FnS.d.ts","sourceRoot":"","sources":["../dependency/FnS.ts"],"names":[],"mappings":"AAAA,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,wBAAgB,GAAG,SAAM;AACzB,eAAO,MAAM,CAAC,KAAK,CAAC"}`
);
}
function verifyScriptInfos(session: TestSession, host: TestServerHost, openInfos: readonly string[], closedInfos: readonly string[], otherWatchedFiles: readonly string[], additionalInfo?: string) {
checkScriptInfos(session.getProjectService(), openInfos.concat(closedInfos), additionalInfo);
checkWatchedFiles(host, closedInfos.concat(otherWatchedFiles).map(f => f.toLowerCase()), additionalInfo);
}
function verifyOnlyRandomInfos(session: TestSession, host: TestServerHost) {
verifyScriptInfos(session, host, [randomFile.path], [libFile.path], [randomConfig.path], "Random");
}
function declarationSpan(fn: number): protocol.TextSpanWithContext {
return {
start: { line: fn, offset: 17 },
end: { line: fn, offset: 20 },
contextStart: { line: fn, offset: 1 },
contextEnd: { line: fn, offset: 26 }
};
}
function importSpan(fn: number): protocol.TextSpanWithContext {
return {
start: { line: fn + 1, offset: 5 },
end: { line: fn + 1, offset: 8 },
contextStart: { line: 1, offset: 1 },
contextEnd: { line: 7, offset: 22 }
};
}
function usageSpan(fn: number): protocol.TextSpan {
return { start: { line: fn + 8, offset: 1 }, end: { line: fn + 8, offset: 4 } };
}
function goToDefFromMainTs(fn: number): Action<protocol.DefinitionAndBoundSpanRequest, protocol.DefinitionInfoAndBoundSpan> {
const textSpan = usageSpan(fn);
const definition: protocol.FileSpan = { file: dependencyTs.path, ...declarationSpan(fn) };
return {
reqName: "goToDef",
request: {
command: protocol.CommandTypes.DefinitionAndBoundSpan,
arguments: { file: mainTs.path, ...textSpan.start }
},
expectedResponse: {
// To dependency
definitions: [definition],
textSpan
}
};
}
function goToDefFromMainTsWithNoMap(fn: number): Action<protocol.DefinitionAndBoundSpanRequest, protocol.DefinitionInfoAndBoundSpan> {
const textSpan = usageSpan(fn);
const definition = declarationSpan(fn);
const declareSpaceLength = "declare ".length;
return {
reqName: "goToDef",
request: {
command: protocol.CommandTypes.DefinitionAndBoundSpan,
arguments: { file: mainTs.path, ...textSpan.start }
},
expectedResponse: {
// To the dts
definitions: [{
file: dtsPath,
start: { line: fn, offset: definition.start.offset + declareSpaceLength },
end: { line: fn, offset: definition.end.offset + declareSpaceLength },
contextStart: { line: fn, offset: 1 },
contextEnd: { line: fn, offset: 37 }
}],
textSpan
}
};
}
function goToDefFromMainTsWithNoDts(fn: number): Action<protocol.DefinitionAndBoundSpanRequest, protocol.DefinitionInfoAndBoundSpan> {
const textSpan = usageSpan(fn);
return {
reqName: "goToDef",
request: {
command: protocol.CommandTypes.DefinitionAndBoundSpan,
arguments: { file: mainTs.path, ...textSpan.start }
},
expectedResponse: {
// To import declaration
definitions: [{ file: mainTs.path, ...importSpan(fn) }],
textSpan
}
};
}
function goToDefFromMainTsWithDependencyChange(fn: number): Action<protocol.DefinitionAndBoundSpanRequest, protocol.DefinitionInfoAndBoundSpan> {
const textSpan = usageSpan(fn);
return {
reqName: "goToDef",
request: {
command: protocol.CommandTypes.DefinitionAndBoundSpan,
arguments: { file: mainTs.path, ...textSpan.start }
},
expectedResponse: {
// Definition on fn + 1 line
definitions: [{ file: dependencyTs.path, ...declarationSpan(fn + 1) }],
textSpan
}
};
}
function renameFromDependencyTs(fn: number): Action<protocol.RenameRequest, protocol.RenameResponseBody> {
const defSpan = declarationSpan(fn);
const { contextStart: _, contextEnd: _1, ...triggerSpan } = defSpan;
return {
reqName: "rename",
request: {
command: protocol.CommandTypes.Rename,
arguments: { file: dependencyTs.path, ...triggerSpan.start }
},
expectedResponse: {
info: {
canRename: true,
fileToRename: undefined,
displayName: `fn${fn}`,
fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`,
kind: ScriptElementKind.functionElement,
kindModifiers: "export",
triggerSpan
},
locs: [
{ file: dependencyTs.path, locs: [defSpan] }
]
}
};
}
function renameFromDependencyTsWithDependencyChange(fn: number): Action<protocol.RenameRequest, protocol.RenameResponseBody> {
const { expectedResponse: { info, locs }, ...rest } = renameFromDependencyTs(fn + 1);
return {
...rest,
expectedResponse: {
info: {
...info as protocol.RenameInfoSuccess,
displayName: `fn${fn}`,
fullDisplayName: `"${dependecyLocation}/FnS".fn${fn}`,
},
locs
}
};
}
function renameFromDependencyTsWithBothProjectsOpen(fn: number): Action<protocol.RenameRequest, protocol.RenameResponseBody> {
const { reqName, request, expectedResponse } = renameFromDependencyTs(fn);
const { info, locs } = expectedResponse;
return {
reqName,
request,
expectedResponse: {
info,
locs: [
locs[0],
{
file: mainTs.path,
locs: [
importSpan(fn),
usageSpan(fn)
]
}
]
}
};
}
function renameFromDependencyTsWithBothProjectsOpenWithDependencyChange(fn: number): Action<protocol.RenameRequest, protocol.RenameResponseBody> {
const { reqName, request, expectedResponse, } = renameFromDependencyTsWithDependencyChange(fn);
const { info, locs } = expectedResponse;
return {
reqName,
request,
expectedResponse: {
info,
locs: [
locs[0],
{
file: mainTs.path,
locs: [
importSpan(fn),
usageSpan(fn)
]
}
]
}
};
}
function removePath(array: readonly string[], ...delPaths: string[]) {
return array.filter(a => {
const aLower = a.toLowerCase();
return delPaths.every(dPath => dPath !== aLower);
});
}
interface Action<Req = protocol.Request, Response = {}> {
reqName: string;
request: Partial<Req>;
expectedResponse: Response;
}
function verifyAction(session: TestSession, { reqName, request, expectedResponse }: Action) {
const { response } = session.executeCommandSeq(request);
assert.deepEqual(response, expectedResponse, `Failed Request: ${reqName}`);
}
function verifyDocumentPositionMapper(
session: TestSession,
dependencyMap: server.ScriptInfo | undefined,
documentPositionMapper: server.ScriptInfo["documentPositionMapper"],
equal: boolean,
debugInfo?: string,
) {
assert.strictEqual(session.getProjectService().filenameToScriptInfo.get(dtsMapPath), dependencyMap, `${debugInfo} dependencyMap`);
if (dependencyMap) {
verifyEquality(dependencyMap.documentPositionMapper, documentPositionMapper, equal, `${debugInfo} DocumentPositionMapper`);
}
}
function verifyDocumentPositionMapperEqual(
session: TestSession,
dependencyMap: server.ScriptInfo | undefined,
documentPositionMapper: server.ScriptInfo["documentPositionMapper"],
debugInfo?: string,
) {
verifyDocumentPositionMapper(session, dependencyMap, documentPositionMapper, /*equal*/ true, debugInfo);
}
function verifyEquality<T>(actual: T, expected: T, equal: boolean, debugInfo?: string) {
if (equal) {
assert.strictEqual(actual, expected, debugInfo);
}
else {
assert.notStrictEqual(actual, expected, debugInfo);
}
}
function verifyAllFnAction<Req = protocol.Request, Response = {}>(
session: TestSession,
host: TestServerHost,
action: (fn: number) => Action<Req, Response>,
expectedInfos: readonly string[],
expectedWatchedFiles: readonly string[],
existingDependencyMap: server.ScriptInfo | undefined,
existingDocumentPositionMapper: server.ScriptInfo["documentPositionMapper"],
existingMapEqual: boolean,
existingDocumentPositionMapperEqual: boolean,
skipMapPathInDtsInfo?: boolean
) {
let sourceMapPath: server.ScriptInfo["sourceMapFilePath"] | undefined;
let dependencyMap: server.ScriptInfo | undefined;
let documentPositionMapper: server.ScriptInfo["documentPositionMapper"];
for (let fn = 1; fn <= 5; fn++) {
const fnAction = action(fn);
verifyAction(session, fnAction);
const debugInfo = `${fnAction.reqName}:: ${fn}`;
checkScriptInfos(session.getProjectService(), expectedInfos, debugInfo);
checkWatchedFiles(host, expectedWatchedFiles, debugInfo);
const dtsInfo = session.getProjectService().getScriptInfoForPath(dtsPath);
const dtsMapInfo = session.getProjectService().getScriptInfoForPath(dtsMapPath);
if (fn === 1) {
if (dtsInfo) {
if (!skipMapPathInDtsInfo) {
if (dtsMapInfo) {
assert.equal(dtsInfo.sourceMapFilePath, dtsMapPath, `${debugInfo} sourceMapFilePath`);
}
else {
assert.isNotString(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`);
assert.isNotFalse(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`);
assert.isDefined(dtsInfo.sourceMapFilePath, `${debugInfo} sourceMapFilePath`);
}
}
}
verifyEquality(dtsMapInfo, existingDependencyMap, existingMapEqual, `${debugInfo} dependencyMap`);
verifyEquality(existingDocumentPositionMapper, dtsMapInfo?.documentPositionMapper, existingDocumentPositionMapperEqual, `${debugInfo} DocumentPositionMapper`);
sourceMapPath = dtsInfo?.sourceMapFilePath;
dependencyMap = dtsMapInfo;
documentPositionMapper = dependencyMap?.documentPositionMapper;
}
else {
assert.equal(dtsInfo?.sourceMapFilePath, sourceMapPath, `${debugInfo} sourceMapFilePath`);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper, debugInfo);
}
}
}
function verifyScriptInfoCollectionWith(
session: TestSession,
host: TestServerHost,
openFiles: readonly File[],
expectedInfos: readonly string[],
expectedWatchedFiles: readonly string[],
) {
const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session);
// Collecting at this point retains dependency.d.ts and map
closeFilesForSession([randomFile], session);
openFilesForSession([randomFile], session);
checkScriptInfos(session.getProjectService(), expectedInfos);
checkWatchedFiles(host, expectedWatchedFiles);
// If map is not collected, document position mapper shouldnt change
if (session.getProjectService().filenameToScriptInfo.has(dtsMapPath)) {
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
}
// Closing open file, removes dependencies too
closeFilesForSession([...openFiles, randomFile], session);
openFilesForSession([randomFile], session);
verifyOnlyRandomInfos(session, host);
}
type OnHostCreate = (host: TestServerHost) => void;
type CreateSessionFn = (onHostCreate?: OnHostCreate) => { host: TestServerHost; session: TestSession; };
function setupWith(createSession: CreateSessionFn, openFiles: readonly File[], onHostCreate: OnHostCreate | undefined) {
const result = createSession(onHostCreate);
openFilesForSession(openFiles, result.session);
return result;
}
function setupWithMainTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) {
return setupWith(createSession, [mainTs, randomFile], onHostCreate);
}
function setupWithDependencyTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) {
return setupWith(createSession, [dependencyTs, randomFile], onHostCreate);
}
function setupWithMainTsAndDependencyTs(createSession: CreateSessionFn, onHostCreate: OnHostCreate | undefined) {
return setupWith(createSession, [mainTs, dependencyTs, randomFile], onHostCreate);
}
function createSessionWithoutProjectReferences(onHostCreate?: OnHostCreate) {
const host = createHostWithSolutionBuild(files, [mainConfig.path]);
// Erase project reference
host.writeFile(mainConfig.path, JSON.stringify({
compilerOptions: { composite: true, declarationMap: true }
}));
onHostCreate?.(host);
const session = createSession(host);
return { host, session };
}
function createSessionWithProjectReferences(onHostCreate?: OnHostCreate) {
const host = createHostWithSolutionBuild(files, [mainConfig.path]);
onHostCreate?.(host);
const session = createSession(host);
return { host, session };
}
function createSessionWithDisabledProjectReferences(onHostCreate?: OnHostCreate) {
const host = createHostWithSolutionBuild(files, [mainConfig.path]);
// Erase project reference
host.writeFile(mainConfig.path, JSON.stringify({
compilerOptions: {
composite: true,
declarationMap: true,
disableSourceOfProjectReferenceRedirect: true
},
references: [{ path: "../dependency" }]
}));
onHostCreate?.(host);
const session = createSession(host);
return { host, session };
}
function getDocumentPositionMapper(session: TestSession) {
const dependencyMap = session.getProjectService().filenameToScriptInfo.get(dtsMapPath);
const documentPositionMapper = dependencyMap?.documentPositionMapper;
return { dependencyMap, documentPositionMapper };
}
function checkMainProjectWithoutProjectReferences(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dtsPath]);
}
function checkMainProjectWithoutProjectReferencesWithoutDts(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path]);
}
function checkMainProjectWithProjectReferences(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dependencyTs.path]);
}
function checkMainProjectWithDisabledProjectReferences(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path, dtsPath]);
}
function checkMainProjectWithDisabledProjectReferencesWithoutDts(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(mainConfig.path)!, [mainTs.path, libFile.path, mainConfig.path]);
}
function checkDependencyProjectWith(session: TestSession) {
checkProjectActualFiles(session.getProjectService().configuredProjects.get(dependencyConfig.path)!, [dependencyTs.path, libFile.path, dependencyConfig.path]);
}
function makeChangeToMainTs(session: TestSession) {
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: mainTs.path,
line: 14,
offset: 1,
endLine: 14,
endOffset: 1,
insertString: "const x = 10;"
}
});
}
function makeChangeToDependencyTs(session: TestSession) {
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: dependencyTs.path,
line: 6,
offset: 1,
endLine: 6,
endOffset: 1,
insertString: "const x = 10;"
}
});
}
describe("from project that uses dependency: goToDef", () => {
function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType<CreateSessionFn>, onHostCreate: OnHostCreate | undefined) {
const result = setup(onHostCreate);
result.session.executeCommandSeq(goToDefFromMainTs(1).request);
return { ...result, ...getDocumentPositionMapper(result.session) };
}
function verifyScriptInfoCollection(
session: TestSession,
host: TestServerHost,
expectedInfos: readonly string[],
expectedWatchedFiles: readonly string[],
) {
return verifyScriptInfoCollectionWith(session, host, [mainTs], expectedInfos, expectedWatchedFiles);
}
describe("when main tsconfig doesnt have project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTs(createSessionWithoutProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkMainProjectWithoutProjectReferences(session);
}
function checkProjectsWithoutDts(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkMainProjectWithoutProjectReferencesWithoutDts(session);
}
function expectedScriptInfosWhenMapped() {
return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation];
}
function expectedWatchedFilesWhenMapped() {
return [dependencyTsPath, libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path];
}
function expectedScriptInfosWhenNoMap() {
// Because map is deleted, map and dependency are released
return removePath(expectedScriptInfosWhenMapped(), dtsMapPath, dependencyTsPath);
}
function expectedWatchedFilesWhenNoMap() {
// Watches deleted file
return removePath(expectedWatchedFilesWhenMapped(), dependencyTsPath);
}
function expectedScriptInfosWhenNoDts() {
// No dts, no map, no dependency
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath);
}
function expectedWatchedFilesWhenNoDts() {
return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath);
}
it("can go to definition correctly", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
// The script info for map is collected only after file open
expectedScriptInfosWhenNoMap().concat(dependencyTs.path),
expectedWatchedFilesWhenNoMap().concat(dependencyTsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjectsWithoutDts(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
// The script info for map is collected only after file open
expectedScriptInfosWhenNoDts().concat(dependencyTs.path, dtsMapLocation),
expectedWatchedFilesWhenNoDts().concat(dependencyTsPath, dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
});
describe("when main tsconfig has project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTs(createSessionWithProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkMainProjectWithProjectReferences(session);
}
function expectedScriptInfos() {
return [dependencyTs.path, libFile.path, mainTs.path, randomFile.path];
}
function expectedWatchedFiles() {
return [dependencyTsPath, dependencyConfig.path, libFile.path, mainConfig.path, randomConfig.path];
}
it("can go to definition correctly", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
it(`when defining project source changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
// Make change, without rebuild of solution
host.writeFile(dependencyTs.path, `function fooBar() { }
${dependencyTs.content}`);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithDependencyChange,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when defining project source changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session } = setupWithAction();
// change
// Make change, without rebuild of solution
host.writeFile(dependencyTs.path, `function fooBar() { }
${dependencyTs.content}`);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithDependencyChange,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it("when projects are not built", () => {
const host = createServerHost(files);
const session = createSession(host);
openFilesForSession([mainTs, randomFile], session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
});
describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTs(createSessionWithDisabledProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkMainProjectWithDisabledProjectReferences(session);
}
function checkProjectsWithoutDts(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkMainProjectWithDisabledProjectReferencesWithoutDts(session);
}
function expectedScriptInfosWhenMapped() {
return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation];
}
function expectedWatchedFilesWhenMapped() {
return [dependencyTsPath, libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path];
}
function expectedScriptInfosWhenNoMap() {
// Because map is deleted, map and dependency are released
return removePath(expectedScriptInfosWhenMapped(), dtsMapPath, dependencyTsPath);
}
function expectedWatchedFilesWhenNoMap() {
// Watches deleted file
return removePath(expectedWatchedFilesWhenMapped(), dependencyTsPath);
}
function expectedScriptInfosWhenNoDts() {
// No dts, no map, no dependency
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath);
}
function expectedWatchedFilesWhenNoDts() {
return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath, dependencyTsPath);
}
it("can go to definition correctly", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
// The script info for map is collected only after file open
expectedScriptInfosWhenNoMap().concat(dependencyTs.path),
expectedWatchedFilesWhenNoMap().concat(dependencyTsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjectsWithoutDts(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
// The script info for map is collected only after file open
expectedScriptInfosWhenNoDts().concat(dependencyTs.path, dtsMapLocation),
expectedWatchedFilesWhenNoDts().concat(dependencyTsPath, dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
});
});
describe("from defining project: rename", () => {
function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType<CreateSessionFn>, onHostCreate: OnHostCreate | undefined) {
const result = setup(onHostCreate);
result.session.executeCommandSeq(renameFromDependencyTs(1).request);
return { ...result, ...getDocumentPositionMapper(result.session) };
}
function verifyScriptInfoCollection(
session: TestSession,
host: TestServerHost,
expectedInfos: readonly string[],
expectedWatchedFiles: readonly string[],
) {
return verifyScriptInfoCollectionWith(session, host, [dependencyTs], expectedInfos, expectedWatchedFiles);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 2 });
checkDependencyProjectWith(session);
}
function expectedScriptInfos() {
return [libFile.path, dtsLocation, dtsMapLocation, dependencyTs.path, randomFile.path];
}
function expectedWatchedFiles() {
return [libFile.path, dtsPath, dtsMapPath, dependencyConfig.path, randomConfig.path];
}
function expectedScriptInfosWhenNoMap() {
// No map
return removePath(expectedScriptInfos(), dtsMapPath);
}
function expectedWatchedFilesWhenNoMap() {
// Watches deleted file = map file
return expectedWatchedFiles();
}
function expectedScriptInfosWhenNoDts() {
// no dts or map since dts itself doesnt exist
return removePath(expectedScriptInfos(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesWhenNoDts() {
// watch deleted file
return removePath(expectedWatchedFiles(), dtsMapPath);
}
describe("when main tsconfig doesnt have project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithDependencyTs(createSessionWithoutProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
it("rename locations from dependency", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
// Map is collected after file open
expectedScriptInfosWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesWhenNoDts().concat(dtsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
});
describe("when main tsconfig has project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithDependencyTs(createSessionWithProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
it("rename locations from dependency", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
// Map is collected after file open
expectedScriptInfosWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesWhenNoDts().concat(dtsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`when defining project source changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
// Make change, without rebuild of solution
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { }
`}
});
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithDependencyChange,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when defining project source changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session } = setupWithAction();
// change
// Make change, without rebuild of solution
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { }
`}
});
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithDependencyChange,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
});
it("when projects are not built", () => {
const host = createServerHost(files);
const session = createSession(host);
openFilesForSession([dependencyTs, randomFile], session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
});
describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithDependencyTs(createSessionWithDisabledProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
it("rename locations from dependency", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfos(),
expectedWatchedFiles(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfos(),
expectedWatchedFiles()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
// Map is collected after file open
expectedScriptInfosWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesWhenNoDts().concat(dtsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoDts(),
expectedWatchedFilesWhenNoDts(),
);
});
});
});
describe("when opening depedency and usage project: goToDef and rename", () => {
function setupWithActionWith(setup: (onHostCreate?: OnHostCreate) => ReturnType<CreateSessionFn>, onHostCreate: OnHostCreate | undefined) {
const result = setup(onHostCreate);
result.session.executeCommandSeq(goToDefFromMainTs(1).request);
result.session.executeCommandSeq(renameFromDependencyTsWithBothProjectsOpen(1).request);
return { ...result, ...getDocumentPositionMapper(result.session) };
}
function verifyScriptInfoCollection(
session: TestSession,
host: TestServerHost,
expectedInfos: readonly string[],
expectedWatchedFiles: readonly string[],
) {
return verifyScriptInfoCollectionWith(session, host, [mainTs, dependencyTs], expectedInfos, expectedWatchedFiles);
}
describe("when main tsconfig doesnt have project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTsAndDependencyTs(createSessionWithoutProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 });
checkMainProjectWithoutProjectReferences(session);
checkDependencyProjectWith(session);
}
function checkProjectsWithoutDts(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 });
checkMainProjectWithoutProjectReferencesWithoutDts(session);
checkDependencyProjectWith(session);
}
function expectedScriptInfosWhenMapped() {
return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation];
}
function expectedWatchedFilesWhenMapped() {
return [libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path];
}
function expectedScriptInfosWhenNoMap() {
// Because map is deleted, map and dependency are released
return removePath(expectedScriptInfosWhenMapped(), dtsMapPath);
}
function expectedWatchedFilesWhenNoMap() {
// Watches deleted file
return expectedWatchedFilesWhenMapped();
}
function expectedScriptInfosAfterGotoDefWhenNoDts() {
// No dts, no map
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesAfterGotoDefWhenNoDts() {
return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath);
}
function expectedScriptInfosAfterRenameWhenNoDts() {
// No dts, no map
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesAfterRenameWhenNoDts() {
// Watches dts file but not map file
return removePath(expectedWatchedFilesWhenMapped(), dtsMapPath);
}
it("goto Definition in usage and rename locations from defining project", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjectsWithoutDts(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
expectedScriptInfosAfterGotoDefWhenNoDts(),
expectedWatchedFilesAfterGotoDefWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
// The script info for map is collected only after file open
expectedScriptInfosAfterGotoDefWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesAfterGotoDefWhenNoDts().concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
// The script info for map is collected only after file open
expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
});
describe("when main tsconfig has project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTsAndDependencyTs(createSessionWithProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 });
checkMainProjectWithProjectReferences(session);
checkDependencyProjectWith(session);
}
function expectedScriptInfosAfterGotoDef() {
return [dependencyTs.path, libFile.path, mainTs.path, randomFile.path];
}
function expectedWatchedFilesAfterGotoDef() {
return [dependencyConfig.path, libFile.path, mainConfig.path, randomConfig.path];
}
function expectedScriptInfosAfterRenameWhenMapped() {
return expectedScriptInfosAfterGotoDef().concat(dtsLocation, dtsMapLocation);
}
function expectedWatchedFilesAfterRenameWhenMapped() {
return expectedWatchedFilesAfterGotoDef().concat(dtsPath, dtsMapPath);
}
function expectedScriptInfosAfterRenameWhenNoMap() {
// Map file is not present
return removePath(expectedScriptInfosAfterRenameWhenMapped(), dtsMapPath);
}
function expectedWatchedFilesAfterRenameWhenNoMap() {
// Watches map file
return expectedWatchedFilesAfterRenameWhenMapped();
}
function expectedScriptInfosAfterRenameWhenNoDts() {
// map and dts not present
return removePath(expectedScriptInfosAfterRenameWhenMapped(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesAfterRenameWhenNoDts() {
// Watches dts file but not map
return removePath(expectedWatchedFilesAfterRenameWhenMapped(), dtsMapPath);
}
it("goto Definition in usage and rename locations from defining project", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterGotoDef(),
expectedWatchedFilesAfterGotoDef(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterGotoDef(),
expectedWatchedFilesAfterGotoDef(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenNoMap(),
expectedWatchedFilesAfterRenameWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoMap(),
expectedWatchedFilesAfterRenameWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenNoMap(),
// Map file is reset so its not watched any more, as this action doesnt need map
removePath(expectedWatchedFilesAfterRenameWhenNoMap(), dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true,
/*skipMapPathInDtsInfo*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterRenameWhenNoMap(),
// Map file is reset so its not watched any more, as this action doesnt need map
removePath(expectedWatchedFilesAfterRenameWhenNoMap(), dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false,
/*skipMapPathInDtsInfo*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenNoMap(),
expectedWatchedFilesAfterRenameWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoMap(),
expectedWatchedFilesAfterRenameWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterGotoDef(),
expectedWatchedFilesAfterGotoDef(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterGotoDef(),
// Since the project for dependency is not updated, the watcher from rename for dts still there
expectedWatchedFilesAfterGotoDef().concat(dtsPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
// Map collection after file open
expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation),
// not watching dts since this operation doesnt need it
removePath(expectedWatchedFilesAfterRenameWhenNoDts(), dtsPath).concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
// Map collection after file open
expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
it(`when defining project source changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
// Make change, without rebuild of solution
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { }
`}
});
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithDependencyChange,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpenWithDependencyChange,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when defining project source changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
// Make change, without rebuild of solution
session.executeCommandSeq<protocol.ChangeRequest>({
command: protocol.CommandTypes.Change,
arguments: {
file: dependencyTs.path, line: 1, offset: 1, endLine: 1, endOffset: 1, insertString: `function fooBar() { }
`}
});
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithDependencyChange,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpenWithDependencyChange,
expectedScriptInfosAfterRenameWhenMapped(),
expectedWatchedFilesAfterRenameWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it("when projects are not built", () => {
const host = createServerHost(files);
const session = createSession(host);
openFilesForSession([mainTs, dependencyTs, randomFile], session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosAfterGotoDef(),
expectedWatchedFilesAfterGotoDef(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
});
describe("when main tsconfig has disableSourceOfProjectReferenceRedirect along with project reference", () => {
function setup(onHostCreate?: OnHostCreate) {
return setupWithMainTsAndDependencyTs(createSessionWithDisabledProjectReferences, onHostCreate);
}
function setupWithAction(onHostCreate?: OnHostCreate) {
return setupWithActionWith(setup, onHostCreate);
}
function checkProjects(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 });
checkMainProjectWithDisabledProjectReferences(session);
checkDependencyProjectWith(session);
}
function checkProjectsWithoutDts(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 3 });
checkMainProjectWithDisabledProjectReferencesWithoutDts(session);
checkDependencyProjectWith(session);
}
function expectedScriptInfosWhenMapped() {
return [mainTs.path, randomFile.path, dependencyTs.path, libFile.path, dtsPath, dtsMapLocation];
}
function expectedWatchedFilesWhenMapped() {
return [libFile.path, dtsPath, dtsMapPath, mainConfig.path, randomConfig.path, dependencyConfig.path];
}
function expectedScriptInfosWhenNoMap() {
// Because map is deleted, map and dependency are released
return removePath(expectedScriptInfosWhenMapped(), dtsMapPath);
}
function expectedWatchedFilesWhenNoMap() {
// Watches deleted file
return expectedWatchedFilesWhenMapped();
}
function expectedScriptInfosAfterGotoDefWhenNoDts() {
// No dts, no map
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesAfterGotoDefWhenNoDts() {
return removePath(expectedWatchedFilesWhenMapped(), dtsPath, dtsMapPath);
}
function expectedScriptInfosAfterRenameWhenNoDts() {
// No dts, no map
return removePath(expectedScriptInfosWhenMapped(), dtsPath, dtsMapPath);
}
function expectedWatchedFilesAfterRenameWhenNoDts() {
// Watches dts file but not map file
return removePath(expectedWatchedFilesWhenMapped(), dtsMapPath);
}
it("goto Definition in usage and rename locations from defining project", () => {
const { host, session } = setup();
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap, documentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
);
});
// Edit
it(`when usage file changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when usage file changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
makeChangeToMainTs(session);
makeChangeToDependencyTs(session);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit dts to add new fn
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency .d.ts changes, document position mapper doesnt change, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
// Edit map file to represent added new line
it(`when dependency file's map changes, when timeout occurs before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
host.runQueuedTimeoutCallbacks();
checkProjects(session);
verifyDocumentPositionMapperEqual(session, dependencyMap, documentPositionMapper);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`when dependency file's map changes, when timeout does not occur before request`, () => {
// Create DocumentPositionMapper
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// change
changeDtsMapFile(host);
// action
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ false
);
const { documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
});
it(`with depedency files map file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsMapLocation));
checkProjects(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency files map file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsMapLocation)!;
host.deleteFile(dtsMapLocation);
});
host.writeFile(dtsMapLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency files map file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsMapLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoMap,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
// Script info collection should behave as fileNotPresentKey
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenNoMap(),
expectedWatchedFilesWhenNoMap(),
);
});
it(`with depedency .d.ts file, when file is not present`, () => {
const { host, session } = setup(host => host.deleteFile(dtsLocation));
checkProjectsWithoutDts(session);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
expectedScriptInfosAfterGotoDefWhenNoDts(),
expectedWatchedFilesAfterGotoDefWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
/*existingDependencyMap*/ undefined,
/*existingDocumentPositionMapper*/ undefined,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
it(`with depedency .d.ts file, when file is created after actions on projects`, () => {
let fileContents: string;
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction(host => {
fileContents = host.readFile(dtsLocation)!;
host.deleteFile(dtsLocation);
});
host.writeFile(dtsLocation, fileContents!);
verifyAllFnAction(
session,
host,
goToDefFromMainTs,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ false,
/*existingDocumentPositionMapperEqual*/ false
);
const { dependencyMap: newDependencyMap, documentPositionMapper: newDocumentPositionMapper } = getDocumentPositionMapper(session);
verifyAllFnAction(
session,
host,
renameFromDependencyTsWithBothProjectsOpen,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped(),
newDependencyMap,
newDocumentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjects(session);
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosWhenMapped(),
expectedWatchedFilesWhenMapped()
);
});
it(`with depedency .d.ts file, when file is deleted after actions on the projects`, () => {
const { host, session, dependencyMap, documentPositionMapper } = setupWithAction();
// The dependency file is deleted when orphan files are collected
host.deleteFile(dtsLocation);
verifyAllFnAction(
session,
host,
goToDefFromMainTsWithNoDts,
// The script info for map is collected only after file open
expectedScriptInfosAfterGotoDefWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesAfterGotoDefWhenNoDts().concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
verifyAllFnAction(
session,
host,
renameFromDependencyTs,
// The script info for map is collected only after file open
expectedScriptInfosAfterRenameWhenNoDts().concat(dtsMapLocation),
expectedWatchedFilesAfterRenameWhenNoDts().concat(dtsMapPath),
dependencyMap,
documentPositionMapper,
/*existingMapEqual*/ true,
/*existingDocumentPositionMapperEqual*/ true
);
checkProjectsWithoutDts(session);
// Script info collection should behave as "noDts"
verifyScriptInfoCollection(
session,
host,
expectedScriptInfosAfterRenameWhenNoDts(),
expectedWatchedFilesAfterRenameWhenNoDts(),
);
});
});
});
});
} | the_stack |
import { Vector3 } from "three";
import Channel from "./Channel";
import Histogram from "./Histogram";
import { getColorByChannelIndex } from "./constants/colors";
/* eslint-disable @typescript-eslint/naming-convention */
export interface ImageInfo {
name: string;
version: string;
width: number;
height: number;
channels: number;
tiles: number;
pixel_size_x: number;
pixel_size_y: number;
pixel_size_z: number;
channel_names: string[];
channel_colors?: [number, number, number][];
rows: number;
cols: number;
tile_width: number;
tile_height: number;
atlas_width: number;
atlas_height: number;
transform: {
translation: [number, number, number];
rotation: [number, number, number];
};
}
export const getDefaultImageInfo = (): ImageInfo => {
return {
name: "",
version: "",
width: 1,
height: 1,
channels: 0,
tiles: 1,
pixel_size_x: 1,
pixel_size_y: 1,
pixel_size_z: 1,
channel_names: [],
channel_colors: [],
rows: 1,
cols: 1,
tile_width: 1,
tile_height: 1,
atlas_width: 1,
atlas_height: 1,
transform: {
translation: [0, 0, 0],
rotation: [0, 0, 0],
},
}
};
/* eslint-enable @typescript-eslint/naming-convention */
interface VolumeDataObserver {
onVolumeData: (vol: Volume, batch: number[]) => void;
onVolumeChannelAdded: (vol: Volume, idx: number) => void;
}
/**
* Provide dimensions of the volume data, including dimensions for texture atlas data in which the volume z slices
* are tiled across a single large 2d image plane.
* @typedef {Object} ImageInfo
* @property {string} name Base name of image
* @property {string} version schema version preferably in semver format.
* @property {number} width Width of original volumetric data prior to downsampling
* @property {number} height Height of original volumetric data prior to downsampling
* @property {number} channels Number of channels
* @property {number} tiles Number of tiles, which must be equal to the number of z-slices in original volumetric data
* @property {number} pixel_size_x Size of pixel in volumetric data to be rendered, in x-dimension, unitless
* @property {number} pixel_size_y Size of pixel in volumetric data to be rendered, in y-dimension, unitless
* @property {number} pixel_size_z Size of pixel in volumetric data to be rendered, in z-dimension, unitless
* @property {Array.<string>} channel_names Names of each of the channels to be rendered, in order. Unique identifier expected
* @property {number} rows Number of rows in tile array in each image. Note tiles <= rows*cols
* @property {number} cols Number of columns in tile array in each image. Note tiles <= rows*cols
* @property {number} tile_width Width of each tile in volumetric dataset to be rendered, in pixels
* @property {number} tile_height Height of each tile in volumetric dataset to be rendered, in pixels
* @property {number} atlas_width Total width of image containing all the tiles, in pixels. Note atlas_width === cols*tile_width
* @property {number} atlas_height Total height of image containing all the tiles, in pixels. Note atlas_height === rows*tile_height
* @property {Object} transform translation and rotation as arrays of 3 numbers. Translation is in voxels (to be multiplied by pixel_size values). Rotation is Euler angles in radians, appled in XYZ order.
* @example let imgdata = {
"width": 306,
"height": 494,
"channels": 9,
"channel_names": ["DRAQ5", "EGFP", "Hoechst 33258", "TL Brightfield", "SEG_STRUCT", "SEG_Memb", "SEG_DNA", "CON_Memb", "CON_DNA"],
"rows": 7,
"cols": 10,
"tiles": 65,
"tile_width": 204,
"tile_height": 292,
// for webgl reasons, it is best for atlas_width and atlas_height to be <= 2048
// and ideally a power of 2. This generally implies downsampling the original volume data for display in this viewer.
"atlas_width": 2040,
"atlas_height": 2044,
"pixel_size_x": 0.065,
"pixel_size_y": 0.065,
"pixel_size_z": 0.29,
"name": "AICS-10_5_5",
"status": "OK",
"version": "0.0.0",
"aicsImageVersion": "0.3.0",
"transform": {
"translation": [5, 5, 1],
"rotation": [0, 3.14159, 1.57]
}
};
*/
/**
* A renderable multichannel volume image with 8-bits per channel intensity values.
* @class
* @param {ImageInfo} imageInfo
*/
export default class Volume {
public imageInfo: ImageInfo;
public name: string;
public x: number;
public y: number;
public z: number;
private t: number;
private atlasSize: [number, number];
private volumeSize: [number, number, number];
public channels: Channel[];
private volumeDataObservers: VolumeDataObserver[];
public scale: Vector3;
private currentScale: Vector3;
private physicalSize: Vector3;
public normalizedPhysicalSize: Vector3;
private loaded: boolean;
/* eslint-disable @typescript-eslint/naming-convention */
public num_channels: number;
public channel_names: string[];
public channel_colors_default: [number, number, number][];
private pixel_size: [number, number, number];
/* eslint-enable @typescript-eslint/naming-convention */
constructor(imageInfo: ImageInfo = getDefaultImageInfo()) {
this.scale = new Vector3(1, 1, 1);
this.currentScale = new Vector3(1, 1, 1);
this.physicalSize = new Vector3(1, 1, 1);
this.normalizedPhysicalSize = new Vector3(1, 1, 1);
this.loaded = false;
this.imageInfo = imageInfo;
this.name = this.imageInfo.name;
// clean up some possibly bad data.
this.imageInfo.pixel_size_x = imageInfo.pixel_size_x || 1.0;
this.imageInfo.pixel_size_y = imageInfo.pixel_size_y || 1.0;
this.imageInfo.pixel_size_z = imageInfo.pixel_size_z || 1.0;
this.pixel_size = [this.imageInfo.pixel_size_x, this.imageInfo.pixel_size_y, this.imageInfo.pixel_size_z];
this.x = this.imageInfo.tile_width;
this.y = this.imageInfo.tile_height;
this.z = this.imageInfo.tiles;
this.t = 1;
this.num_channels = this.imageInfo.channels;
this.channel_names = this.imageInfo.channel_names.slice();
this.channel_colors_default = this.imageInfo.channel_colors
? this.imageInfo.channel_colors.slice()
: this.channel_names.map((name, index) => getColorByChannelIndex(index));
// fill in gaps
if (this.channel_colors_default.length < this.num_channels) {
for (let i = this.channel_colors_default.length - 1; i < this.num_channels; ++i) {
this.channel_colors_default[i] = getColorByChannelIndex(i);
}
}
this.atlasSize = [this.imageInfo.atlas_width, this.imageInfo.atlas_height];
this.volumeSize = [this.x, this.y, this.z];
this.channels = [];
for (let i = 0; i < this.num_channels; ++i) {
const channel = new Channel(this.channel_names[i]);
this.channels.push(channel);
// TODO pass in channel constructor...
channel.dims = [this.x, this.y, this.z];
}
this.setVoxelSize(this.pixel_size);
// make sure a transform is specified
if (!this.imageInfo.transform) {
this.imageInfo.transform = {
translation: [0, 0, 0],
rotation: [0, 0, 0],
};
}
if (!this.imageInfo.transform.translation) {
this.imageInfo.transform.translation = [0, 0, 0];
}
if (!this.imageInfo.transform.rotation) {
this.imageInfo.transform.rotation = [0, 0, 0];
}
this.volumeDataObservers = [];
}
setScale(scale: Vector3): void {
this.scale = scale;
this.currentScale = scale.clone();
}
// we calculate the physical size of the volume (voxels*pixel_size)
// and then normalize to the max physical dimension
setVoxelSize(values: number[]): void {
// basic error check. bail out if we get something bad.
if (!values.length || values.length < 3) {
return;
}
// only set the data if it is > 0. zero is not an allowed value.
if (values[0] > 0) {
this.pixel_size[0] = values[0];
}
if (values[1] > 0) {
this.pixel_size[1] = values[1];
}
if (values[2] > 0) {
this.pixel_size[2] = values[2];
}
const physSizeMin = Math.min(this.pixel_size[0], Math.min(this.pixel_size[1], this.pixel_size[2]));
const pixelsMax = Math.max(this.imageInfo.width, Math.max(this.imageInfo.height, this.z));
const sx = ((this.pixel_size[0] / physSizeMin) * this.imageInfo.width) / pixelsMax;
const sy = ((this.pixel_size[1] / physSizeMin) * this.imageInfo.height) / pixelsMax;
const sz = ((this.pixel_size[2] / physSizeMin) * this.z) / pixelsMax;
// this works because image was scaled down in x and y but not z.
// so use original x and y dimensions from imageInfo.
this.physicalSize = new Vector3(
this.imageInfo.width * this.pixel_size[0],
this.imageInfo.height * this.pixel_size[1],
this.z * this.pixel_size[2]
);
const m = Math.max(this.physicalSize.x, Math.max(this.physicalSize.y, this.physicalSize.z));
// Compute the volume's max extent - scaled to max dimension.
this.normalizedPhysicalSize = new Vector3().copy(this.physicalSize).multiplyScalar(1.0 / m);
// sx, sy, sz should be same as normalizedPhysicalSize
this.setScale(new Vector3(sx, sy, sz));
}
cleanup(): void {
// no op
}
/**
* @return a reference to the list of channel names
*/
channelNames(): string[] {
return this.channel_names;
}
getChannel(channelIndex: number): Channel {
return this.channels[channelIndex];
}
onChannelLoaded(batch: number[]): void {
// check to see if all channels are now loaded, and fire an event(?)
if (
this.channels.every(function (element, _index, _array) {
return element.loaded;
})
) {
this.loaded = true;
}
for (let i = 0; i < this.volumeDataObservers.length; ++i) {
this.volumeDataObservers[i].onVolumeData(this, batch);
}
}
/**
* Assign volume data via a 2d array containing the z slices as tiles across it. Assumes that the incoming data is consistent with the image's pre-existing imageInfo tile metadata.
* @param {number} channelIndex
* @param {Uint8Array} atlasdata
* @param {number} atlaswidth
* @param {number} atlasheight
*/
setChannelDataFromAtlas(channelIndex: number, atlasdata: Uint8Array, atlaswidth: number, atlasheight: number): void {
this.channels[channelIndex].setBits(atlasdata, atlaswidth, atlasheight);
this.channels[channelIndex].unpackVolumeFromAtlas(this.x, this.y, this.z);
this.onChannelLoaded([channelIndex]);
}
// ASSUMES that this.channelData.options is already set and incoming data is consistent with it
/**
* Assign volume data as a 3d array ordered x,y,z. The xy size must be equal to tilewidth*tileheight from the imageInfo used to construct this Volume. Assumes that the incoming data is consistent with the image's pre-existing imageInfo tile metadata.
* @param {number} channelIndex
* @param {Uint8Array} volumeData
*/
setChannelDataFromVolume(channelIndex: number, volumeData: Uint8Array): void {
this.channels[channelIndex].setFromVolumeData(
volumeData,
this.x,
this.y,
this.z,
this.atlasSize[0],
this.atlasSize[1]
);
this.onChannelLoaded([channelIndex]);
}
// TODO: decide if this should update imageInfo or not. For now, leave imageInfo alone as the "original" data
/**
* Add a new channel ready to receive data from one of the setChannelDataFrom* calls.
* Name and color will be defaulted if not provided. For now, leave imageInfo alone as the "original" data
* @param {string} name
* @param {Array.<number>} color [r,g,b]
*/
appendEmptyChannel(name: string, color?: [number, number, number]): number {
const idx = this.num_channels;
const chname = name || "channel_" + idx;
const chcolor = color || getColorByChannelIndex(idx);
this.num_channels += 1;
this.channel_names.push(chname);
this.channel_colors_default.push(chcolor);
this.channels.push(new Channel(chname));
for (let i = 0; i < this.volumeDataObservers.length; ++i) {
this.volumeDataObservers[i].onVolumeChannelAdded(this, idx);
}
return idx;
}
/**
* Get a value from the volume data
* @return {number} the intensity value from the given channel at the given xyz location
* @param {number} c The channel index
* @param {number} x
* @param {number} y
* @param {number} z
*/
getIntensity(c: number, x: number, y: number, z: number): number {
return this.channels[c].getIntensity(x, y, z);
}
/**
* Get the 256-bin histogram for the given channel
* @return {Histogram} the histogram
* @param {number} c The channel index
*/
getHistogram(c: number): Histogram {
return this.channels[c].getHistogram();
}
/**
* Set the lut for the given channel
* @param {number} c The channel index
* @param {Array.<number>} lut The lut as a 256 element array
*/
setLut(c: number, lut: Uint8Array): void {
this.channels[c].setLut(lut);
}
/**
* Set the color palette for the given channel
* @param {number} c The channel index
* @param {Array.<number>} palette The colors as a 256 element array * RGBA
*/
setColorPalette(c: number, palette: Uint8Array): void {
this.channels[c].setColorPalette(palette);
}
/**
* Set the color palette alpha multiplier for the given channel.
* This will blend between the ordinary color lut and this colorPalette lut.
* @param {number} c The channel index
* @param {number} alpha The alpha value as a number from 0 to 1
*/
setColorPaletteAlpha(c: number, alpha: number): void {
this.channels[c].setColorPaletteAlpha(alpha);
}
/**
* Return the intrinsic rotation associated with this volume (radians)
* @return {Array.<number>} the xyz Euler angles (radians)
*/
getRotation(): [number, number, number] {
// default axis order is XYZ
return this.imageInfo.transform.rotation;
}
/**
* Return the intrinsic translation (pivot center delta) associated with this volume, in normalized volume units
* @return {Array.<number>} the xyz translation in normalized volume units
*/
getTranslation(): [number, number, number] {
return this.voxelsToWorldSpace(this.imageInfo.transform.translation);
}
/**
* Return a translation in normalized volume units, given a translation in image voxels
* @return {Array.<number>} the xyz translation in normalized volume units
*/
voxelsToWorldSpace(xyz: [number, number, number]): [number, number, number] {
// ASSUME: translation is in original image voxels.
// account for pixel_size and normalized scaling in the threejs volume representation we're using
const m = 1.0 / Math.max(this.physicalSize.x, Math.max(this.physicalSize.y, this.physicalSize.z));
const pixelSizeVec = new Vector3().fromArray(this.pixel_size);
return new Vector3().fromArray(xyz).multiply(pixelSizeVec).multiplyScalar(m).toArray();
}
addVolumeDataObserver(o: VolumeDataObserver): void {
this.volumeDataObservers.push(o);
}
removeVolumeDataObserver(o: VolumeDataObserver): void {
if (o) {
const i = this.volumeDataObservers.indexOf(o);
if (i !== -1) {
this.volumeDataObservers.splice(i, 1);
}
}
}
removeAllVolumeDataObservers(): void {
this.volumeDataObservers = [];
}
isLoaded(): boolean {
return this.loaded;
}
setIsLoaded(loaded: boolean): void {
this.loaded = loaded;
}
} | the_stack |
import * as React from "react";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import commonServices from "../Common/CommonServices";
import * as stringsConstants from "../constants/strings";
import styles from "../scss/TOTMyDashBoard.module.scss";
import TOTSidebar from "./TOTSideBar";
import { RxJsEventEmitter } from "../events/RxJsEventEmitter";
//React Boot Strap
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
//FluentUI controls
import { IButtonStyles, PrimaryButton, DefaultButton } from "@fluentui/react/lib/Button";
import { Label } from "@fluentui/react/lib/Label";
import { Spinner, SpinnerSize } from "@fluentui/react/lib/Spinner";
import { Icon, IIconProps } from '@fluentui/react/lib/Icon';
//PNP
import {
TreeView,
ITreeItem,
TreeViewSelectionMode,
} from "@pnp/spfx-controls-react/lib/TreeView";
//Global Variables
let commonServiceManager: commonServices;
let currentUserEmail: string = "";
export interface ITOTMyDashboardProps {
context?: WebPartContext;
siteUrl: string;
onClickCancel: Function;
}
const backBtnStyles: Partial<IButtonStyles> = {
root: {
marginLeft: "1.5%",
marginTop: "1.5%",
borderColor: "#33344A",
backgroundColor: "white",
},
rootHovered: {
borderColor: "#33344A",
backgroundColor: "white",
color: "#000003"
},
rootPressed: {
borderColor: "#33344A",
backgroundColor: "white",
color: "#000003"
},
icon: {
fontSize: "17px",
fontWeight: "bolder",
color: "#000003",
opacity: 1
},
label: {
font: "normal normal bold 14px/24px Segoe UI",
letterSpacing: "0px",
color: "#000003",
opacity: 1,
marginTop: "-3px"
}
};
const saveIcon: IIconProps = { iconName: 'Save' };
const backIcon: IIconProps = { iconName: 'NavigateBack' };
interface ITOTMyDashboardState {
actionsList: ITreeItem[];
selectedActionsList: ITreeItem[];
completedActionsList: ITreeItem[];
showSuccess: boolean;
showError: boolean;
noActiveTournament: boolean;
errorMessage: string;
actionsError: boolean;
tournamentName: string;
showSpinner: boolean;
noPendingActions: boolean;
tournamentDescription: string;
}
export default class TOTMyDashboard extends React.Component<
ITOTMyDashboardProps,
ITOTMyDashboardState
> {
private readonly _eventEmitter: RxJsEventEmitter =
RxJsEventEmitter.getInstance();
constructor(props: ITOTMyDashboardProps, state: ITOTMyDashboardState) {
super(props);
//Set default values
this.state = {
actionsList: [],
selectedActionsList: [],
completedActionsList: [],
showSuccess: false,
showError: false,
noActiveTournament: false,
errorMessage: "",
actionsError: false,
tournamentName: "",
showSpinner: false,
noPendingActions: false,
tournamentDescription: "",
};
//Create object for CommonServices class
commonServiceManager = new commonServices(
this.props.context,
this.props.siteUrl
);
//Bind Methods
this.onActionSelected = this.onActionSelected.bind(this);
this.getPendingActions = this.getPendingActions.bind(this);
this.saveActions = this.saveActions.bind(this);
}
//Get Actions from Master list and bind it to treeview on app load
public componentDidMount() {
//Get Actions from Master list and bind it to Treeview
this.getPendingActions();
}
//On select of a tree node change the state of selected actions
private onActionSelected(items: ITreeItem[]) {
this.setState({ selectedActionsList: items });
}
//Get Actions from Master list and bind it to Treeview
private async getPendingActions() {
console.log(stringsConstants.TotLog + "Getting actions from master list.");
try {
//Get current users's email
currentUserEmail =
this.props.context.pageContext.user.email.toLowerCase();
//Get current active tournament details
let tournamentDetails: any[] =
await commonServiceManager.getActiveTournamentDetails();
//If active tournament found
if (tournamentDetails.length != 0) {
this.setState({
tournamentName: tournamentDetails[0]["Title"],
tournamentDescription: tournamentDetails[0]["Description"],
});
let filterActive: string =
"Title eq '" +
tournamentDetails[0]["Title"].replace(/'/g, "''") +
"'";
let filterUserTournaments: string =
"Tournament_x0020_Name eq '" +
tournamentDetails[0]["Title"].replace(/'/g, "''") +
"'" +
" and Title eq '" +
currentUserEmail +
"'";
//Get all actions for the tournament from "Tournament Actions" list
const allTournamentsActionsArray: any[] =
await commonServiceManager.getItemsWithOnlyFilter(
stringsConstants.TournamentActionsMasterList,
filterActive
);
//Sort on Category
allTournamentsActionsArray.sort((a, b) => a.Category.localeCompare(b.Category));
//Get all actions completed by the current user for the current tournament
const userActionsArray: any[] =
await commonServiceManager.getItemsWithOnlyFilter(
stringsConstants.UserActionsList,
filterUserTournaments
);
var treeItemsArray: ITreeItem[] = [];
var completedTreeItemsArray: ITreeItem[] = [];
//Build the Parent Nodes(Categories) in Treeview. Skip the items which are already completed by the user in "User Actions" list
await allTournamentsActionsArray.forEach((vAction) => {
//Check if the category is present in the 'User Actions' list
var compareCategoriesArray = userActionsArray.filter((elArray) => {
return (
elArray.Action == vAction["Action"] &&
elArray.Category == vAction["Category"]
);
});
const tree: ITreeItem = {
key: vAction["Category"],
label: vAction["Category"],
children: [],
};
//If the category is not present in User Actions list add it to 'Pending Tree view'
var found: boolean;
if (compareCategoriesArray.length == 0) {
//Check if Category is already added to the Treeview. If yes, skip adding.
found = treeItemsArray.some((value) => {
return value.label === vAction["Category"];
});
if (!found) treeItemsArray.push(tree);
}
//If the category is present in User Actions list add it to 'Completed Tree view'
else {
//Check if Category is already added to the Treeview. If yes, skip adding.
found = completedTreeItemsArray.some((value) => {
return value.label === vAction["Category"];
});
if (!found) completedTreeItemsArray.push(tree);
}
}); //For Loop
//Build the child nodes(Actions) in Treeview. Skip the items which are already completed by the user in "User Actions" list
await allTournamentsActionsArray.forEach((vAction) => {
//Check if the action is present in the 'User Actions' list
var compareActionsArray = userActionsArray.filter((elChildArray) => {
return (
elChildArray.Action == vAction["Action"] &&
elChildArray.Category == vAction["Category"]
);
});
//If the action is not present in User Actions list add it to 'Pending Tree view'
let tree: ITreeItem;
if (compareActionsArray.length == 0) {
if (vAction["HelpURL"] === 'null' || vAction["HelpURL"] == "") {
tree = {
key: vAction.Id,
label: vAction["Action"],
data:
vAction["Category"] +
stringsConstants.StringSeperator +
vAction["HelpURL"],
subLabel:
vAction["Points"] +
stringsConstants.PointsDisplayString +
vAction["Description"]
};
}
else {
tree = {
key: vAction.Id,
label: vAction["Action"],
data:
vAction["Category"] +
stringsConstants.StringSeperator +
vAction["HelpURL"],
subLabel:
vAction["Points"] +
stringsConstants.PointsDisplayString +
vAction["Description"],
actions: [
{
iconProps: {
iconName: "Info",
title: "Find out more about this action"
},
id: "GetItem",
actionCallback: async (treeItem: ITreeItem) => {
window.open(vAction["HelpURL"]);
},
},
],
};
}
var treeCol: Array<ITreeItem> = treeItemsArray.filter((value) => {
return value.label == vAction["Category"];
});
if (treeCol.length != 0) {
treeCol[0].children.push(tree);
}
}
//If the action present in User Actions list add it to 'Completed Tree view'
else {
if (vAction["HelpURL"] === 'null' || vAction["HelpURL"] == "") {
tree = {
key: vAction.Id,
label: vAction["Action"],
data:
vAction["Category"] +
stringsConstants.StringSeperator +
vAction["HelpURL"],
subLabel:
vAction["Points"] +
stringsConstants.PointsDisplayString +
vAction["Description"],
iconProps: {
iconName: "SkypeCheck",
},
};
}
else {
tree = {
key: vAction.Id,
label: vAction["Action"],
data:
vAction["Category"] +
stringsConstants.StringSeperator +
vAction["HelpURL"],
subLabel:
vAction["Points"] +
stringsConstants.PointsDisplayString +
vAction["Description"],
iconProps: {
iconName: "SkypeCheck",
},
actions: [
{
iconProps: {
iconName: "Info",
title: "Find out more about this action"
},
id: "GetItem",
actionCallback: async (treeItem: ITreeItem) => {
window.open(vAction["HelpURL"]);
},
},
],
};
}
var treeColCompleted: Array<ITreeItem> =
completedTreeItemsArray.filter((value) => {
return value.label == vAction["Category"];
});
if (treeColCompleted.length != 0) {
treeColCompleted[0].children.push(tree);
}
}
}); //For loop
if (treeItemsArray.length == 0)
this.setState({ noPendingActions: true });
this.setState({
actionsList: treeItemsArray,
completedActionsList: completedTreeItemsArray,
});
} // IF END
//If there is no active tournament
else {
this.setState({
showError: true,
errorMessage: stringsConstants.NoActiveTournamentMessage,
noActiveTournament: true
});
}
} catch (error) {
console.error("TOT_TOTMyDashboard_getPendingActions \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
" while retrieving actions list. Below are the details: \n" +
JSON.stringify(error),
});
}
}
// Save Tournament Details to SP Lists 'Actions List' and 'Tournament Actions'
private async saveActions() {
try {
this.setState({ showSpinner: true, actionsError: false });
if (this.state.selectedActionsList.length > 0) {
var selectedTreeArray: ITreeItem[] = this.state.selectedActionsList;
//Loop through actions selected and create a list item for each treeview selection
let createActionsPromise = [];
let checkActionsPromise = [];
for (let counter = 0; counter < selectedTreeArray.length; counter++) {
//Skip parent node for treeview which is not an action
if (selectedTreeArray[counter].data != undefined) {
//Insert User Action only if its not already there.
let filterUserTournaments: string =
"Tournament_x0020_Name eq '" +
this.state.tournamentName.replace(/'/g, "''") +
"'" +
" and Title eq '" +
currentUserEmail +
"'" +
" and Action eq '" +
selectedTreeArray[counter].label +
"'";
let checkActionsPresent =
await commonServiceManager.getItemsWithOnlyFilter(
stringsConstants.UserActionsList,
filterUserTournaments
);
checkActionsPromise.push(checkActionsPresent);
}
}
Promise.all(checkActionsPromise).then(async (responseObj) => {
let filterChildNodesArray = selectedTreeArray.filter(
(eFilter) => eFilter.data != undefined
);
for (let iCount = 0; iCount < responseObj.length; iCount++) {
if (responseObj[iCount].length == 0) {
if (filterChildNodesArray[iCount].data != undefined) {
let submitObject: any = {
Title: currentUserEmail,
Tournament_x0020_Name: this.state.tournamentName,
Action: filterChildNodesArray[iCount].label,
Category: filterChildNodesArray[iCount].data.split(
stringsConstants.StringSeperator
)[0],
Points: filterChildNodesArray[iCount].subLabel
.split(stringsConstants.StringSeperatorPoints)[0]
.replace(stringsConstants.PointsReplaceString, ""),
};
let createItems = await commonServiceManager.createListItem(
stringsConstants.UserActionsList,
submitObject
);
createActionsPromise.push(createItems);
}
}
}
this.setState({ actionsList: [], selectedActionsList: [] });
Promise.all(createActionsPromise).then(() => {
this.getPendingActions().then(() => {
this.setState({ showSpinner: false });
this._eventEmitter.emit("rebindSideBar:start", {
currentNumber: "1",
});
});
});
});
}
//No Action selected in Treeview
else {
this.setState({ actionsError: true, showSpinner: false });
}
} catch (error) {
console.error("TOT_TOTMyDashboard_saveActions \n", error);
this.setState({
showError: true,
errorMessage:
stringsConstants.TOTErrorMessage +
" while saving your actions. Below are the details: \n" +
JSON.stringify(error),
});
}
}
//Render Method
public render(): React.ReactElement<ITOTMyDashboardProps> {
return (
<div className={styles.container}>
<div className={styles.totSideBar}>
<TOTSidebar
siteUrl={this.props.siteUrl}
context={this.props.context}
onClickCancel={() => this.props.onClickCancel()}
/>
<div className={styles.contentTab}>
<div>
<div className={styles.totDashboardPath}>
<img src={require("../assets/CMPImages/BackIcon.png")}
className={styles.backImg}
/>
<span
className={styles.backLabel}
onClick={() => this.props.onClickCancel()}
title="Tournament of Teams"
>
Tournament of Teams
</span>
<span className={styles.border}></span>
<span className={styles.totDashboardLabel}>My Dashboard</span>
</div>
{this.state.showError && (
<div>
{this.state.noActiveTournament ? (
<div>
<Label className={styles.noTourErrorMessage}>
{this.state.errorMessage}
</Label>
<DefaultButton
text="Back"
title="Back"
iconProps={backIcon}
onClick={() => this.props.onClickCancel()}
styles={backBtnStyles}>
</DefaultButton>
</div>
)
:
<Label className={styles.errorMessage}>
{this.state.errorMessage}
</Label>
}
</div>
)}
</div>
{this.state.tournamentName != "" && (
<div>
{this.state.tournamentName != "" && (
<ul className={styles.listArea}>
<li className={styles.listVal}>
<span className={styles.labelHeading}>Tournament</span>:
<span className={styles.labelNormal}>
{this.state.tournamentName}
</span>
</li>
{this.state.tournamentDescription && (
<li className={styles.listVal}>
<span className={styles.labelHeading}>Description</span>:
<span className={styles.labelNormal}>
{this.state.tournamentDescription}
</span>
</li>
)}
</ul>
)}
</div>
)}
{this.state.tournamentName != "" && (
<div className={styles.contentArea}>
<Row>
<Col>
<Label className={styles.subHeaderUnderline}>
Pending Actions
</Label>
{this.state.noPendingActions && (
<Label className={styles.successMessage}>
<img src={require('../assets/TOTImages/tickIcon.png')} alt="tickIcon" className={styles.tickImage} />
There are no more pending actions in this tournament.
</Label>
)}
<TreeView
items={this.state.actionsList}
showCheckboxes={true}
selectChildrenIfParentSelected={true}
selectionMode={TreeViewSelectionMode.Multiple}
defaultExpanded={true}
onSelect={this.onActionSelected}
/>
{this.state.actionsError && (
<Label className={styles.errorMessage}>
Select atleast one action to proceed.
</Label>
)}
{this.state.showSpinner && (
<Spinner
label={stringsConstants.formSavingMessage}
size={SpinnerSize.large}
/>
)}
<div className={styles.btnArea}>
{this.state.actionsList.length != 0 && (
<PrimaryButton
text="Save"
title="Save"
iconProps={saveIcon}
onClick={this.saveActions}
className={styles.saveBtn}
></PrimaryButton>
)}
<PrimaryButton
text="Back"
title="Back"
iconProps={backIcon}
onClick={() => this.props.onClickCancel()}
styles={backBtnStyles}
></PrimaryButton>
</div>
</Col>
<Col>
<Label className={styles.subHeaderUnderline}>
Completed Actions
</Label>
<TreeView
items={this.state.completedActionsList}
defaultExpanded={true}
/>
</Col>
</Row>
</div>
)}
</div>
</div>
</div> //Final DIV
);
}
} | the_stack |
import { PaperLibrariesSelector } from "./tools/paper-libraries-selector/paper-libraries-selector";
import { PaperGetPageProperties } from './tools/paper-get-page-properties/paper-get-page-properties';
import { CrmApp } from '../../crm-app/crm-app';
import { NodeEditBehaviorStylesheetInstance, NodeEditBehaviorScriptInstance, NodeEditBehavior } from '../../node-edit-behavior/node-edit-behavior';
import { MonacoEditor } from '../monaco-editor/monaco-editor';
import { ScriptEdit } from '../script-edit/script-edit';
import { StylesheetEdit } from '../stylesheet-edit/stylesheet-edit';
import { Polymer } from '../../../../../tools/definitions/polymer';
declare const browserAPI: browserAPI;
type CodeEditBehaviorScriptInstanceAdditions = ScriptEdit & {
isScript: true;
};
export type CodeEditBehaviorScriptInstance = CodeEditBehavior<CodeEditBehaviorScriptInstanceAdditions>;
type CodeEditBehaviorStylesheetInstanceAdditions = StylesheetEdit & {
isScript: false;
};
export type CodeEditBehaviorStylesheetInstance = CodeEditBehavior<CodeEditBehaviorStylesheetInstanceAdditions>;
export type CodeEditBehaviorInstance = CodeEditBehavior<NodeEditBehaviorScriptInstance>|
CodeEditBehavior<NodeEditBehaviorStylesheetInstance>;
namespace CodeEditBehaviorNamespace {
type JQContextMenuItem = JQueryContextMenu | string;
export interface JQueryContextMenu extends JQueryStatic {
contextMenu(settings: {
selector: string;
items: JQContextMenuItem[];
} | 'destroy'): void;
bez(curve: number[]): string;
}
export class CEB {
static properties = {};
/**
* An interval to save any work not discarder or saved (say if your browser/pc crashes)
*/
static savingInterval: number = 0;
/**
* Whether this dialog is active
*/
static active: boolean = false;
/**
* The editor
*/
static editorManager: MonacoEditor = null;
/**
* The editor manager for the fullscreen editor
*/
static fullscreenEditorManager: MonacoEditor = null;
/**
* Whether the vertical scrollbar is already shown
*/
static verticalVisible: boolean = false;
/**
* Whether the horizontal scrollbar is already shown
*/
static horizontalVisible: boolean = false;
/**
* The settings element on the top-right of the editor
*/
static settingsEl: HTMLElement = null;
/**
* The container of the fullscreen and settings buttons
*/
static buttonsContainer: HTMLElement = null;
/**
* The editor's starting height
*/
static editorHeight: number = 0;
/**
* The editor's starting width
*/
static editorWidth: number = 0;
/**
* Whether to show the trigger editing section
*/
static showTriggers: boolean = false;
/**
* Whether to show the section that allows you to choose on which content to show this
*/
static showContentTypeChooser: boolean = false;
/**
* Whether the options are shown
*/
static optionsShown: boolean = false;
/**
* Whether the editor is in fullscreen mode
*/
static fullscreen: boolean = false;
/**
* The editor's settings before going to the settings page
*/
static unchangedEditorSettings: CRM.EditorSettings;
/**
* The editor's dimensions before it goes fullscreen
*/
static preFullscreenEditorDimensions: {
width?: string;
height?: string;
marginTop?: string;
marginLeft?: string;
} = {};
/**
* The mode the editor is in (main or background)
*/
static editorMode: 'main'|'background'|'options'|'libraries' = 'main';
static editorPlaceHolderAnimation: Animation;
static setThemeWhite(this: CodeEditBehaviorInstance) {
this.$.editorThemeSettingWhite.classList.add('currentTheme');
this.$.editorThemeSettingDark.classList.remove('currentTheme');
window.app.settings.editor.theme = 'white';
window.app.upload();
}
static setThemeDark(this: CodeEditBehaviorInstance) {
this.$.editorThemeSettingWhite.classList.remove('currentTheme');
this.$.editorThemeSettingDark.classList.add('currentTheme');
window.app.settings.editor.theme = 'dark';
window.app.upload();
}
static fontSizeChange(this: CodeEditBehaviorInstance) {
this.async(() => {
window.app.settings.editor.zoom = this.$.editorThemeFontSizeInput.$$('input').value + '';
window.app.upload();
}, 50);
}
static finishEditing(this: CodeEditBehaviorInstance) {
browserAPI.storage.local.set({
editing: null
});
window.useOptionsCompletions = false;
this.hideCodeOptions();
if (this.optionsShown) {
this.hideOptions();
}
Array.prototype.slice.apply(this.shadowRoot.querySelectorAll('.editorTab')).forEach(
function(tab: HTMLElement) {
tab.classList.remove('active');
});
this.$$('.mainEditorTab').classList.add('active');
};
/**
* Inserts given snippet of code into the editor
*/
static insertSnippet(__this: CodeEditBehaviorInstance, snippet: string, noReplace: boolean = false) {
const editor = __this.getEditorInstance().getEditorAsMonaco();
if (__this.editorManager.isTextarea(editor)) {
const { from, to, content } = editor.getSelected();
const replacement = noReplace ? snippet : snippet.replace(/%s/g, content);
const oldValue = editor.getValue();
const newValue = oldValue.slice(0, from.totalChar) +
replacement + oldValue.slice(to.totalChar);
if (!__this.editorManager.isDiff(editor)) {
editor.setValue(newValue);
}
} else {
const selections = editor.getSelections();
if (selections.length === 1) {
if (selections[0].toString().length === 0 &&
selections[0].getPosition().lineNumber === 0 &&
selections[0].getPosition().column === 0) {
//Find the first line without comments
const lines = __this.getEditorInstance().getValue().split('\n');
const commentLines = ['//', '/*', '*/', '*', ' *'];
for (let i = 0 ; i < lines.length; i++) {
for (const commentLine of commentLines) {
if (lines[i].indexOf(commentLine) === 0) {
continue;
}
}
selections[0] = new monaco.Selection(i, 0, i, 0);
break;
}
}
}
const commands = selections.map((selection) => {
const content = noReplace ? snippet : snippet.replace(/%s/g, selection.toString());
return window.monacoCommands.createReplaceCommand(selection, content);
});
if (!__this.editorManager.isDiff(editor)) {
editor.executeCommands('snippet', commands);
}
}
};
/**
* Pops out only the tools ribbon
*/
static popOutToolsRibbon(this: CodeEditBehaviorInstance) {
window.doc.editorToolsRibbonContainer.animate([
{
marginLeft: '0'
}, {
marginLeft: '-200px'
}
], {
duration: 800,
easing: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)'
}).onfinish = function (this: Animation) {
window.doc.editorToolsRibbonContainer.style.marginLeft = '-200px';
window.doc.editorToolsRibbonContainer.classList.remove('visible');
};
};
/**
* Toggles fullscreen mode for the editor
*/
static toggleFullScreen(this: CodeEditBehaviorInstance) {
(this.fullscreen ? this.exitFullScreen() : this.enterFullScreen());
};
/**
* Whether this instance is fullscreen
*/
static isFullscreen(this: CodeEditBehaviorInstance) {
return this.fullscreen;
}
/**
* Toggles the editor's options
*/
static toggleOptions(this: CodeEditBehaviorInstance) {
(this.optionsShown ? this.hideOptions() : this.showOptions());
};
/**
* Fills the editor-tools-ribbon on the left of the editor with elements
*/
static initToolsRibbon(this: CodeEditBehaviorInstance) {
if (this.item.type === 'script') {
(window.app.$.paperLibrariesSelector as PaperLibrariesSelector).init();
(window.app.$.paperGetPageProperties as PaperGetPageProperties).init((snippet: string) => {
this.insertSnippet(this, snippet);
});
}
};
/**
* Pops in the ribbons with an animation
*/
static popInRibbons(this: CodeEditBehaviorInstance) {
//Introduce title at the top
const scriptTitle = window.app.$.editorCurrentScriptTitle;
let titleRibbonSize;
if (window.app.storageLocal.shrinkTitleRibbon) {
window.doc.editorTitleRibbon.style.fontSize = '40%';
scriptTitle.style.padding = '0';
titleRibbonSize = '-18px';
} else {
titleRibbonSize = '-51px';
}
window.setDisplayFlex(scriptTitle);
scriptTitle.style.marginTop = titleRibbonSize;
const scriptTitleAnimation: {
marginTop: string;
marginLeft?: string;
}[] = [
{
marginTop: titleRibbonSize
}, {
marginTop: '0'
}
];
scriptTitle.style.marginLeft = '-200px';
this.initToolsRibbon();
setTimeout(() => {
window.setDisplayFlex(window.doc.editorToolsRibbonContainer);
if (!window.app.storageLocal.hideToolsRibbon) {
$(window.doc.editorToolsRibbonContainer).animate({
marginLeft: '0'
}, {
duration: 500,
easing: ($ as CodeEditBehaviorNamespace.JQueryContextMenu).bez([0.215, 0.610, 0.355, 1.000]),
step: (now: number) => {
window.addCalcFn(window.doc.fullscreenEditorEditor, 'width', `100vw - 200px - ${now}px`);
window.doc.fullscreenEditorEditor.style.marginLeft = `${now + 200}px`;
this.fullscreenEditorManager.editor.layout();
}
});
} else {
window.doc.editorToolsRibbonContainer.classList.add('visible');
}
}, 200);
setTimeout(() => {
const dummy = window.app.util.getDummy();
dummy.style.height = '0';
$(dummy).animate({
height: '50px'
}, {
duration: 500,
easing: ($ as CodeEditBehaviorNamespace.JQueryContextMenu).bez([0.215, 0.610, 0.355, 1.000]),
step: (now: number) => {
window.addCalcFn(window.doc.fullscreenEditorEditor, 'height', `100vh - ${now}px`);
window.addCalcFn(window.doc.fullscreenEditorHorizontal, 'height', `100vh - ${now}px`);
this.fullscreenEditorManager.editor.layout();
}
});
scriptTitle.animate(scriptTitleAnimation, {
duration: 500,
easing: 'cubic-bezier(0.215, 0.610, 0.355, 1.000)'
}).onfinish = function() {
scriptTitle.style.marginTop = '0';
if (scriptTitleAnimation[0]['marginLeft'] !== undefined) {
scriptTitle.style.marginLeft = '0';
}
};
}, 200);
};
/**
* Pops out the ribbons with an animation
*/
static popOutRibbons(this: CodeEditBehaviorInstance) {
const scriptTitle = window.app.$.editorCurrentScriptTitle;
let titleRibbonSize: string;
if (window.app.storageLocal.shrinkTitleRibbon) {
window.doc.editorTitleRibbon.style.fontSize = '40%';
scriptTitle.style.padding = '0';
titleRibbonSize = '-18px';
} else {
titleRibbonSize = '-51px';
}
window.setDisplayFlex(scriptTitle);
scriptTitle.style.marginTop = '0';
const scriptTitleAnimation: {
marginTop: string;
marginLeft?: string;
}[] = [
{
marginTop: '0'
}, {
marginTop: titleRibbonSize
}
];
scriptTitle.style.marginLeft = '-200px';
setTimeout(() => {
window.setDisplayFlex(window.doc.editorToolsRibbonContainer);
const hideToolsRibbon =
(window.app.storageLocal &&
window.app.storageLocal.hideToolsRibbon) || false;
if (!hideToolsRibbon) {
$(window.doc.editorToolsRibbonContainer).animate({
marginLeft: '-200px'
}, {
duration: 500,
easing: 'linear',
step: (now: number) => {
window.addCalcFn(window.doc.fullscreenEditorEditor, 'width', `100vw - 200px - ${now}px`);
window.doc.fullscreenEditorEditor.style.marginLeft = `${now + 200}px`;
this.fullscreenEditorManager.editor.layout();
}
});
} else {
window.doc.editorToolsRibbonContainer.classList.add('visible');
}
}, 200);
setTimeout(() => {
const dummy = window.app.util.getDummy();
dummy.style.height = '50px';
$(dummy).animate({
height: '0'
}, {
duration: 500,
easing: 'linear',
step: (now: number) => {
window.addCalcFn(window.doc.fullscreenEditorEditor, 'height', `100vh - ${now}px`);
window.addCalcFn(window.doc.fullscreenEditorHorizontal, 'height', `100vh - ${now}px`);
this.fullscreenEditorManager.editor.layout();
}
});
scriptTitle.animate(scriptTitleAnimation, {
duration: 500,
easing: 'linear'
}).onfinish = function() {
scriptTitle.style.marginTop = titleRibbonSize;
if (scriptTitleAnimation[0]['marginLeft'] !== undefined) {
scriptTitle.style.marginLeft = titleRibbonSize;
}
};
}, 200);
};
/**
* Exits the editor's fullscreen mode
*/
static exitFullScreen(this: CodeEditBehaviorInstance) {
if (!this.fullscreen) {
return;
}
this.fullscreen = false;
this.popOutRibbons();
setTimeout(() => {
const editorCont = window.doc.fullscreenEditorEditor;
this.$.editorFullScreen.children[0].innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M14 28h-4v10h10v-4h-6v-6zm-4-8h4v-6h6v-4H10v10zm24 14h-6v4h10V28h-4v6zm-6-24v4h6v6h4V10H28z"/></svg>';
$(editorCont).animate({
width: this.preFullscreenEditorDimensions.width,
height: this.preFullscreenEditorDimensions.height,
marginTop: this.preFullscreenEditorDimensions.marginTop,
marginLeft: this.preFullscreenEditorDimensions.marginLeft
}, {
duration: 500,
easing: 'easeOutCubic',
complete: () => {
editorCont.style.marginLeft = '0';
editorCont.style.marginTop = '0';
window.addCalcFn(editorCont, 'width', '', true);
window.addCalcFn(editorCont, 'height', '', true);
editorCont.style.width = '0';
editorCont.style.height = '0';
this.fullscreenEditorManager.destroy();
this.editorManager.claimScope();
window.doc.fullscreenEditor.style.display = 'none';
}
});
}, 700);
};
/**
* Enters fullscreen mode for the editor
*/
static async enterFullScreen(this: CodeEditBehaviorInstance): Promise<void> {
return new Promise<void>(async (resolve) => {
if (this.fullscreen) {
resolve(null);
return null;
}
this.fullscreen = true;
window.doc.fullscreenEditor.style.display = 'block';
const rect = this.editorManager.editor.getDomNode().getBoundingClientRect();
const editorCont = window.doc.fullscreenEditorEditor;
const editorContStyle = editorCont.style;
editorContStyle.marginLeft = this.preFullscreenEditorDimensions.marginLeft = rect.left + 'px';
editorContStyle.marginTop = this.preFullscreenEditorDimensions.marginTop = rect.top + 'px';
window.addCalcFn(editorCont, 'height', '', true);
window.addCalcFn(editorCont, 'width', '', true);
editorContStyle.height = this.preFullscreenEditorDimensions.height = rect.height + 'px';
editorContStyle.width = this.preFullscreenEditorDimensions.width = rect.width + 'px';
editorContStyle.position = 'absolute';
if (this.item.type === 'script') {
const __this = this as CodeEditBehavior<NodeEditBehaviorScriptInstance>;
const libsArr = __this.editorMode === 'main' ?
__this.newSettings.value.libraries : __this.newSettings.value.backgroundLibraries || [];
window.app.$.paperLibrariesSelector.updateLibraries(libsArr as any,
this.newSettings as CRM.ScriptNode, this.editorMode as 'main'|'background');
if (__this.newSettings.value.ts && __this.newSettings.value.ts.enabled) {
window.app.$.editorTypescript.classList.add('active');
} else {
window.app.$.editorTypescript.classList.remove('active');
}
}
this.fullscreenEditorManager = await editorCont.createFrom(this.editorManager);
const horizontalCenterer = window.crmEditPage.$.horizontalCenterer;
const bcr = horizontalCenterer.getBoundingClientRect();
const viewportWidth = bcr.width+ 20;
const viewPortHeight = bcr.height;
if (window.app.storageLocal.hideToolsRibbon !== undefined) {
if (window.app.storageLocal.hideToolsRibbon) {
window.doc.showHideToolsRibbonButton.classList.add('hidden');
} else {
window.doc.showHideToolsRibbonButton.classList.remove('hidden');
}
} else {
browserAPI.storage.local.set({
hideToolsRibbon: false
});
window.app.storageLocal.hideToolsRibbon = false;
window.doc.showHideToolsRibbonButton.classList.add('hidden');
}
if (window.app.storageLocal.shrinkTitleRibbon !== undefined) {
if (window.app.storageLocal.shrinkTitleRibbon) {
window.setTransform(window.doc.shrinkTitleRibbonButton, 'rotate(90deg)');
} else {
window.setTransform(window.doc.shrinkTitleRibbonButton, 'rotate(270deg)');
}
} else {
browserAPI.storage.local.set({
shrinkTitleRibbon: false
});
window.app.storageLocal.shrinkTitleRibbon = false;
window.setTransform(window.doc.shrinkTitleRibbonButton, 'rotate(270deg)');
}
document.documentElement.style.overflow = 'hidden';
editorCont.style.display = '-wekbit-flex';
editorCont.style.display = 'flex';
this.fullscreenEditorManager.editor.layout();
//Animate to corners
$(editorCont).animate({
width: viewportWidth,
height: viewPortHeight,
marginTop: 0,
marginLeft: 0
}, {
duration: 500,
easing: 'easeOutCubic',
step: () => {
this.fullscreenEditorManager.editor.layout();
},
complete: () => {
this.fullscreenEditorManager.editor.layout();
this.style.width = '100vw';
this.style.height = '100vh';
window.addCalcFn(window.app.$.fullscreenEditorHorizontal, 'height', '', true);
window.app.$.fullscreenEditorHorizontal.style.height = '100vh';
this.popInRibbons();
resolve(null);
}
});
});
};
/**
* Shows the options for the editor
*/
static showOptions(this: CodeEditBehaviorInstance) {
this.optionsShown = true;
this.unchangedEditorSettings = $.extend(true, {}, window.app.settings.editor);
if (this.fullscreen) {
this.fillEditorOptions(window.app);
this._showFullscreenOptions();
return;
}
const editorWidth = this.getEditorInstance().editor.getDomNode().getBoundingClientRect().width;
const editorHeight = this.getEditorInstance().editor.getDomNode().getBoundingClientRect().height;
const circleRadius = Math.sqrt((editorWidth * editorWidth) + (editorHeight * editorHeight)) + 200;
const settingsInitialMarginLeft = -500
const negHalfRadius = -circleRadius;
const squaredCircleRadius = circleRadius * 2;
this.$.bubbleCont.parentElement.style.width = `${editorWidth}px`;
this.$.bubbleCont.parentElement.style.height = `${editorHeight}px`;
this.$.editorOptionsContainer.style.width = `${editorWidth}px`;
this.$.editorOptionsContainer.style.height = `${editorHeight}px`;
(this.$$('#editorThemeFontSizeInput') as HTMLPaperInputElement).value = window.app.settings.editor.zoom;
this.fillEditorOptions(this);
$(this.$.settingsShadow).css({
width: '50px',
height: '50px',
borderRadius: '50%',
marginTop: '-25px',
marginRight: '-25px'
}).animate({
width: squaredCircleRadius,
height: squaredCircleRadius,
marginTop: negHalfRadius,
marginRight: negHalfRadius
}, {
duration: 500,
easing: 'linear',
progress: (animation: any) => {
this.$.editorOptionsContainer.style.marginLeft = (settingsInitialMarginLeft - animation.tweens[3].now) + 'px';
this.$.editorOptionsContainer.style.marginTop = -animation.tweens[2].now + 'px';
}
});
};
static _hideFullscreenOptions(this: CodeEditBehaviorInstance) {
window.setTransform(window.app.$.fullscreenSettingsContainer, 'translateX(500px)');
window.setTimeout(() => {
window.app.$.fullscreenEditorToggle.style.display = 'block';
}, 500);
}
/**
* Hides the options for the editor
*/
static hideOptions(this: CodeEditBehaviorInstance) {
this.optionsShown = false;
if (this.fullscreen) {
this._hideFullscreenOptions();
}
const settingsInitialMarginLeft = -500;
this.$.editorFullScreen.style.display = 'block';
$(this.$.settingsShadow).animate({
width: 0,
height: 0,
marginTop: 0,
marginRight: 0
}, {
duration: 500,
easing: 'linear',
progress: (animation: any) => {
this.$.editorOptionsContainer.style.marginLeft = (settingsInitialMarginLeft - animation.tweens[3].now) + 'px';
this.$.editorOptionsContainer.style.marginTop = -animation.tweens[2].now + 'px';
},
complete: () => {
const zoom = window.app.settings.editor.zoom;
const prevZoom = this.unchangedEditorSettings.zoom;
this.unchangedEditorSettings.zoom = zoom;
if (JSON.stringify(this.unchangedEditorSettings) !== JSON.stringify(window.app.settings.editor)) {
(this as any).reloadEditor();
}
if (zoom !== prevZoom) {
window.app.updateEditorZoom();
}
if (this.fullscreen) {
this.$.settingsContainer.style.height = '345px';
this.$.settingsContainer.style.overflowX = 'hidden';
this.$.bubbleCont.style.position = 'absolute';
this.$.bubbleCont.style.zIndex = 'auto';
}
}
});
};
/**
* Fills the this.editorOptions element with the elements it should contain (the options for the editor)
*/
static async fillEditorOptions(this: CodeEditBehaviorInstance, container: CrmApp|CodeEditBehaviorInstance) {
if (this.item.type === 'script') {
const __this = this as CodeEditBehaviorScriptInstance;
const scriptContainer = container as CodeEditBehaviorScriptInstance;
const keyBindings = await __this.getKeyBindings();
scriptContainer.$.keyBindingsTemplate.items = keyBindings;
scriptContainer.$.keyBindingsTemplate.render();
window.app.settings.editor.keyBindings = window.app.settings.editor.keyBindings || {
goToDef: keyBindings[0].defaultKey,
rename: keyBindings[1].defaultKey
};
Array.prototype.slice.apply(scriptContainer.$.keyBindingsTemplate.querySelectorAll('paper-input')).forEach((input: HTMLPaperInputElement) => {
input.setAttribute('data-prev-value', input.$$('input').value);
});
}
if (window.app.settings.editor.theme === 'white') {
container.$.editorThemeSettingWhite.classList.add('currentTheme');
} else {
container.$.editorThemeSettingWhite.classList.remove('currentTheme');
}
if (window.app.settings.editor.theme === 'dark') {
container.$.editorThemeSettingDark.classList.add('currentTheme');
} else {
container.$.editorThemeSettingDark.classList.remove('currentTheme');
}
container.$.editorThemeFontSizeInput.$$('input').value = window.app.settings.editor.zoom || '100';
};
static _showFullscreenOptions(this: CodeEditBehaviorInstance) {
window.app.$.fullscreenEditorToggle.style.display = 'none';
window.setTransform(window.app.$.fullscreenSettingsContainer, 'translateX(0)');
}
/**
* Triggered when the scrollbars get updated (hidden or showed) and adapts the
* icons' positions
*/
static scrollbarsUpdate(this: CodeEditBehaviorInstance, vertical: boolean) {
if (vertical !== this.verticalVisible) {
if (vertical) {
this.buttonsContainer.style.right = '29px';
} else {
this.buttonsContainer.style.right = '11px';
}
this.verticalVisible = !this.verticalVisible;
}
};
static getEditorInstance(this: CodeEditBehaviorInstance): MonacoEditor {
if (this.item.type === 'script') {
if (window.scriptEdit.fullscreen) {
return window.scriptEdit.fullscreenEditorManager;
}
return window.scriptEdit.editorManager;
}
if (window.stylesheetEdit.fullscreen) {
return window.stylesheetEdit.fullscreenEditorManager;
}
return window.stylesheetEdit.editorManager;
}
static showCodeOptions(this: CodeEditBehaviorInstance) {
window.useOptionsCompletions = true;
const value = typeof this.item.value.options === 'string' ?
this.item.value.options : JSON.stringify(this.item.value.options, null, '\t');
this.editorManager.switchToModel('options', value, this.editorManager.EditorMode.JSON_OPTIONS);
}
static hideCodeOptions(this: CodeEditBehaviorInstance) {
if (!window.useOptionsCompletions) {
return;
}
window.useOptionsCompletions = false;
}
static getAutoUpdateState(this: CodeEditBehaviorInstance) {
if ((this.newSettings.type !== 'script' && this.newSettings.type !== 'stylesheet') ||
this.newSettings.nodeInfo.source === 'local') {
return [false, true];
}
if (this.newSettings.nodeInfo &&
this.newSettings.nodeInfo.source) {
return [this.newSettings.nodeInfo.source.autoUpdate, false];
}
return [true, false];
}
static setUpdateIcons(this: CodeEditBehaviorInstance, enabled: boolean, hidden: boolean) {
if (hidden) {
this.$.updateIcon.style.display = 'none';
return;
}
if (enabled) {
this.$.updateEnabled.classList.remove('hidden');
this.$.updateDisabled.classList.add('hidden');
} else {
this.$.updateEnabled.classList.add('hidden');
this.$.updateDisabled.classList.remove('hidden');
}
}
static initUI(this: CodeEditBehaviorInstance) {
this.$.dropdownMenu.addEventListener('expansionStateChange', (({detail}: Polymer.EventType<'expansionStateChange', {
state: 'closing'|'closed'|'opening'|'opened';
}>) => {
const { state } = detail;
if (state === 'opening') {
this.editorManager.setDefaultHeight();
} else if (state === 'closed') {
this.editorManager.stopTempLayout();
} else if (state === 'opened') {
this.editorManager.setTempLayout();
}
}) as any);
const [ enabled, hidden ] = this.getAutoUpdateState();
this.setUpdateIcons(enabled, hidden);
}
static toggleAutoUpdate(this: CodeEditBehaviorInstance) {
if ((this.newSettings.type !== 'script' && this.newSettings.type !== 'stylesheet') ||
this.newSettings.nodeInfo.source === 'local') {
return;
}
if (!this.newSettings.nodeInfo) {
return;
}
this.newSettings.nodeInfo.source.autoUpdate =
!this.newSettings.nodeInfo.source.autoUpdate;
this.setUpdateIcons(this.newSettings.nodeInfo.source.autoUpdate, false);
}
static _CEBIinit(this: CodeEditBehaviorInstance) {
window.addEventListener('resize', () => {
if (this.fullscreen && this.active) {
this.fullscreenEditorManager.editor.layout();
}
});
this.initUI();
}
}
const CEBGlobal = {
getActive() {
if (window.scriptEdit && window.scriptEdit.active) {
return window.scriptEdit;
}
if (window.stylesheetEdit && window.stylesheetEdit.active) {
return window.stylesheetEdit;
}
return null;
},
getEditor() {
return this.getActive() && this.getActive().editorManager;
}
};
window.codeEditBehavior = CEBGlobal;
export type CodeEditBehaviorGlobal = typeof CEBGlobal;
}
export type CodeEditBehaviorBase = Polymer.El<'code-edit-behavior', typeof CodeEditBehaviorNamespace.CEB>;
export type CodeEditBehaviorGlobal = CodeEditBehaviorNamespace.CodeEditBehaviorGlobal;
export type CodeEditBehavior<T = CodeEditBehaviorScriptInstanceAdditions|CodeEditBehaviorStylesheetInstanceAdditions> =
NodeEditBehavior<CodeEditBehaviorBase & T>;
window.Polymer.CodeEditBehavior = window.Polymer.CodeEditBehavior || CodeEditBehaviorNamespace.CEB as CodeEditBehaviorBase; | the_stack |
import {Event, ErrorEvent, Evented} from '../util/evented';
import {extend} from '../util/util';
import EXTENT from '../data/extent';
import {ResourceType} from '../util/ajax';
import browser from '../util/browser';
import type {Source} from './source';
import type Map from '../ui/map';
import type Dispatcher from '../util/dispatcher';
import type Tile from './tile';
import type Actor from '../util/actor';
import type {Callback} from '../types/callback';
import type {GeoJSONSourceSpecification, PromoteIdSpecification} from '../style-spec/types.g';
import type {MapSourceDataType} from '../ui/events';
export type GeoJSONSourceOptions = GeoJSONSourceSpecification & {
workerOptions?: any;
collectResourceTiming: boolean;
}
/**
* A source containing GeoJSON.
* (See the [Style Specification](https://maplibre.org/maplibre-gl-js-docs/style-spec/#sources-geojson) for detailed documentation of options.)
*
* @example
* map.addSource('some id', {
* type: 'geojson',
* data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'
* });
*
* @example
* map.addSource('some id', {
* type: 'geojson',
* data: {
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "Point",
* "coordinates": [
* -76.53063297271729,
* 39.18174077994108
* ]
* }
* }]
* }
* });
*
* @example
* map.getSource('some id').setData({
* "type": "FeatureCollection",
* "features": [{
* "type": "Feature",
* "properties": { "name": "Null Island" },
* "geometry": {
* "type": "Point",
* "coordinates": [ 0, 0 ]
* }
* }]
* });
* @see [Draw GeoJSON points](https://maplibre.org/maplibre-gl-js-docs/example/geojson-markers/)
* @see [Add a GeoJSON line](https://maplibre.org/maplibre-gl-js-docs/example/geojson-line/)
* @see [Create a heatmap from points](https://maplibre.org/maplibre-gl-js-docs/example/heatmap/)
* @see [Create and style clusters](https://maplibre.org/maplibre-gl-js-docs/example/cluster/)
*/
class GeoJSONSource extends Evented implements Source {
type: 'geojson';
id: string;
minzoom: number;
maxzoom: number;
tileSize: number;
attribution: string;
promoteId: PromoteIdSpecification;
isTileClipped: boolean;
reparseOverscaled: boolean;
_data: GeoJSON.GeoJSON | string;
_options: any;
workerOptions: any;
map: Map;
actor: Actor;
_pendingLoads: number;
_collectResourceTiming: boolean;
_removed: boolean;
/**
* @private
*/
constructor(id: string, options: GeoJSONSourceOptions, dispatcher: Dispatcher, eventedParent: Evented) {
super();
this.id = id;
// `type` is a property rather than a constant to make it easy for 3rd
// parties to use GeoJSONSource to build their own source types.
this.type = 'geojson';
this.minzoom = 0;
this.maxzoom = 18;
this.tileSize = 512;
this.isTileClipped = true;
this.reparseOverscaled = true;
this._removed = false;
this._pendingLoads = 0;
this.actor = dispatcher.getActor();
this.setEventedParent(eventedParent);
this._data = (options.data as any);
this._options = extend({}, options);
this._collectResourceTiming = options.collectResourceTiming;
if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;
if (options.type) this.type = options.type;
if (options.attribution) this.attribution = options.attribution;
this.promoteId = options.promoteId;
const scale = EXTENT / this.tileSize;
// sent to the worker, along with `url: ...` or `data: literal geojson`,
// so that it can load/parse/index the geojson data
// extending with `options.workerOptions` helps to make it easy for
// third-party sources to hack/reuse GeoJSONSource.
this.workerOptions = extend({
source: this.id,
cluster: options.cluster || false,
geojsonVtOptions: {
buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,
tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,
extent: EXTENT,
maxZoom: this.maxzoom,
lineMetrics: options.lineMetrics || false,
generateId: options.generateId || false
},
superclusterOptions: {
maxZoom: options.clusterMaxZoom !== undefined ? options.clusterMaxZoom : this.maxzoom - 1,
minPoints: Math.max(2, options.clusterMinPoints || 2),
extent: EXTENT,
radius: (options.clusterRadius || 50) * scale,
log: false,
generateId: options.generateId || false
},
clusterProperties: options.clusterProperties,
filter: options.filter
}, options.workerOptions);
}
load() {
// although GeoJSON sources contain no metadata, we fire this event to let the SourceCache
// know its ok to start requesting tiles.
this._updateWorkerData('metadata');
}
onAdd(map: Map) {
this.map = map;
this.load();
}
/**
* Sets the GeoJSON data and re-renders the map.
*
* @param {Object|string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.
* @returns {GeoJSONSource} this
*/
setData(data: GeoJSON.GeoJSON | string) {
this._data = data;
this._updateWorkerData('content');
return this;
}
/**
* For clustered sources, fetches the zoom at which the given cluster expands.
*
* @param clusterId The value of the cluster's `cluster_id` property.
* @param callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`).
* @returns {GeoJSONSource} this
*/
getClusterExpansionZoom(clusterId: number, callback: Callback<number>) {
this.actor.send('geojson.getClusterExpansionZoom', {clusterId, source: this.id}, callback);
return this;
}
/**
* For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).
*
* @param clusterId The value of the cluster's `cluster_id` property.
* @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
* @returns {GeoJSONSource} this
*/
getClusterChildren(clusterId: number, callback: Callback<Array<GeoJSON.Feature>>) {
this.actor.send('geojson.getClusterChildren', {clusterId, source: this.id}, callback);
return this;
}
/**
* For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).
*
* @param clusterId The value of the cluster's `cluster_id` property.
* @param limit The maximum number of features to return.
* @param offset The number of features to skip (e.g. for pagination).
* @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).
* @returns {GeoJSONSource} this
* @example
* // Retrieve cluster leaves on click
* map.on('click', 'clusters', function(e) {
* var features = map.queryRenderedFeatures(e.point, {
* layers: ['clusters']
* });
*
* var clusterId = features[0].properties.cluster_id;
* var pointCount = features[0].properties.point_count;
* var clusterSource = map.getSource('clusters');
*
* clusterSource.getClusterLeaves(clusterId, pointCount, 0, function(error, features) {
* // Print cluster leaves in the console
* console.log('Cluster leaves:', error, features);
* })
* });
*/
getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback<Array<GeoJSON.Feature>>) {
this.actor.send('geojson.getClusterLeaves', {
source: this.id,
clusterId,
limit,
offset
}, callback);
return this;
}
/*
* Responsible for invoking WorkerSource's geojson.loadData target, which
* handles loading the geojson data and preparing to serve it up as tiles,
* using geojson-vt or supercluster as appropriate.
*/
_updateWorkerData(sourceDataType: MapSourceDataType) {
const options = extend({}, this.workerOptions);
const data = this._data;
if (typeof data === 'string') {
options.request = this.map._requestManager.transformRequest(browser.resolveURL(data), ResourceType.Source);
options.request.collectResourceTiming = this._collectResourceTiming;
} else {
options.data = JSON.stringify(data);
}
this._pendingLoads++;
this.fire(new Event('dataloading', {dataType: 'source'}));
// target {this.type}.loadData rather than literally geojson.loadData,
// so that other geojson-like source types can easily reuse this
// implementation
this.actor.send(`${this.type}.loadData`, options, (err, result) => {
this._pendingLoads--;
if (this._removed || (result && result.abandoned)) {
this.fire(new Event('dataabort', {dataType: 'source', sourceDataType}));
return;
}
let resourceTiming = null;
if (result && result.resourceTiming && result.resourceTiming[this.id])
resourceTiming = result.resourceTiming[this.id].slice(0);
if (err) {
this.fire(new ErrorEvent(err));
return;
}
const data: any = {dataType: 'source', sourceDataType};
if (this._collectResourceTiming && resourceTiming && resourceTiming.length > 0)
extend(data, {resourceTiming});
this.fire(new Event('data', data));
});
}
loaded(): boolean {
return this._pendingLoads === 0;
}
loadTile(tile: Tile, callback: Callback<void>) {
const message = !tile.actor ? 'loadTile' : 'reloadTile';
tile.actor = this.actor;
const params = {
type: this.type,
uid: tile.uid,
tileID: tile.tileID,
zoom: tile.tileID.overscaledZ,
maxZoom: this.maxzoom,
tileSize: this.tileSize,
source: this.id,
pixelRatio: this.map.getPixelRatio(),
showCollisionBoxes: this.map.showCollisionBoxes,
promoteId: this.promoteId
};
tile.request = this.actor.send(message, params, (err, data) => {
delete tile.request;
tile.unloadVectorData();
if (tile.aborted) {
return callback(null);
}
if (err) {
return callback(err);
}
tile.loadVectorData(data, this.map.painter, message === 'reloadTile');
return callback(null);
});
}
abortTile(tile: Tile) {
if (tile.request) {
tile.request.cancel();
delete tile.request;
}
tile.aborted = true;
}
unloadTile(tile: Tile) {
tile.unloadVectorData();
this.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id});
}
onRemove() {
this._removed = true;
this.actor.send('removeSource', {type: this.type, source: this.id});
}
serialize() {
return extend({}, this._options, {
type: this.type,
data: this._data
});
}
hasTransition() {
return false;
}
}
export default GeoJSONSource; | the_stack |
declare const $$: any;
declare const $: any;
export function defaultWaitTime(): number {
return browser.options.waitforTimeout;
}
export function currentPlatformName(): string {
return browser.capabilities.platformName;
}
export function currentBrowserName(): string {
return browser.capabilities.browserName;
}
export function getImageTagBrowserPlatform(): string {
return `${currentBrowserName()}-${currentPlatformName()}`;
}
export function getBaseURL(): string {
return browser.options.baseUrl;
}
export function open(path: string = ''): void {
browser.url(path);
}
export function pause(waitTime: number = defaultWaitTime()): void {
browser.pause(waitTime);
}
// tslint:disable-next-line:no-shadowed-variable
export function execute(source): void {
browser.execute(source);
}
export function isBrowser(browserName: string): boolean {
return browser.capabilities.browserName === browserName;
}
export function browserIsIEorSafari(): boolean {
return browserIsSafari() || browserIsIE();
}
export function browserIsFirefox(): boolean {
return isBrowser('firefox');
}
export function browserIsIE(): boolean {
return isBrowser('internet explorer');
}
export function browserIsSafari(): boolean {
return isBrowser('Safari');
}
export function browserIsSafariorFF(): boolean {
return browserIsSafari() || browserIsFirefox();
}
export function goBack(): void {
browser.back();
}
export function refreshPage(): void {
browser.refresh();
}
export function getAlertText(): string {
return browser.getAlertText();
}
export function acceptAlert(): void {
browser.acceptAlert();
}
export function isAlertOpen(): boolean {
return browser.isAlertOpen();
}
export function click(selector: string, index: number = 0, waitTime: number = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].click();
}
export function clickWithOption(
selector: string,
index: number = 0,
waitTime: number = defaultWaitTime(),
options: object
): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].click(options);
}
export function doubleClick(selector: string, index: number = 0, waitTime: number = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].doubleClick();
}
// Clear value before set new
export function setValue(selector: string, value: string, index: number = 0, waitTime = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
$$(selector)[index].clearValue();
$$(selector)[index].setValue(value);
}
export function addValueWithDelay(
selector: string,
value: string,
delay: number = 100,
index: number = 0,
waitTime = defaultWaitTime()
): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
const valueArray = Array.from(value);
for (const symbol of valueArray) {
$$(selector)[index].addValue(symbol);
browser.pause(delay);
}
}
// add value to existing one
export function addValue(selector: string, value: string, index: number = 0, waitTime = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
$$(selector)[index].addValue(value);
}
export function getValue(selector: string, index: number = 0, waitTime = defaultWaitTime()): string {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].getValue();
}
export function getArrValues(selector: string, sliceStart?: number, sliceEnd?: number): string[] {
checkSelectorExists(selector);
return $$(selector)
.slice(sliceStart, sliceEnd)
.map((element) => element.getValue());
}
export function getText(selector: string, index: number = 0, waitTime = defaultWaitTime()): string {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].getText();
}
export function getTextArr(selector: string, sliceStart?: number, sliceEnd?: number): string[] {
checkSelectorExists(selector);
return $$(selector)
.slice(sliceStart, sliceEnd)
.map((element) => element.getText());
}
export function waitForElDisplayed(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
waitForPresent(selector, index);
checkSelectorExists(selector, index);
return $$(selector)[index].waitForDisplayed({ timeout: waitTime });
}
export function waitForInvisibilityOf(selector: string, index: number = 0): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitForDisplayed({ reverse: true });
}
export function waitForNotDisplayed(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitForDisplayed({ timeout: waitTime, reverse: true });
}
export function waitForClickable(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitForClickable({ timeout: waitTime });
}
export function waitForUnclickable(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitForClickable({ timeout: waitTime, reverse: true });
}
export function waitForElDisappear(selector: string, waitTime = defaultWaitTime()): boolean {
return $(selector).waitForExist({ timeout: waitTime, reverse: true });
}
export function waitForPresent(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitForExist({ timeout: waitTime });
}
export function waitForNotPresent(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
return $$(selector)[index].waitForExist({ timeout: waitTime, reverse: true });
}
export function isEnabled(selector: string, index: number = 0, waitTime = defaultWaitTime()): boolean {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
return $$(selector)[index].isEnabled();
}
// Waits to be empty if text is not passed
export function waitTextToBePresentInValue(
selector: string,
text: string = '',
index: number = 0,
waitTime = defaultWaitTime()
): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].waitUntil(
function (): boolean {
return this.getValue() === text;
},
{ timeout: waitTime, timeoutMsg: `${text} is not present in element ${selector}` }
);
}
// Sends to the active element
export function sendKeys(keys: string | string[]): void {
browser.keys(keys);
}
export function uploadFile(selector: string, pathToFile: string, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].setValue(pathToFile);
}
export function getAttributeByName(selector: string, attrName: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].getAttribute(attrName);
}
export function getElementClass(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].getAttribute('class');
}
export function getElementTitle(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].getAttribute('title');
}
export function getElementAriaLabel(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].getAttribute('aria-label');
}
export function getElementPlaceholder(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].getAttribute('placeholder');
}
export function getAttributeByNameArr(
selector: string,
attrName: string,
sliceStart?: number,
sliceEnd?: number
): string[] {
checkSelectorExists(selector);
return $$(selector)
.slice(sliceStart, sliceEnd)
.map((element) => element.getAttribute(attrName));
}
// Returns object (assertions needs to be adapted)
export function getCSSPropertyByName(selector: string, propertyName: string, index: number = 0): any {
// TODO: returns WebdriverIO.CSSProperty
checkSelectorExists(selector, index);
return $$(selector)[index].getCSSProperty(propertyName);
}
export function mouseHoverElement(selector: string, index: number = 0, waitTime = defaultWaitTime()): any {
checkSelectorExists(selector, index);
$$(selector)[index].waitForExist({ timeout: waitTime });
$$(selector)[index].moveTo();
}
export function clearValue(selector: string, index: number = 0, waitTime = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
$$(selector)[index].clearValue();
}
export function getElementSize(selector: string, index?: number): any; // TODO: returns WebdriverIO.SizeReturn;
export function getElementSize(selector: string, index: number, prop: 'width' | 'height'): number;
export function getElementSize(selector: string, index: number = 0, prop?: 'width' | 'height'): number {
// TODO: number | WebdriverIO.SizeReturn;
checkSelectorExists(selector, index);
return $$(selector)[index].getSize(prop || void 0);
}
export function executeScriptBeforeTagAttr(selector: string, attrName: string, index: number = 0): string {
return browser.execute(
(projectedSelector, projectedAttrName, projectedIndex) => {
return window.getComputedStyle(document.querySelectorAll(projectedSelector)[projectedIndex], ':before')[
projectedAttrName
];
},
selector,
attrName,
index
);
}
export function executeScriptAfterTagAttr(selector: string, attrName: string, index: number = 0): string {
return browser.execute(
(projectedSelector, projectedAttrName, projectedIndex) => {
return window.getComputedStyle(document.querySelectorAll(projectedSelector)[projectedIndex], ':after')[
projectedAttrName
];
},
selector,
attrName,
index
);
}
export function getElementArrayLength(selector: string): number {
return $$(selector).length;
}
export function elementArray(selector: string): any {
// TODO: returns WebdriverIO.ElementArray
return $$(selector);
}
export function elementDisplayed(selector: string, index: number = 0): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].isDisplayed();
}
export function clickAndHold(selector: string, index: number = 0, waitTime: number = defaultWaitTime()): void {
checkSelectorExists(selector, index);
$$(selector)[index].waitForDisplayed({ timeout: waitTime });
$$(selector)[index].moveTo();
return browser.buttonDown();
}
export function scrollIntoView(selector: string, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].scrollIntoView();
}
export function isElementClickable(selector: string, index: number = 0): boolean {
checkSelectorExists(selector, index);
return $$(selector)[index].isClickable();
}
export function isDisplayedInViewport(selector: string, index: number = 0): boolean {
return $$(selector)[index].isDisplayedInViewport();
}
export function waitElementToBeClickable(selector: string, index: number = 0): void {
browser.waitUntil(
(): boolean => {
return $$(selector)[index].isClickable();
},
{ timeout: defaultWaitTime() }
);
}
export function doesItExist(selector: string): boolean {
return $(selector).isExisting();
}
export function getCurrentUrl(): string {
return browser.getUrl();
}
export function dragAndDrop(
elementToDragSelector: string,
index: number = 0,
targetElementSelector: string,
targetIndex: number = 0
): void {
checkSelectorExists(elementToDragSelector, index);
checkSelectorExists(targetElementSelector, index);
$$(elementToDragSelector)[index].scrollIntoView();
$$(elementToDragSelector)[index].dragAndDrop($$(targetElementSelector)[targetIndex]);
}
export function clickAndMoveElement(selector: string, offsetX: number, offsetY: number, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].scrollIntoView();
$$(selector)[index].dragAndDrop({ x: offsetX, y: offsetY });
}
export function isElementDisplayed(selector: string, index: number = 0): boolean {
checkSelectorExists(selector, index);
$$(selector)[index].scrollIntoView();
return $$(selector)[index].isDisplayed();
}
export function focusElement(selector: string, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].scrollIntoView();
// @ts-ignore
$$(selector)[index].focus();
}
export function mouseButtonDown(button: 0 | 1 | 2 = 0): void {
browser.buttonDown(button);
}
export function mouseButtonUp(button: 0 | 1 | 2 = 0): void {
browser.buttonUp(button);
}
export function clickNextElement(selector: string, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].nextElement().click();
}
export function clickPreviousElement(selector: string, index: number = 0): void {
checkSelectorExists(selector, index);
$$(selector)[index].previousElement().click();
}
export function getElementLocation(selector: string, index?: number): any; // TODO: returns WebdriverIO.LocationReturn
export function getElementLocation(selector: string, index: number, prop: 'x' | 'y'): number;
export function getElementLocation(selector: string, index: number = 0, prop?: 'x' | 'y'): number {
// TODO: returns WebdriverIO.LocationReturn | number
return $$(selector)[index].getLocation(prop || void 0);
}
export function getParentElementCSSProperty(selector: string, prop: string, index: number): string {
checkSelectorExists(selector, index);
return $$(selector)[index].parentElement().getCSSProperty(prop).value;
}
export function addIsActiveClass(selector: string, index: number = 0): void {
// @ts-ignore
$$(selector)[index].addIsActiveClass();
}
export function clickAndDragElement(
locationX: number,
locationY: number,
newLocationX: number,
newLocationY: number
): void {
browser.performActions([
{
type: 'pointer',
id: 'pointer1',
parameters: { pointerType: 'mouse' },
actions: [
{ type: 'pointerMove', duration: 600, x: locationX, y: locationY },
{ type: 'pointerDown', button: 0 },
{ type: 'pointerMove', duration: 600, x: locationX, y: locationY },
{ type: 'pointerMove', duration: 1000, x: newLocationX, y: newLocationY },
{ type: 'pointerUp', button: 0 },
{ type: 'pause', duration: 500 }
]
}
]);
}
export function selectOptionByAttribute(
selector: string,
attribute: string,
attributeValue: string,
index: number = 0
): void {
click(selector, index);
waitForElDisplayed(`${selector} option[${attribute}="${attributeValue}"]`);
$(`${selector} option[${attribute}="${attributeValue}"]`).click();
}
export function selectOptionByValueAttribute(selector: string, attributeValue: string, index: number = 0): void {
selectOptionByAttribute(selector, 'value', attributeValue, index);
}
export function saveElementScreenshot(selector: string, tag: string, options?: object, index: number = 0): void {
browser.saveElement($$(selector)[index], tag, options);
}
export function checkElementScreenshot(selector: string, tag: string, options?: object, index: number = 0): any {
return browser.checkElement($$(selector)[index], tag, options);
}
function checkSelectorExists(selector: string, index: number = 0): void {
if ($$(selector)[index] === undefined) {
throw new Error(`Element with index: ${index} for selector: '${selector}' not found.`);
}
}
export function applyState(state: 'hover' | 'active' | 'focus', selector: string, index: number = 0): void {
switch (state) {
case 'hover':
return mouseHoverElement(selector, index);
case 'active':
return addIsActiveClass(selector, index);
case 'focus':
return focusElement(selector, index);
}
}
export function getPreviousElementText(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].previousElement().getText();
}
export function getNextElementText(selector: string, index: number = 0): string {
checkSelectorExists(selector, index);
return $$(selector)[index].nextElement().getText();
} | the_stack |
import { UserRequest } from '../interfaces/user-request.interface';
import { Response } from 'express';
import { getConnection } from 'typeorm';
import { Assessment } from '../entity/Assessment';
import { validate } from 'class-validator';
import { Vulnerability } from '../entity/Vulnerability';
import { File } from '../entity/File';
import { ProblemLocation } from '../entity/ProblemLocation';
import { Resource } from '../entity/Resource';
import { exportToJiraIssue } from '../utilities/jira.utility';
import { JiraInit } from '../interfaces/jira/jira-init.interface';
import { Jira } from '../entity/Jira';
import {
hasAssetReadAccess,
hasAssetWriteAccess,
} from '../utilities/role.utility';
const fileUploadController = require('../routes/file-upload.controller');
/**
* @description get vulnerability by ID
* @param {UserRequest} req
* @param {Response} res contains JSON object with the organization data
* @returns vulnerability data
*/
export const getVulnById = async (req: UserRequest, res: Response) => {
if (!req.params.vulnId) {
return res.status(400).send('Invalid Vulnerability UserRequest');
}
if (isNaN(+req.params.vulnId)) {
return res.status(400).send('Invalid Vulnerability ID');
}
// TODO: Utilize createQueryBuilder to only return screenshot IDs and not the full object
const vuln = await getConnection()
.getRepository(Vulnerability)
.findOne(req.params.vulnId, {
relations: ['screenshots', 'problemLocations', 'resources', 'assessment'],
});
const assessment = await getConnection()
.getRepository(Assessment)
.createQueryBuilder('assessment')
.leftJoinAndSelect('assessment.asset', 'asset')
.leftJoinAndSelect('asset.organization', 'organization')
.where('assessment.id = :assessmentId', {
assessmentId: vuln.assessment.id,
})
.select(['assessment', 'asset', 'organization'])
.getOne();
const hasReadAccess = await hasAssetReadAccess(req, assessment.asset.id);
if (!hasReadAccess) {
return res.status(404).json('Vulnerability not found');
}
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
const jira = await getConnection()
.getRepository(Jira)
.findOne({ where: { asset: assessment.asset } });
const jiraHost = jira ? jira.host : null;
if (!vuln) {
return res.status(404).send('Vulnerability does not exist.');
}
return res
.status(200)
.json({ vulnerability: vuln, jiraHost, readOnly: !hasAccess });
};
/**
* @description Delete vulnerability by ID
* @param {UserRequest} req vulnID is required
* @param {Response} res contains JSON object with the success/fail
* @returns success/error message
*/
export const deleteVulnById = async (req: UserRequest, res: Response) => {
if (!req.params.vulnId) {
return res.status(400).send('Invalid vulnerability UserRequest');
}
if (isNaN(+req.params.vulnId)) {
return res.status(400).send('Invalid vulnerability ID');
}
const vuln = await getConnection()
.getRepository(Vulnerability)
.findOne(req.params.vulnId, { relations: ['assessment'] });
if (!vuln) {
return res.status(404).send('Vulnerability does not exist.');
} else {
const assessment = await getConnection()
.getRepository(Assessment)
.findOne(req.body.assessment, { relations: ['asset'] });
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
await getConnection().getRepository(Vulnerability).delete(vuln);
return res
.status(200)
.json(`Vulnerability #${vuln.id}: "${vuln.name}" successfully deleted`);
}
};
/**
* @description Update vulnerability by ID
* @param {UserRequest} req
* @param {Response} res
* @returns success/error message
* // TODO: Break apart this function into smaller functions. Also make common as create is almost the same.
*/
export const patchVulnById = async (req: UserRequest, res: Response) => {
req = await fileUploadController.uploadFileArray(req, res);
if (isNaN(+req.body.assessment) || !req.body.assessment) {
return res.status(400).json('Invalid Assessment ID');
}
const assessment = await getConnection()
.getRepository(Assessment)
.findOne(req.body.assessment, { relations: ['asset'] });
if (!assessment) {
return res.status(404).json('Assessment does not exist');
}
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
if (isNaN(+req.params.vulnId)) {
return res.status(400).json('Vulnerability ID is invalid');
}
const vulnerability = await getConnection()
.getRepository(Vulnerability)
.findOne(req.params.vulnId);
if (!vulnerability) {
return res.status(404).json('Vulnerability does not exist');
}
const callback = (resStatus: number, message: any) => {
res.status(resStatus).send(message);
};
vulnerability.id = +req.params.vulnId;
vulnerability.impact = req.body.impact;
vulnerability.likelihood = req.body.likelihood;
vulnerability.risk = req.body.risk;
vulnerability.status = req.body.status;
vulnerability.description = req.body.description;
vulnerability.remediation = req.body.remediation;
vulnerability.jiraId = req.body.jiraId;
vulnerability.cvssScore = req.body.cvssScore;
vulnerability.cvssUrl = req.body.cvssUrl;
vulnerability.detailedInfo = req.body.detailedInfo;
vulnerability.assessment = assessment;
vulnerability.name = req.body.name;
vulnerability.systemic = req.body.systemic;
const errors = await validate(vulnerability);
if (errors.length > 0) {
return res.status(400).send('Vulnerability form validation failed');
} else {
await getConnection().getRepository(Vulnerability).save(vulnerability);
// Remove deleted files
if (req.body.screenshotsToDelete) {
const existingScreenshots = await getConnection()
.getRepository(File)
.find({ where: { vulnerability: vulnerability.id } });
const existingScreenshotIds = existingScreenshots.map(
(screenshot) => screenshot.id
);
let screenshotsToDelete = JSON.parse(req.body.screenshotsToDelete);
// We only want to remove the files associated to the vulnerability
screenshotsToDelete = existingScreenshotIds.filter((value) =>
screenshotsToDelete.includes(value)
);
for (const screenshotId of screenshotsToDelete) {
getConnection().getRepository(File).delete(screenshotId);
}
}
saveScreenshots(req.files, vulnerability, callback);
// Remove deleted problem locations
if (req.body.problemLocations.length) {
const clientProdLocs = JSON.parse(req.body.problemLocations);
const clientProdLocsIds = clientProdLocs.map((value) => value.id);
const existingProbLocs = await getConnection()
.getRepository(ProblemLocation)
.find({ where: { vulnerability: vulnerability.id } });
const existingProbLocIds = existingProbLocs.map((probLoc) => probLoc.id);
const prodLocsToDelete = existingProbLocIds.filter(
(value) => !clientProdLocsIds.includes(value)
);
for (const probLoc of prodLocsToDelete) {
getConnection().getRepository(ProblemLocation).delete(probLoc);
}
saveProblemLocations(clientProdLocs, vulnerability, callback);
}
// Remove deleted resources
if (req.body.resources.length) {
const clientResources = JSON.parse(req.body.resources);
const clientResourceIds = clientResources.map((value) => value.id);
const existingResources = await getConnection()
.getRepository(Resource)
.find({ where: { vulnerability: vulnerability.id } });
const existingResourceIds = existingResources.map(
(resource) => resource.id
);
const resourcesToDelete = existingResourceIds.filter(
(value) => !clientResourceIds.includes(value)
);
for (const resource of resourcesToDelete) {
getConnection().getRepository(Resource).delete(resource);
}
saveResources(clientResources, vulnerability, callback);
}
return res.status(200).json('Vulnerability patched successfully');
}
};
/**
* @description Create vulnerability
* @param {UserRequest} req
* @param {Response} res
* @returns success/error message
*/
export const createVuln = async (req: UserRequest, res: Response) => {
req = await fileUploadController.uploadFileArray(req, res);
if (isNaN(+req.body.assessment) || !req.body.assessment) {
return res.status(400).json('Invalid Assessment ID');
}
const assessment = await getConnection()
.getRepository(Assessment)
.findOne(req.body.assessment, { relations: ['asset'] });
if (!assessment) {
return res.status(404).json('Assessment does not exist');
}
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
const callback = (resStatus: number, message: any) => {
res.status(resStatus).send(message);
};
const vulnerability = new Vulnerability();
vulnerability.impact = req.body.impact;
vulnerability.likelihood = req.body.likelihood;
vulnerability.risk = req.body.risk;
vulnerability.status = req.body.status;
vulnerability.description = req.body.description;
vulnerability.remediation = req.body.remediation;
vulnerability.jiraId = req.body.jiraId;
vulnerability.cvssScore = req.body.cvssScore;
vulnerability.cvssUrl = req.body.cvssUrl;
vulnerability.detailedInfo = req.body.detailedInfo;
vulnerability.assessment = assessment;
vulnerability.name = req.body.name;
vulnerability.systemic = req.body.systemic;
const errors = await validate(vulnerability);
if (errors.length > 0) {
return res.status(400).send('Vulnerability form validation failed');
} else {
await getConnection().getRepository(Vulnerability).save(vulnerability);
saveScreenshots(req.files, vulnerability, callback);
const problemLocations = JSON.parse(req.body.problemLocations);
saveProblemLocations(problemLocations, vulnerability, callback);
const resources = JSON.parse(req.body.resources);
saveResources(resources, vulnerability, callback);
res.status(200).json('Vulnerability saved successfully');
}
};
/**
* @description Save screenshots to vulnerability
* @param {UserRequest} req
* @param {Response} res
* @param {Vulnerability} vulnerability
* @returns saved file or error message
*/
export const saveScreenshots = async (
files: File[],
vulnerability: Vulnerability,
callback
) => {
for (const screenshot of files) {
let file = new File();
file = screenshot;
file.vulnerability = vulnerability;
const fileErrors = await validate(file);
if (fileErrors.length > 0) {
return callback(400, JSON.stringify('File validation failed'));
} else {
await getConnection().getRepository(File).save(file);
}
}
};
/**
* @description Save problem locations to vulnerability
* @param {UserRequest} req
* @param {Response} res
* @param {Vulnerability} vulnerability
* @returns saved problem locations or error message
*/
export const saveProblemLocations = async (
problemLocations: ProblemLocation[],
vulnerability: Vulnerability,
callback
) => {
for (const probLoc of problemLocations) {
if (probLoc && probLoc.location && probLoc.target) {
let problemLocation = new ProblemLocation();
problemLocation = probLoc;
problemLocation.vulnerability = vulnerability;
const plErrors = await validate(problemLocation);
if (plErrors.length > 0) {
return callback(
400,
JSON.stringify('Problem Location validation failed')
);
} else {
await getConnection()
.getRepository(ProblemLocation)
.save(problemLocation);
}
} else {
return callback(400, JSON.stringify('Invalid Problem Location'));
}
}
};
/**
* @description Save resources to vulnerability
* @param {UserRequest} req
* @param {Response} res
* @param {Vulnerability} vulnerability
* @returns saved resources or error message
*/
export const saveResources = async (
resources: Resource[],
vulnerability: Vulnerability,
callback
) => {
for (const resource of resources) {
if (resource.description && resource.url) {
let newResource = new Resource();
newResource = resource;
newResource.vulnerability = vulnerability;
const nrErrors = await validate(newResource);
if (nrErrors.length > 0) {
return callback(
400,
JSON.stringify('Resource Location validation failed')
);
} else {
await getConnection().getRepository(Resource).save(newResource);
}
} else {
return callback(400, JSON.stringify('Resource Location Invalid'));
}
}
};
/**
* @description Generate JIRA Ticket from Vuln
* @param {UserRequest} req
* @param {Response} res
* @param {Vulnerability} vulnerability
* @returns JIRA return ID?
*/
export const exportToJira = async (req: UserRequest, res: Response) => {
if (!req.params.vulnId) {
return res.status(400).json('Invalid Vulnerability ID');
}
if (isNaN(+req.params.vulnId)) {
return res.status(400).json('Invalid Vulnerability ID');
}
const vuln = await getConnection()
.getRepository(Vulnerability)
.findOne(req.params.vulnId, {
relations: ['screenshots', 'resources', 'problemLocations', 'assessment'],
});
const assessment = await getConnection()
.getRepository(Assessment)
.findOne(vuln.assessment.id, { relations: ['asset'] });
const hasAccess = await hasAssetWriteAccess(req, assessment.asset.id);
if (!hasAccess) {
return res.status(403).json('Authorization is required');
}
const jira = await getConnection()
.getRepository(Jira)
.findOne({ where: { asset: assessment.asset } });
if (!assessment.jiraId) {
return res
.status(400)
.json(
'Unable to create JIRA ticket. Assessment requires an associated Jira ticket.'
);
}
if (!jira) {
return res
.status(400)
.json(
'Unable to create JIRA ticket. Please provide JIRA credentials to the parent Asset.'
);
}
const jiraInit: JiraInit = {
apiKey: jira.apiKey,
host: jira.host,
username: jira.username,
};
try {
const result = await exportToJiraIssue(vuln, jiraInit);
vuln.jiraId = `https://${jiraInit.host}/browse/${result.key}`;
await getConnection().getRepository(Vulnerability).save(vuln);
return res.status(200).json(`${result.message}`);
} catch (err) {
return res.status(404).json(err);
}
}; | the_stack |
import {Buffer} from 'buffer';
import {URL} from 'url';
import test from 'ava';
import delay from 'delay';
import getStream from 'get-stream';
import got, {Response} from '../source/index.js';
import withServer, {withBodyParsingServer} from './helpers/with-server.js';
import {ExtendedHttpTestServer} from './helpers/create-http-test-server.js';
const thrower = (): any => {
throw new Error('This should not be called');
};
const resetPagination = {
paginate: undefined,
transform: undefined,
filter: undefined,
shouldContinue: undefined,
};
// eslint-disable-next-line unicorn/no-object-as-default-parameter
const attachHandler = (server: ExtendedHttpTestServer, count: number, {relative} = {relative: false}): void => {
server.get('/', (request, response) => {
// eslint-disable-next-line unicorn/prevent-abbreviations
const searchParams = new URLSearchParams(request.url.split('?')[1]);
const page = Number(searchParams.get('page')) || 1;
if (page < count) {
response.setHeader('link', `<${relative ? '' : server.url}/?page=${page + 1}>; rel="next"`);
}
response.end(`[${page <= count ? page : ''}]`);
});
};
test('the link header has no next value', withServer, async (t, server, got) => {
const items = [1];
server.get('/', (_request, response) => {
response.setHeader('link', '<https://example.com>; rel="prev"');
response.end(JSON.stringify(items));
});
const received = await got.paginate.all<number>('');
t.deepEqual(received, items);
});
test('the link header is empty', withServer, async (t, server, got) => {
const items = [1];
server.get('/', (_request, response) => {
response.setHeader('link', '');
response.end(JSON.stringify(items));
});
const received = await got.paginate.all<number>('');
t.deepEqual(received, items);
});
test('retrieves all elements', withServer, async (t, server, got) => {
attachHandler(server, 2);
const result = await got.paginate.all<number>('');
t.deepEqual(result, [1, 2]);
});
test('retrieves all elements with JSON responseType', withServer, async (t, server, got) => {
attachHandler(server, 2);
const result = await got.extend({
responseType: 'json',
}).paginate.all<number>('');
t.deepEqual(result, [1, 2]);
});
test('points to defaults when extending Got without custom `pagination`', withServer, async (t, server, got) => {
attachHandler(server, 2);
const result = await got.extend().paginate.all<number>('');
t.deepEqual(result, [1, 2]);
});
test('pagination options can be extended', withServer, async (t, server, got) => {
attachHandler(server, 2);
const result = await got.extend({
pagination: {
shouldContinue: () => false,
},
}).paginate.all<number>('');
t.deepEqual(result, []);
});
test('filters elements', withServer, async (t, server, got) => {
attachHandler(server, 3);
const result = await got.paginate.all<number>({
pagination: {
filter: ({item, currentItems, allItems}) => {
t.true(Array.isArray(allItems));
t.true(Array.isArray(currentItems));
return item !== 2;
},
},
});
t.deepEqual(result, [1, 3]);
});
test('parses elements', withServer, async (t, server, got) => {
attachHandler(server, 100);
const result = await got.paginate.all<number, string>('?page=100', {
pagination: {
transform: response => [response.body.length],
},
});
t.deepEqual(result, [5]);
});
test('parses elements - async function', withServer, async (t, server, got) => {
attachHandler(server, 100);
const result = await got.paginate.all<number, string>('?page=100', {
pagination: {
transform: async response => [response.body.length],
},
});
t.deepEqual(result, [5]);
});
test('custom paginate function', withServer, async (t, server, got) => {
attachHandler(server, 3);
const result = await got.paginate.all<number>({
pagination: {
paginate: ({response}) => {
const url = new URL(response.url);
if (url.search === '?page=3') {
return false;
}
url.search = '?page=3';
return {url};
},
},
});
t.deepEqual(result, [1, 3]);
});
test('custom paginate function using allItems', withServer, async (t, server, got) => {
attachHandler(server, 3);
const result = await got.paginate.all<number>({
pagination: {
paginate: ({allItems, response}) => {
if (allItems.length === 2) {
return false;
}
return {
url: new URL('/?page=3', response.url),
};
},
stackAllItems: true,
},
});
t.deepEqual(result, [1, 3]);
});
test('custom paginate function using currentItems', withServer, async (t, server, got) => {
attachHandler(server, 3);
const result = await got.paginate.all<number>({
pagination: {
paginate: ({currentItems, response}) => {
if (currentItems[0] === 3) {
return false;
}
return {
url: new URL('/?page=3', response.url),
};
},
},
});
t.deepEqual(result, [1, 3]);
});
test('iterator works', withServer, async (t, server, got) => {
attachHandler(server, 5);
const results: number[] = [];
for await (const item of got.paginate<number>('')) {
results.push(item);
}
t.deepEqual(results, [1, 2, 3, 4, 5]);
});
test('iterator works #2', withServer, async (t, server, got) => {
attachHandler(server, 5);
const results: number[] = [];
for await (const item of got.paginate.each<number>('')) {
results.push(item);
}
t.deepEqual(results, [1, 2, 3, 4, 5]);
});
test('`shouldContinue` works', withServer, async (t, server, got) => {
attachHandler(server, 2);
const options = {
pagination: {
shouldContinue: ({currentItems, allItems}: {allItems: number[]; currentItems: number[]}) => {
t.true(Array.isArray(allItems));
t.true(Array.isArray(currentItems));
return false;
},
},
};
const results: number[] = [];
for await (const item of got.paginate<number>(options)) {
results.push(item);
}
t.deepEqual(results, []);
});
test('`countLimit` works', withServer, async (t, server, got) => {
attachHandler(server, 2);
const options = {
pagination: {
countLimit: 1,
},
};
const results: number[] = [];
for await (const item of got.paginate<number>(options)) {
results.push(item);
}
t.deepEqual(results, [1]);
});
test('throws if the `pagination` option does not have `transform` property', async t => {
const iterator = got.paginate('', {
pagination: {...resetPagination},
prefixUrl: 'https://example.com',
});
await t.throwsAsync(iterator.next(),
// {message: '`options.pagination.transform` must be implemented'}
);
});
test('throws if the `pagination` option does not have `shouldContinue` property', async t => {
const iterator = got.paginate('', {
pagination: {
...resetPagination,
transform: thrower,
},
prefixUrl: 'https://example.com',
});
await t.throwsAsync(iterator.next(),
// {message: '`options.pagination.shouldContinue` must be implemented'}
);
});
test('throws if the `pagination` option does not have `filter` property', async t => {
const iterator = got.paginate('', {
pagination: {
...resetPagination,
transform: thrower,
shouldContinue: thrower,
paginate: thrower,
},
prefixUrl: 'https://example.com',
});
await t.throwsAsync(iterator.next(),
// {message: '`options.pagination.filter` must be implemented'}
);
});
test('throws if the `pagination` option does not have `paginate` property', async t => {
const iterator = got.paginate('', {
pagination: {
...resetPagination,
transform: thrower,
shouldContinue: thrower,
filter: thrower,
},
prefixUrl: 'https://example.com',
});
await t.throwsAsync(iterator.next(),
// {message: '`options.pagination.paginate` must be implemented'}
);
});
test('ignores the `resolveBodyOnly` option', withServer, async (t, server, got) => {
attachHandler(server, 2);
const items = await got.paginate.all('', {
resolveBodyOnly: true,
});
t.deepEqual(items, [1, 2]);
});
test('allowGetBody sends json payload with .paginate()', withBodyParsingServer, async (t, server, got) => {
server.get('/', (request, response) => {
if (request.body.hello !== 'world') {
response.statusCode = 400;
}
response.end(JSON.stringify([1, 2, 3]));
});
const iterator = got.paginate<number>({
allowGetBody: true,
json: {hello: 'world'},
retry: {
limit: 0,
},
});
const results: number[] = [];
for await (const item of iterator) {
results.push(item);
}
t.deepEqual(results, [1, 2, 3]);
});
test('`hooks` are not duplicated', withServer, async (t, server, got) => {
let page = 1;
server.get('/', (_request, response) => {
response.end(JSON.stringify([page++]));
});
const nopHook = () => {};
const result = await got.paginate.all<number>({
pagination: {
paginate: ({response}) => {
if ((response.body as string) === '[3]') {
return false; // Stop after page 3
}
const {options} = response.request;
const {init, beforeRequest, beforeRedirect, beforeRetry, afterResponse, beforeError} = options.hooks;
const hooksCount = [init, beforeRequest, beforeRedirect, beforeRetry, afterResponse, beforeError].map(a => a.length);
t.deepEqual(hooksCount, [1, 1, 1, 1, 1, 1]);
return options;
},
},
hooks: {
init: [nopHook],
beforeRequest: [nopHook],
beforeRedirect: [nopHook],
beforeRetry: [nopHook],
afterResponse: [response => response],
beforeError: [error => error],
},
});
t.deepEqual(result, [1, 2, 3]);
});
test('allowGetBody sends correct json payload with .paginate()', withServer, async (t, server, got) => {
let page = 1;
server.get('/', async (request, response) => {
const payload = await getStream(request);
try {
JSON.parse(payload);
} catch {
response.statusCode = 422;
}
if (request.headers['content-length']) {
t.is(Number(request.headers['content-length'] || 0), Buffer.byteLength(payload));
}
response.end(JSON.stringify([page++]));
});
let body = '';
const iterator = got.paginate<number>({
allowGetBody: true,
retry: {
limit: 0,
},
json: {body},
pagination: {
paginate: () => {
if (body.length === 2) {
return false;
}
body += 'a';
return {
json: {body},
};
},
},
});
const results: number[] = [];
for await (const item of iterator) {
results.push(item);
}
t.deepEqual(results, [1, 2, 3]);
});
test('`requestLimit` works', withServer, async (t, server, got) => {
attachHandler(server, 2);
const options = {
pagination: {
requestLimit: 1,
},
};
const results: number[] = [];
for await (const item of got.paginate<number>(options)) {
results.push(item);
}
t.deepEqual(results, [1]);
});
test('`backoff` works', withServer, async (t, server, got) => {
attachHandler(server, 2);
const backoff = 200;
const asyncIterator: AsyncIterator<number> = got.paginate<number>('', {
pagination: {
backoff,
},
});
t.is((await asyncIterator.next()).value, 1);
let receivedLastOne = false;
const start = Date.now();
const promise = asyncIterator.next();
(async () => {
await promise;
receivedLastOne = true;
})();
await delay(backoff / 2);
t.false(receivedLastOne);
await promise;
t.true(Date.now() - start >= backoff);
});
test('`stackAllItems` set to true', withServer, async (t, server, got) => {
attachHandler(server, 3);
let itemCount = 0;
const result = await got.paginate.all<number>({
pagination: {
stackAllItems: true,
filter: ({allItems}) => {
t.is(allItems.length, itemCount);
return true;
},
shouldContinue: ({allItems}) => {
t.is(allItems.length, itemCount);
return true;
},
paginate: ({response, currentItems, allItems}) => {
itemCount += 1;
t.is(allItems.length, itemCount);
return got.defaults.options.pagination.paginate!({response, currentItems, allItems});
},
},
});
t.deepEqual(result, [1, 2, 3]);
});
test('`stackAllItems` set to false', withServer, async (t, server, got) => {
attachHandler(server, 3);
const result = await got.paginate.all<number>({
pagination: {
stackAllItems: false,
filter: ({allItems}) => {
t.is(allItems.length, 0);
return true;
},
shouldContinue: ({allItems}) => {
t.is(allItems.length, 0);
return true;
},
paginate: ({response, currentItems, allItems}) => {
t.is(allItems.length, 0);
return got.defaults.options.pagination.paginate!({response, allItems, currentItems});
},
},
});
t.deepEqual(result, [1, 2, 3]);
});
test('next url in json response', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
const parameters = new URLSearchParams(request.url.slice(2));
const page = Number(parameters.get('page') ?? 0);
response.end(JSON.stringify({
currentUrl: request.url,
next: page < 3 ? `${server.url}/?page=${page + 1}` : undefined,
}));
});
interface Page {
currentUrl: string;
next?: string;
}
const all = await got.paginate.all('', {
searchParams: {
page: 0,
},
responseType: 'json',
pagination: {
transform: (response: Response<Page>) => [response.body.currentUrl],
paginate: ({response}) => {
const {next} = response.body;
if (!next) {
return false;
}
return {
url: new URL(next),
prefixUrl: '',
searchParams: undefined,
};
},
},
});
t.deepEqual(all, [
'/?page=0',
'/?page=1',
'/?page=2',
'/?page=3',
]);
});
test('pagination using searchParams', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
const parameters = new URLSearchParams(request.url.slice(2));
const page = Number(parameters.get('page') ?? 0);
response.end(JSON.stringify({
currentUrl: request.url,
next: page < 3,
}));
});
interface Page {
currentUrl: string;
next?: string;
}
const all = await got.paginate.all('', {
searchParams: {
page: 0,
},
responseType: 'json',
pagination: {
transform: (response: Response<Page>) => [response.body.currentUrl],
paginate: ({response}) => {
const {next} = response.body;
// eslint-disable-next-line unicorn/prevent-abbreviations
const searchParams = response.request.options.searchParams as URLSearchParams;
const previousPage = Number(searchParams.get('page'));
if (!next) {
return false;
}
return {
searchParams: {
page: previousPage + 1,
},
};
},
},
});
t.deepEqual(all, [
'/?page=0',
'/?page=1',
'/?page=2',
'/?page=3',
]);
});
test('pagination using extended searchParams', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
const parameters = new URLSearchParams(request.url.slice(2));
const page = Number(parameters.get('page') ?? 0);
response.end(JSON.stringify({
currentUrl: request.url,
next: page < 3,
}));
});
interface Page {
currentUrl: string;
next?: string;
}
const client = got.extend({
searchParams: {
limit: 10,
},
});
const all = await client.paginate.all('', {
searchParams: {
page: 0,
},
responseType: 'json',
pagination: {
transform: (response: Response<Page>) => [response.body.currentUrl],
paginate: ({response}) => {
const {next} = response.body;
// eslint-disable-next-line unicorn/prevent-abbreviations
const searchParams = response.request.options.searchParams as URLSearchParams;
const previousPage = Number(searchParams.get('page'));
if (!next) {
return false;
}
return {
searchParams: {
page: previousPage + 1,
},
};
},
},
});
t.is(all.length, 4);
for (let i = 0; i < 4; i++) {
t.true(all[i] === `/?page=${i}&limit=10` || all[i] === `/?limit=10&page=${i}`);
}
});
test('calls init hooks on pagination', withServer, async (t, server) => {
server.get('/', (request, response) => {
response.end(JSON.stringify([request.url]));
});
const instance = got.extend({
hooks: {
init: [
options => {
options.searchParams = 'foobar';
},
],
},
});
const received = await instance.paginate.all<string>(server.url, {
searchParams: 'unicorn',
});
t.deepEqual(received, [
'/?foobar=',
]);
});
test('retrieves all elements - relative url', withServer, async (t, server, got) => {
attachHandler(server, 2, {relative: true});
const result = await got.paginate.all<number>('');
t.deepEqual(result, [1, 2]);
});
test('throws if url is not an instance of URL', withServer, async (t, server, got) => {
attachHandler(server, 2);
await t.throwsAsync(got.paginate.all<number>('', {
pagination: {
paginate: () => ({
url: 'not an instance of URL',
}),
},
}), {
instanceOf: TypeError,
});
});
test('throws when transform does not return an array', withServer, async (t, server) => {
server.get('/', (_request, response) => {
response.end(JSON.stringify(''));
});
await t.throwsAsync(got.paginate.all<string>(server.url));
// TODO: Add assert message above.
}); | the_stack |
import DocumentSearch from '@/views/DocumentSearch.vue'
import {afterEach, beforeEach, describe, expect, jest, test} from '@jest/globals'
import {shallowMount, Wrapper} from '@vue/test-utils'
import axios from 'axios'
import Vue from 'vue'
import {ACLProfile, BasicDocument, Branch, FlowControlPolicy, RateLimit, GlobalFilter, SecurityPolicy, WAFPolicy} from '@/types'
jest.useFakeTimers()
jest.mock('axios')
describe('DocumentSearch.vue', () => {
let wrapper: Wrapper<Vue>
let mockRouter
let gitData: Branch[]
let aclDocs: ACLProfile[]
let profilingListDocs: GlobalFilter[]
let securityPoliciesDocs: SecurityPolicy[]
let flowControlPolicyDocs: FlowControlPolicy[]
let rateLimitDocs: RateLimit[]
let wafDocs: WAFPolicy[]
beforeEach((done) => {
gitData = [
{
'id': 'master',
'description': 'Update entry [__default__] of document [aclprofiles]',
'date': '2020-11-10T15:49:17+02:00',
'logs': [
{
'version': '7dd9580c00bef1049ee9a531afb13db9ef3ee956',
'date': '2020-11-10T15:49:17+02:00',
'parents': [
'fc47a6cd9d7f254dd97875a04b87165cc484e075',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': 'fc47a6cd9d7f254dd97875a04b87165cc484e075',
'date': '2020-11-10T15:48:35+02:00',
'parents': [
'5aba4a5b9d6faea1896ee8965c7aa651f76af63c',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '5aba4a5b9d6faea1896ee8965c7aa651f76af63c',
'date': '2020-11-10T15:48:31+02:00',
'parents': [
'277c5d7bd0e2eb4b9d2944f7eefdfadf37ba8581',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '277c5d7bd0e2eb4b9d2944f7eefdfadf37ba8581',
'date': '2020-11-10T15:48:22+02:00',
'parents': [
'878b47deeddac94625fe7c759786f2df885ec541',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '878b47deeddac94625fe7c759786f2df885ec541',
'date': '2020-11-10T15:48:05+02:00',
'parents': [
'93c180513fe7edeaf1c0ca69a67aa2a11374da4f',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '93c180513fe7edeaf1c0ca69a67aa2a11374da4f',
'date': '2020-11-10T15:47:59+02:00',
'parents': [
'1662043d2a18d6ad2c9c94d6f826593ff5506354',
],
'message': 'Update entry [__default__] of document [aclprofiles]',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '1662043d2a18d6ad2c9c94d6f826593ff5506354',
'date': '2020-11-08T21:31:41+01:00',
'parents': [
'16379cdf39501574b4a2f5a227b82a4454884b84',
],
'message': 'Create config [master]\n',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': '16379cdf39501574b4a2f5a227b82a4454884b84',
'date': '2020-08-27T16:19:06+00:00',
'parents': [
'a34f979217215060861b58b3f270e82580c20efb',
],
'message': 'Initial empty config',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
{
'version': 'a34f979217215060861b58b3f270e82580c20efb',
'date': '2020-08-27T16:19:06+00:00',
'parents': [],
'message': 'Initial empty content',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
],
'version': '7dd9580c00bef1049ee9a531afb13db9ef3ee956',
},
{
'id': 'zzz_branch',
'description': 'Initial empty content',
'date': '2020-08-27T16:19:06+00:00',
'logs': [
{
'version': 'a34f979217215060861b58b3f270e82580c20efb',
'date': '2020-08-27T16:19:06+00:00',
'parents': [],
'message': 'Initial empty content',
'email': 'curiefense@reblaze.com',
'author': 'Curiefense API',
},
],
'version': 'a34f979217215060861b58b3f270e82580c20efb',
},
]
aclDocs = [
{
'id': '__default__',
'name': 'default-acl',
'allow': [],
'allow_bot': [
'google',
],
'deny_bot': [],
'passthrough': [
'internal',
],
'deny': [
'tor',
],
'force_deny': [
'china',
],
},
{
'id': '5828321c37e0',
'name': 'an ACL',
'allow': [],
'allow_bot': [
'google',
'yahoo',
],
'deny_bot': [],
'passthrough': [
'devops',
],
'deny': [
'tor',
],
'force_deny': [
'iran',
],
},
]
profilingListDocs = [
{
'id': 'xlbp148c',
'name': 'API Discovery',
'source': 'self-managed',
'mdate': '2020-05-23T00:04:41',
'description': 'Default Tag API Requests',
'active': true,
'tags': ['api'],
'action': {
'type': 'monitor',
'params': {},
},
'rule': {
'relation': 'OR',
'sections': [
{
'relation': 'OR', 'entries': [
[
'headers',
[
'content-type',
'.*/(json|xml)',
],
'content type',
],
[
'headers',
[
'host',
'.?ap[ip]\\.',
],
'app or api in domain name',
],
[
'method',
'(POST|PUT|DELETE|PATCH)',
'Methods',
],
[
'path',
'/api/',
'api path',
],
[
'uri',
'/.+\\.json',
'URI JSON extention',
],
],
},
],
},
}, {
'id': '07656fbe',
'name': 'devop internal demo',
'source': 'self-managed',
'mdate': '2020-05-23T00:04:41',
'description': 'this is my own list',
'active': false,
'tags': ['internal', 'devops'],
'action': {
'type': 'monitor',
'params': {},
},
'rule': {
'relation': 'OR',
'sections': [
{'relation': 'OR', 'entries': [['ip', '1.1.1.1', null]]},
{'relation': 'OR', 'entries': [['ip', '2.2.2.2', null]]},
{'relation': 'OR', 'entries': [['headers', ['headerrr', 'valueeee'], 'anooo']]}],
},
},
]
securityPoliciesDocs = [
{
'id': '__default__',
'name': 'default entry',
'match': '__default__',
'map': [
{
'name': 'default',
'match': '/',
'acl_profile': '5828321c37e0',
'acl_active': false,
'waf_profile': '__default__',
'waf_active': false,
'limit_ids': ['f971e92459e2'],
},
{
'name': 'name',
'match': '/foo',
'acl_profile': '__default__',
'acl_active': false,
'waf_profile': '__default__',
'waf_active': false,
'limit_ids': ['f971e92459e2'],
},
{
'name': 'name',
'match': '/foo',
'acl_profile': '__default__',
'acl_active': false,
'waf_profile': '__default__',
'waf_active': false,
'limit_ids': ['f971e92459e2'],
},
],
},
]
flowControlPolicyDocs = [
{
'active': true,
'description': '',
'exclude': [],
'include': ['all'],
'name': 'flow control policy',
'key': [
{'headers': 'something'},
],
'sequence': [
{
'method': 'GET',
'uri': '/login',
'cookies': {
'foo': 'bar',
},
'headers': {},
'args': {},
},
{
'method': 'POST',
'uri': '/login',
'cookies': {
'foo': 'bar',
},
'headers': {
'test': 'one',
},
'args': {},
},
],
'action': {
'type': 'default',
'params': {},
},
'timeframe': 60,
'id': 'c03dabe4b9ca',
},
]
rateLimitDocs = [
{
'id': 'f971e92459e2',
'name': 'Rate Limit Example Rule 5/60',
'description': '5 requests per minute',
'timeframe': '60',
'limit': '5',
'action': {'type': 'default'},
'include': ['badpeople'],
'exclude': ['goodpeople'],
'key': [{'attrs': 'ip'}],
'pairwith': {'self': 'self'},
},
]
wafDocs = [
{
'id': '01b2abccc275',
'name': 'default waf',
'ignore_alphanum': true,
'max_header_length': 1024,
'max_cookie_length': 1024,
'max_arg_length': 1024,
'max_headers_count': 42,
'max_cookies_count': 42,
'max_args_count': 512,
'args': {'names': [], 'regex': []},
'headers': {'names': [], 'regex': []},
'cookies': {'names': [], 'regex': []},
},
]
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/configs/') {
return Promise.resolve({data: gitData})
}
const branch = (wrapper.vm as any).selectedBranch
if (path === `/conf/api/v2/configs/${branch}/d/aclprofiles/`) {
return Promise.resolve({data: aclDocs})
}
if (path === `/conf/api/v2/configs/${branch}/d/globalfilters/`) {
return Promise.resolve({data: profilingListDocs})
}
if (path === `/conf/api/v2/configs/${branch}/d/securitypolicies/`) {
return Promise.resolve({data: securityPoliciesDocs})
}
if (path === `/conf/api/v2/configs/${branch}/d/flowcontrol/`) {
return Promise.resolve({data: flowControlPolicyDocs})
}
if (path === `/conf/api/v2/configs/${branch}/d/ratelimits/`) {
return Promise.resolve({data: rateLimitDocs})
}
if (path === `/conf/api/v2/configs/${branch}/d/wafpolicies/`) {
return Promise.resolve({data: wafDocs})
}
return Promise.resolve({data: []})
})
mockRouter = {
push: jest.fn(),
}
wrapper = shallowMount(DocumentSearch, {
mocks: {
$router: mockRouter,
},
})
// allow all requests to finish
setImmediate(() => {
done()
})
})
afterEach(() => {
jest.clearAllMocks()
})
function isItemInFilteredDocs(item: BasicDocument, doctype: string) {
const isInModel = (wrapper.vm as any).filteredDocs.some((doc: any) => {
return doc.id === item.id && doc.docType === doctype
})
const isInView = wrapper.findAll('.doc-id-cell').filter((w) => {
return w.text().includes(item.id)
}).length > 0
return isInModel && isInView
}
function numberOfFilteredDocs() {
return wrapper.findAll('.result-row').length
}
test('should be able to switch branches through dropdown', (done) => {
const branchSelection = wrapper.find('.branch-selection')
branchSelection.trigger('click')
const options = branchSelection.findAll('option')
options.at(1).setSelected()
// allow all requests to finish
setImmediate(() => {
expect((branchSelection.element as HTMLSelectElement).selectedIndex).toEqual(1)
done()
})
})
test('should display all documents on startup', () => {
expect(isItemInFilteredDocs(aclDocs[0], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(aclDocs[1], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(profilingListDocs[0], 'globalfilters')).toBeTruthy()
expect(isItemInFilteredDocs(profilingListDocs[1], 'globalfilters')).toBeTruthy()
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(isItemInFilteredDocs(flowControlPolicyDocs[0], 'flowcontrol')).toBeTruthy()
expect(isItemInFilteredDocs(wafDocs[0], 'wafpolicies')).toBeTruthy()
expect(isItemInFilteredDocs(rateLimitDocs[0], 'ratelimits')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(8)
})
test('should log message when receiving no configs from the server', (done) => {
const originalLog = console.log
let consoleOutput = [] as string[]
const mockedLog = (output: string) => consoleOutput.push(output)
consoleOutput = []
console.log = mockedLog
jest.spyOn(axios, 'get').mockImplementation((path) => {
if (path === '/conf/api/v2/configs/') {
return Promise.reject(new Error())
}
return Promise.resolve({data: {}})
})
wrapper = shallowMount(DocumentSearch)
// allow all requests to finish
setImmediate(() => {
expect(consoleOutput).toContain(`Error while attempting to get configs`)
console.log = originalLog
done()
})
})
test('should not display duplicated values in connections even if connected twice', async () => {
const wantedIDsACL = ['5828321c37e0', '__default__']
const wantedIDsWAF = ['__default__']
const wantedIDsRateLimit = ['f971e92459e2']
// switch filter type to security policy
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(1).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
// Using a partial name instead of 'security policy'
// The search is executing a RegEx which means 'securitypolicies' would not
// match 'security policies'
(searchInput.element as HTMLInputElement).value = 'security pol'
searchInput.trigger('input')
await Vue.nextTick()
// Get connections cell
const connectionsCell = wrapper.find('.doc-connections-cell')
const doc = (wrapper.vm as any).filteredDocs[0]
// check that security policy exists without duplicated connections
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(connectionsCell.text()).toContain(`ACL Profiles:${wantedIDsACL.join('')}`)
expect(connectionsCell.text()).toContain(`WAF Policies:${wantedIDsWAF.join('')}`)
expect(connectionsCell.text()).toContain(`Rate Limits:${wantedIDsRateLimit.join('')}`)
expect(doc.connectedACL).toEqual(wantedIDsACL)
expect(doc.connectedWAF).toEqual(wantedIDsWAF)
expect(doc.connectedRateLimits).toEqual(wantedIDsRateLimit)
})
describe('filters', () => {
test('should filter correctly if filter changed after input', async () => {
// switch filter type
let searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
let options = searchTypeSelection.findAll('option')
options.at(1).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'default'
searchInput.trigger('input')
await Vue.nextTick()
// switch filter type
searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
options = searchTypeSelection.findAll('option')
options.at(0).setSelected()
await Vue.nextTick()
expect(isItemInFilteredDocs(aclDocs[0], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(aclDocs[1], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(profilingListDocs[0], 'globalfilters')).toBeTruthy()
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(isItemInFilteredDocs(wafDocs[0], 'wafpolicies')).toBeTruthy()
expect(isItemInFilteredDocs(rateLimitDocs[0], 'ratelimits')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(6)
})
test('should filter correctly with filter all', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(0).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'default'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(aclDocs[0], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(aclDocs[1], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(profilingListDocs[0], 'globalfilters')).toBeTruthy()
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(isItemInFilteredDocs(wafDocs[0], 'wafpolicies')).toBeTruthy()
expect(isItemInFilteredDocs(rateLimitDocs[0], 'ratelimits')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(6)
})
test('should filter correctly with filter document type', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(1).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'flow'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(flowControlPolicyDocs[0], 'flowcontrol')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(1)
})
test('should filter correctly with filter id', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(2).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'c03dabe4b9ca'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(flowControlPolicyDocs[0], 'flowcontrol')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(1)
})
test('should filter correctly with filter name', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(3).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'default entry'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(1)
})
test('should filter correctly with filter description', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(4).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'default'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(profilingListDocs[0], 'globalfilters')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(1)
})
test('should filter correctly with filter tags', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(5).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'china'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(aclDocs[0], 'aclprofiles')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(1)
})
test('should filter correctly with filter connections', async () => {
// switch filter type
const searchTypeSelection = wrapper.find('.search-type-selection')
searchTypeSelection.trigger('click')
const options = searchTypeSelection.findAll('option')
options.at(6).setSelected()
await Vue.nextTick()
const searchInput = wrapper.find('.search-input');
(searchInput.element as HTMLInputElement).value = 'default'
searchInput.trigger('input')
await Vue.nextTick()
expect(isItemInFilteredDocs(aclDocs[1], 'aclprofiles')).toBeTruthy()
expect(isItemInFilteredDocs(securityPoliciesDocs[0], 'securitypolicies')).toBeTruthy()
expect(isItemInFilteredDocs(rateLimitDocs[0], 'ratelimits')).toBeTruthy()
expect(numberOfFilteredDocs()).toEqual(3)
})
})
describe('go to link', () => {
test('should not render go to link button when not hovering over a row', () => {
expect(wrapper.findAll('.go-to-link-button').length).toEqual(0)
})
test('should render a single go to link button when hovering over a row', async () => {
// 0 is the table header, 1 is our first data
const firstDataRow = wrapper.findAll('tr').at(1)
await firstDataRow.trigger('mouseover')
expect(firstDataRow.findAll('.go-to-link-button').length).toEqual(1)
})
test('should stop rendering the go to link button when no longer hovering over a row', async () => {
// 0 is the table header, 1 is our first data
const firstDataRow = wrapper.findAll('tr').at(1)
await firstDataRow.trigger('mouseover')
await firstDataRow.trigger('mouseleave')
expect(firstDataRow.findAll('.go-to-link-button').length).toEqual(0)
})
test('should change route when go to link button is clicked', async () => {
// 0 is the table header, 1 is our first data
const firstDataRow = wrapper.findAll('tr').at(1)
await firstDataRow.trigger('mouseover')
const goToLinkButton = firstDataRow.find('.go-to-link-button')
await goToLinkButton.trigger('click')
expect(mockRouter.push).toHaveBeenCalledTimes(1)
expect(mockRouter.push).toHaveBeenCalledWith('/config/master/securitypolicies/__default__')
})
})
}) | the_stack |
import './swiper.css';
import { Device } from './device';
import { DeviceEvent } from './device';
import {EMPTY_FUNCTION, EMPTY_PAGE, OPPSITE} from './constant';
import {Direction, Axis, Point, Vector, Transition, Page, $Page, Options, Listeners} from './interface';
import Easing from './easing';
import Render from './render';
import Slide from './renders/slide';
import Rotate from './renders/rotate';
import Flip from './renders/flip';
import Card from './renders/card';
import Fade from './renders/fade';
import Dumi from './renders/dumi';
Render.register('slide', Slide);
Render.register('rotate', Rotate);
Render.register('flip', Flip);
Render.register('card', Card);
Render.register('fade', Fade);
Render.register('dumi', Dumi);
export class Swiper {
static Events: string[] = [
'swipeBeforeStart',
'swipeStart',
'swipeMoving',
'swipeChanged',
'swipeRestore',
'swipeRestored',
'activePageChanged',
'destroy'
];
static Device = new Device(window);
static DefaultOptions: Options = {
container: document.body,
data: [],
debug: false,
isVertical: true,
isLoop: false,
initIndex: 0,
keepDefaultClasses: [],
transition: {
name: 'slide',
duration: 800
}
}
private $container: HTMLElement;
private debug: boolean;
private data: Page[];
private axis: Axis;
private isLoop: boolean;
private initIndex: number;
private keepDefaultClasses: string[];
private sideLength: number;
private transition: Transition;
private _listeners: Listeners;
// runtime member
private $swiper: HTMLElement;
private $pages: $Page[];
private startTime: number;
private endTime: number;
private sliding: boolean;
private moving: boolean;
private start: Point;
private end: Point;
private offset: Vector;
private pageChange: boolean;
private moveDirection: Direction;
private currentPage: $Page;
private activePage: $Page;
private lastActivePage: $Page;
private renderInstance: Render;
// auxiliary
public log: Function;
constructor(options: Options) {
options = {
...Swiper.DefaultOptions,
...options
};
options.transition = {
...Swiper.DefaultOptions.transition,
...options.transition
};
this.$container = options.container;
this.debug = options.debug;
this.data = options.data;
this.axis = options.isVertical ? 'Y' : 'X';
this.isLoop = options.isLoop;
this.initIndex = options.initIndex;
this.keepDefaultClasses = options.keepDefaultClasses;
this.sideLength = this.axis === 'X' ? this.$container.clientWidth : this.$container.clientHeight;
this.transition = options.transition;
this._listeners = {};
// runtime variable
this.sliding = false;
this.moving = false;
this.pageChange = false;
this.moveDirection = Direction.Nonward;
this.activePage = EMPTY_PAGE;
this.lastActivePage = EMPTY_PAGE;
this.start = {X: 0, Y: 0};
this.end = {X: 0, Y: 0};
this.offset = {X: 0, Y:0};
this.log = this.debug ? console.log.bind(window.console) : EMPTY_FUNCTION;
this.bindEvents();
this.initRender();
}
private bindEvents() {
this.$container.addEventListener(Swiper.Device.startEvent, this, <any>{passive: false});
this.$container.addEventListener(Swiper.Device.moveEvent, this, <any>{passive: false});
this.$container.addEventListener(Swiper.Device.transitionEvent, this, <any>{passive: false});
window.addEventListener(Swiper.Device.endEvent, this, <any>{passive: false});
window.addEventListener(Swiper.Device.resizeEvent, this, false);
}
private unbindEvents() {
this.$container.removeEventListener(Swiper.Device.startEvent, this, <any>{passive: false});
this.$container.removeEventListener(Swiper.Device.moveEvent, this, <any>{passive: false});
this.$container.removeEventListener(Swiper.Device.transitionEvent, this, <any>{passive: false});
window.removeEventListener(Swiper.Device.endEvent, this, <any>{passive: false});
window.removeEventListener(Swiper.Device.resizeEvent, this, false);
}
handleEvent(event: any) {
let deviceEvent = Swiper.Device.getDeviceEvent(event);
switch (deviceEvent.type) {
case 'mousedown':
// block mouse buttons except left
if (deviceEvent.button !== 0) {
break;
}
case 'touchstart':
this.keepDefaultHandler(deviceEvent);
this.startHandler(deviceEvent.position);
break;
case Swiper.Device.moveEvent:
this.keepDefaultHandler(deviceEvent);
this.moveHandler(deviceEvent.position);
break;
case Swiper.Device.endEvent:
case Swiper.Device.cancelEvent:
// mouseout, touchcancel event, trigger endEvent
this.endHandler();
break;
case Swiper.Device.resizeEvent:
this.resizeHandler();
break;
case Swiper.Device.transitionEvent:
this.transitionEndHandler(deviceEvent);
break;
default:
break;
}
}
private keepDefaultHandler(event: DeviceEvent): void {
if (event.target && /^(input|textarea|a|select)$/i.test(event.target.tagName)) {
return;
}
let keepDefaultClasses = this.keepDefaultClasses;
for (let keepDefaultClass of keepDefaultClasses) {
for (let e = event.target; e !== null; e = e.parentElement) {
if (e.classList.contains(keepDefaultClass)) {
return;
}
}
}
event.preventDefault();
}
private startHandler(startPosition: Point) {
if (this.sliding) {
return;
}
this.log('start');
this.moving = true;
this.startTime = new Date().getTime();
this.start = startPosition;
// 设置翻页动画
this.transition = {...this.transition, ...this.currentPage.transition};
this.renderInstance = Render.getRenderInstance(this.transition.name);
if (this.transition.direction === Direction.Nonward) {
return;
}
this.fire('swipeStart');
}
private moveHandler(movingPosition: Point) {
if (this.sliding || !this.moving || this.transition.direction === Direction.Nonward) {
return;
}
this.log('moving');
this.end = movingPosition;
this.offset = {
X: this.end.X - this.start.X,
Y: this.end.Y - this.start.Y
};
if (this.offset[this.axis] < 0) {
this.moveDirection = Direction.Forward;
this.lastActivePage = this.activePage;
this.activePage = this.currentPage.next;
}
else if (this.offset[this.axis] > 0) {
this.moveDirection = Direction.Backward;
this.lastActivePage = this.activePage;
this.activePage = this.currentPage.prev;
}
else {
this.moveDirection = Direction.Nonward;
this.lastActivePage = this.activePage;
this.activePage = EMPTY_PAGE;
}
this.fire('swipeMoving');
if (this.activePage !== this.lastActivePage && this.activePage !== EMPTY_PAGE) {
this.fire('activePageChanged');
}
// 页面禁止滑动时
// 防止突然「先上后下」,直接将 this.offset 置为 0
// 防止需要「等」 offset 归 0 后才能往上走
if (this.transition.direction && this.transition.direction !== this.moveDirection) {
this.offset[this.axis] = 0;
this.start = this.end;
}
const GAP = {
Forward: 20,
Backward: this.sideLength - 20
};
let directionKey = Direction[this.moveDirection];
if (this.moveDirection * this.end[this.axis] > this.moveDirection * GAP[directionKey]) {
let logStr = this.moveDirection === Direction.Forward ? '<--- near edge' : 'near edge --->';
this.log(logStr);
return this.endHandler();
}
// activePage 为 EMPTY_PAGE 需要渲染,比如快速滑动最后一帧
// 翻页时长为 0 时不渲染,但是需要在上面判断是否在边界附近
if (this.transition.duration !== 0) {
this.render();
}
}
private endHandler() {
if (this.sliding || !this.moving || this.transition.direction === Direction.Nonward) {
return;
}
this.moving = false;
this.log('end');
// 如果禁止滑动
if (this.transition.direction && this.transition.direction !== this.moveDirection) {
this.offset[this.axis] = 0;
}
this.endTime = new Date().getTime();
let moveTime: number = this.endTime - this.startTime;
let threshold: number = moveTime > 300 ? this.sideLength / 3 : 14;
let sideOffset: number = this.offset[this.axis];
let absOffset: number = Math.abs(this.offset[this.axis]);
let absReverseOffset: number = Math.abs(this.offset[OPPSITE[this.axis]]);
// 是在沿着 axis 滑动
let isSwipeOnTheDir: boolean = absReverseOffset < absOffset;
if (absOffset >= threshold && isSwipeOnTheDir && this.activePage !== EMPTY_PAGE) {
this.pageChange = true;
this._swipeTo();
}
else {
this.pageChange = false;
this._swipeTo();
this.fire('swipeRestore');
}
}
private resizeHandler() {
if (!this.sliding && !this.moving) {
this.sideLength = this.axis === 'X' ? this.$container.clientWidth : this.$container.clientHeight;
}
}
private transitionEndHandler(event?: DeviceEvent) {
if (event && event.target !== this.currentPage) {
return;
}
this.$swiper.style.cssText = '';
this.currentPage.style.cssText = '';
this.activePage.style.cssText = '';
// 回弹
if (this.pageChange === false) {
this.activePage.classList.remove('active')
this.fire('swipeRestored');
}
// 正常翻页
else {
this.currentPage.classList.remove('current');
this.activePage.classList.remove('active')
this.activePage.classList.add('current');
this.currentPage = this.activePage;
this.fire('swipeChanged');
}
this.activePage = EMPTY_PAGE;
this.lastActivePage = EMPTY_PAGE;
this.offset.X = 0;
this.offset.Y = 0;
this.sliding = false;
this.pageChange = false;
}
public swipeTo(toIndex: number, transition?: Transition) {
if (this.sliding) {
return;
}
let currentIndex = this.currentPage.index;
this.moveDirection = Direction.Nonward;
this.pageChange = true;
if (toIndex > currentIndex) {
this.moveDirection = Direction.Forward;
}
else if (toIndex < currentIndex) {
this.moveDirection = Direction.Backward;
}
let activeIndex = this.isLoop ? (toIndex + this.data.length) % this.data.length : toIndex;
this.activePage = this.$pages[activeIndex] || EMPTY_PAGE;
// if the same, do nothing
if (activeIndex === currentIndex || this.activePage === EMPTY_PAGE) {
this.pageChange = false;
}
this.transition = {...this.transition, ...this.currentPage.transition, ...transition};
this.renderInstance = Render.getRenderInstance(this.transition.name);
// 外部调用仍然需要 fire activePageChanged 事件
this.fire('activePageChanged');
this.render();
this._swipeTo();
}
public swipePrev(transition?: Transition) {
var currentIndex = this.currentPage.index;
this.swipeTo(currentIndex - 1, transition);
}
public swipeNext(transition?: Transition) {
var currentIndex = this.currentPage.index;
this.swipeTo(currentIndex + 1, transition);
}
public getCurrentIndex(): number {
return this.currentPage.index;
}
private _swipeTo() {
if (this.sliding) {
return;
}
this.sliding = true;
let duration = this.activePage === EMPTY_PAGE ? 300 : this.transition.duration;
let elapsedTime = Math.abs(this.offset[this.axis]) / this.sideLength * duration;
let remainingTime = duration - elapsedTime;
let animateTime = this.pageChange ? remainingTime : elapsedTime;
let endOffset = this.pageChange ? this.moveDirection * this.sideLength : 0;
if (animateTime === 0) {
return this.transitionEndHandler();
}
// force the animation works
setTimeout(function () {
this.currentPage.style.webkitTransition = `ease-out ${animateTime}ms`;
if (this.activePage !== EMPTY_PAGE) {
this.activePage.style.webkitTransition = `ease-out ${animateTime}ms`;
}
// set final offset
this.offset[this.axis] = endOffset;
this.render();
}.bind(this), 30);
}
private initRender() {
this.$swiper = document.createElement('div');
this.$swiper.classList.add('lg-swiper');
this.$pages = this.data.map((page, index) => {
let $page: $Page = <$Page>document.createElement('div');
$page.classList.add('lg-swiper-page');
if(typeof page.content === 'string'){
$page.innerHTML = page.content;
}else{
$page.appendChild(page.content);
}
$page.index = index;
$page.transition = page.transition
if (this.initIndex === index) {
$page.classList.add('current');
this.currentPage = $page;
}
this.$swiper.appendChild($page);
return $page;
});
this.$pages.forEach(($page, index, $pages) => {
let prevIndex = this.isLoop ? ($pages.length + index - 1) % $pages.length : (index - 1);
let nextIndex = this.isLoop ? ($pages.length + index + 1) % $pages.length : (index + 1);
$page.prev = this.$pages[prevIndex] || EMPTY_PAGE;
$page.next = this.$pages[nextIndex] || EMPTY_PAGE;
});
this.$container.style.overflow = 'hidden';
this.$container.appendChild(this.$swiper);
}
public on(eventName: string, callback: Function): Swiper {
let eventNames = eventName.split(' ');
for (let eventName of eventNames) {
if (!this._listeners[eventName]) {
this._listeners[eventName] = [];
}
this._listeners[eventName].push(callback);
}
return this;
}
public off(eventName: string, callback: Function): Swiper {
if (this._listeners[eventName]) {
let index = this._listeners[eventName].indexOf(callback);
if (index > -1) {
this._listeners[eventName].splice(index, 1);
}
}
return this;
}
private fire(eventName: string, event: any = {}) {
if (this._listeners[eventName]) {
for (let callback of this._listeners[eventName]) {
let extendArgs = {...event, ...{name: eventName}};
callback.call(this, extendArgs);
}
}
return this;
}
public destroy() {
this.unbindEvents();
this._listeners = {};
this.$container.style.overflow = '';
this.$swiper.parentElement.removeChild(this.$swiper);
this.fire('destroy');
}
public render() {
// 撤销旧样式
if (this.lastActivePage !== this.activePage) {
this.lastActivePage.classList.remove('active');
this.lastActivePage.style.cssText = '';
if (this.activePage !== EMPTY_PAGE) {
this.activePage.classList.add('active');
}
}
this.log('offset : ' + this.offset[this.axis]);
// 普通渲染:计算
let easingFn = Easing.easeOutQuad;
if (this.activePage === EMPTY_PAGE) {
easingFn = Easing.rubberBand;
}
this.renderInstance.doRender({
axis: this.axis,
moveDirection: this.moveDirection,
sideOffset: easingFn(this.offset[this.axis], this.sideLength),
sideLength: this.sideLength,
$swiper: this.$swiper,
currentPage: this.currentPage,
activePage: this.activePage
});
}
} | the_stack |
import * as React from 'react';
import {IInputs} from "./generated/ManifestTypes";
import DataSetInterfaces = ComponentFramework.PropertyHelper.DataSetApi;
import {AzureMap, AzureMapsProvider, IAzureMapOptions, IAzureMapControls,
AzureMapDataSourceProvider, AzureMapPopup, AzureMapLayerProvider, IAzureDataSourceChildren, AzureMapFeature} from 'react-azure-maps'
import {data, MapMouseEvent, MapErrorEvent, ControlPosition,
ControlOptions, CameraBoundsOptions, PopupOptions} from 'azure-maps-control'
import { Stack} from 'office-ui-fabric-react/lib/Stack';
import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner';
import { FontIcon } from 'office-ui-fabric-react/lib/Icon';
import { mergeStyleSets, getTheme, FontWeights } from 'office-ui-fabric-react/lib/Styling';
import { HoverCard, HoverCardType, IPlainCardProps } from 'office-ui-fabric-react/lib/HoverCard';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { isNumber } from "util";
import atlas = require('azure-maps-control');
export interface IProps {
pcfContext: ComponentFramework.Context<IInputs>
}
interface MyWindow extends Window {
myFunction: Function;
}
const baseMapOptions: IAzureMapOptions = {
zoom: 10,
center: [0, 0],
language: 'en-US',
style: 'satellite_road_labels'
}
const azureMapsControls: IAzureMapControls[] = [
{
controlName: 'CompassControl',
options: { position: ControlPosition.TopRight } as ControlOptions
},
{
controlName: 'ZoomControl',
options: { position: ControlPosition.TopRight } as ControlOptions
},
{
controlName: 'PitchControl',
options: { position: ControlPosition.TopRight } as ControlOptions
},
{
controlName: 'StyleControl',
controlOptions: { mapStyles: ["satellite", "satellite_road_labels", "road", "road_shaded_relief", "night", "grayscale_dark", "grayscale_light"] },
options: { position: ControlPosition.TopRight } as ControlOptions
}
];
const loaderComponent = <Spinner styles={{root: {height: '100%'}}} size={SpinnerSize.large} label="Loading..." />;
const theme = getTheme();
const errorStyles = mergeStyleSets({
stack: [{
justifyContent: "center",
alignItems: "center",
height: '100%'
}],
icon: [{
fontSize: 50,
height: 50,
width: 50,
margin: '0 25px',
color: 'red'
}],
title: [
theme.fonts.xLarge,
{
margin: 0,
fontWeight: FontWeights.semilight
}
],
subtext: [
theme.fonts.small,
{
margin: 0,
fontWeight: FontWeights.semilight
}
]
});
const invalidRecordsStyle = mergeStyleSets({
compactCard: {
display: 'flex',
cursor: 'text',
flexDirection: 'column',
padding: '10px',
height: '100%',
},
item: {
textDecoration: 'underline',
cursor: 'default',
color: '#3b79b7'
},
invalidItem: {
color: '#333',
textDecoration: 'none',
},
title: {
color: '#333',
textDecoration: 'none',
fontWeight: FontWeights.bold
}
});
export const AzureMapsGridControl: React.FC<IProps> = (props) => {
const [environmentSettings, setEnvironmentSettings] = React.useState({settings: {}, loading: true, errorTitle: '', errorMessage: ''});
const [azureMapOptions, setAzureMapOptions] = React.useState(baseMapOptions);
const [showMap, setShowMap] = React.useState(false);
const [errorDetails, setErrorDetails] = React.useState({hasError: false, errorTitle: '', errorMessage:''});
const [popupDetails, setPopupDetails] = React.useState({options: { position: [0,0] } as PopupOptions, properties: {name: '', id: '', entityName: '', description: ''}, isVisible: false});
const [defaultMarkerColor, setDefaultMarkerColor] = React.useState(props.pcfContext.parameters?.defaultPushpinColor?.raw || "#4288f7");
const _getKeys = () => {
let params = props.pcfContext.parameters;
let dataSet = props.pcfContext.parameters.mapDataSet;
return {
lat: params.latFieldName.raw ? getFieldName(dataSet, params.latFieldName.raw) : "",
long: params.longFieldName.raw ? getFieldName(dataSet, params.longFieldName.raw) : "",
name: params.primaryFieldName.raw ? getFieldName(dataSet, params.primaryFieldName.raw) : "",
description: params.descriptionFieldName.raw ? getFieldName(dataSet, params.descriptionFieldName.raw) : "",
color: params.pushpinColorField.raw ? getFieldName(dataSet, params.pushpinColorField.raw) : ""
}
}
const [keys, setKeys] = React.useState(_getKeys);
const _getMarkers = () : {valid: DataSetInterfaces.EntityRecord[], invalid:string[], cameraOptions:CameraBoundsOptions} => {
let dataSet = props.pcfContext.parameters.mapDataSet;
let _invalidRecords: string[] = [];
let _validRecords: DataSetInterfaces.EntityRecord[] = [];
var _cameraOptions: CameraBoundsOptions = { padding: 20 };
let returnData = {valid: _validRecords, invalid: _invalidRecords, cameraOptions: _cameraOptions}
//if dataset is empty or the lat/long fields are not defined then end
if (!dataSet || !keys.lat || !keys.long) {
return returnData;
}
//store location results so that we can utilize them later to get the bounding box for the map
let totalRecordCount = dataSet.sortedRecordIds.length;
let locationResults: data.Position[] = [];
//loop through all the records to create the pushpins
for (let i = 0; i < totalRecordCount; i++) {
var recordId = dataSet.sortedRecordIds[i];
var record = dataSet.records[recordId] as DataSetInterfaces.EntityRecord;
var lat = record.getValue(keys.lat) as number;
var long = record.getValue(keys.long) as number;
var name = record.getValue(keys.name) as string;
//if incorrect lat or long values are in the data then continue;
if (!checkLatitude(lat) || !checkLongitude(long))
{
//output the incorrect lat/long data so the user could later update the record.
//console.log(`Cannot add pin for ${name}, Lat: ${lat ? lat.toString() : ''}, Long: ${long ? long.toString() : ''}`);
returnData.invalid.push(`Name: ${name}, Lat: ${lat ? lat.toString() : ''}, Long: ${long ? long.toString() : ''}`)
continue;
}
returnData.valid.push(record);
// var pushpinLatLong = new Microsoft.Maps.Location(lat, long);
locationResults.push([long, lat]);
}
if (_validRecords.length > 0)
{
returnData.cameraOptions.bounds = generateBoundingBox(locationResults)
}
return returnData;
}
const [markers, setMarkers] = React.useState(_getMarkers);
//Listens for the data set to change then updates the markers.
React.useEffect(() => {
if (props.pcfContext.parameters.mapDataSet.loading === false)
{
setMarkers(_getMarkers);
}
}, [props.pcfContext.parameters.mapDataSet]);
//This useEffect is an example of one where you want to run something that is async, in this case the
//retrieveMultipleRecords function but you want to await the results.
React.useEffect(() => {
const _getSettings = async() => {
try{
await props.pcfContext.webAPI.retrieveMultipleRecords('raw_azuremapsconfig').then(
(results) => {
if (results.entities.length > 0)
{
setEnvironmentSettings({settings: results.entities[0], loading: false, errorTitle: '', errorMessage: ''});
}
else
{
setEnvironmentSettings({
settings: {},
loading: false,
errorTitle: 'No Settings found for Azure Maps',
errorMessage:
`Please contact your administror and have then add a record in your system under the Azure Maps Config entity.`
});
}
},
(error) => {
setEnvironmentSettings({
settings: {},
loading: false,
errorTitle: 'Error retrieveing the Azure Maps Settings.',
errorMessage: error.message
});
}
);
}
catch(error){
setEnvironmentSettings({
settings: {},
loading: false,
errorTitle: 'Error retrieveing the Azure Maps Settings.',
errorMessage: error});
}
}
_getSettings();
}, []);
React.useEffect(() => {
if (!environmentSettings.loading){
if (environmentSettings.errorTitle === '')
{
let updatedOptions = {...azureMapOptions, authOptions: _getAuthenticationOptions(environmentSettings.settings)}
if (isAzureGoverment(environmentSettings.settings)){
updatedOptions.domain = 'atlas.azure.us';
}
setAzureMapOptions(updatedOptions);
}
else{
setErrorDetails({hasError: true, errorTitle: environmentSettings.errorTitle, errorMessage: environmentSettings.errorMessage});
}
}
}, [environmentSettings]);
React.useEffect(() => {
if (azureMapOptions.authOptions){
setShowMap(true);
}
},
[azureMapOptions.authOptions]);
React.useEffect(()=> {
if (errorDetails.hasError){
setShowMap(false);
}
}, [errorDetails]);
const _getAuthenticationOptions = (settings: any) : any => {
let authType = settings.raw_authenticationtype;
var authOptions = {};
//load authentication information
switch(authType){
case 699720001: //AAD
authOptions = {
authType: atlas.AuthenticationType.aad,
clientId: settings?.raw_clientid || '',
aadAppId: settings?.raw_aadappid || '',
aadTenant: settings?.raw_aadtenant || '',
aadInstance: settings?.raw_aadinstance || '',
}
break;
case 699720002: //Anonymous
authOptions = {
authType: atlas.AuthenticationType.anonymous,
clientId: settings.raw_clientid || '',
getToken: function (resolve: any, reject: any, map: any){
var setError = (e: any) => setErrorDetails({hasError: true, errorTitle: 'Anonymous Authentication getToken Error', errorMessage: `${e.message}`})
try{
var userFunction = settings?.raw_anonymousgettokenfunction || '';
userFunction = userFunction.replace('url', `"${settings?.raw_anonymousurl}"`);
var evalFunction = `(${userFunction})(resolve, reject, map);`
eval(evalFunction);
}
catch(error){
setError(error);
}
}
}
break;
default: //subscription key
authOptions = {
authType: atlas.AuthenticationType.subscriptionKey,
subscriptionKey: settings.raw_subscriptionkey
}
break;
}
return authOptions;
}
const _openRecord = React.useCallback(() => {
//event.preventDefault();
props.pcfContext.navigation.openForm({
openInNewWindow: true,
entityId: popupDetails.properties.id,
entityName: popupDetails.properties.entityName
});
}, [popupDetails.properties]);
const _recordOpen = () => {
//event.preventDefault();
props.pcfContext.navigation.openForm({
openInNewWindow: true,
entityId: popupDetails.properties.id,
entityName: popupDetails.properties.entityName
});
}
const _memoizedMarkerRender: IAzureDataSourceChildren = React.useMemo(
(): any => markers.valid.map(marker => renderPoint(marker, keys, defaultMarkerColor)),
[markers]
);
const _expandingCardProps: IPlainCardProps = {
onRenderPlainCard: onRenderPlainCard,
renderData: markers.invalid
};
return(
<div id="mainDiv">
<div id="mapDiv">
{environmentSettings.loading && loaderComponent}
{errorDetails.hasError &&
<Stack horizontal className={errorStyles.stack}>
<FontIcon iconName="StatusErrorFull" className={errorStyles.icon} />
<Stack>
<Label className={errorStyles.title}>{errorDetails.errorTitle}</Label>
<Label className={errorStyles.subtext}>{errorDetails.errorMessage}</Label>
</Stack>
</Stack>}
{showMap && <AzureMapsProvider>
<AzureMap
options={azureMapOptions}
LoaderComponent={() => loaderComponent}
cameraOptions={markers.cameraOptions}
events={{
ready: (e: any) => {
//console.log('ready', e);
e.map.setCamera({
bounds: markers.cameraOptions.bounds,
padding: markers.cameraOptions.padding});
},
error: (e: MapErrorEvent) => {
//console.log('error', e);
//If the map is not currently loaded then assume that this error is coming from an authentication error.
//Microsoft has decided to throw errors for a lof of things that don't actually affect functionality.
if (e.map['loaded'] === false)
{
setErrorDetails({hasError: true, errorTitle: e.error.name, errorMessage: e.error.message});
}
}
}}
controls={azureMapsControls}>
<AzureMapDataSourceProvider
id={"DataSource1"}>
<AzureMapLayerProvider
id={"Layer1"}
options={{
radius: 3,
strokeColor: ['get', 'color'],
strokeWidth: 4,
color: "white"
}}
type={"BubbleLayer"}
events={{
//this event keeps the popup box open until you hover over another shap or
//hit the close button on the current popup.
mousemove: (e: MapMouseEvent) => {
if (e.shapes && e.shapes.length > 0) {
setPopupDetails({
options: getPopupOptions(e),
properties: getPopupProperties(e),
isVisible: true});
}
}
}}
></AzureMapLayerProvider>
{_memoizedMarkerRender}
</AzureMapDataSourceProvider>
<AzureMapPopup
isVisible={popupDetails.isVisible}
options={popupDetails.options}
popupContent={<div className="azuremapsgrid-customInfobox">
<div className="azuremapsgrid-name">{popupDetails.properties.name}</div>
{popupDetails.properties.description && <div>{popupDetails.properties.description}</div>}
<div>{popupDetails.options.position![1]}, {popupDetails.options.position![0]}</div>
<div><a href={`main.aspx?etn=${popupDetails.properties.entityName}&pagetype=entityrecord&id=${popupDetails.properties.id}`} target="_blank">Open Record</a></div>
</div>}
/>
</AzureMap>
</AzureMapsProvider>}
</div>
<div id="mapInfoDiv">
<div>Total Records ({(markers.invalid.length + markers.valid.length).toString()})</div>
<div className="mapInfoDetails">Valid Locations ({markers.valid.length.toString()})</div>
<div className="mapInfoDetails">Invalid/Empty Locations (</div>
<HoverCard type={HoverCardType.plain} plainCardProps={_expandingCardProps} className={invalidRecordsStyle.item}>{markers.invalid.length.toString()}</HoverCard>
<div>)</div>
</div>
</div>
);
}
const myFunction = () => {
alert("I am an alert box!");
}
const isAzureGoverment = (settings: any): boolean => {
return settings?.raw_azuregovernment === true || false;
}
const generateBoundingBox = (locationResults: data.Position[]): atlas.data.BoundingBox | undefined => {
if (locationResults.length > 0) {
locationResults.sort(compareLocationValues('latitude'));
let minLat = locationResults[0][1];
let maxLat = locationResults[locationResults.length - 1][1];
locationResults.sort(compareLocationValues('longitude'));
let minLong = locationResults[0][0];
let maxLong = locationResults[locationResults.length - 1][0];
//let box = Microsoft.Maps.LocationRect.fromEdges(maxLat, minLong, minLat, maxLong);
return atlas.data.BoundingBox.fromEdges(minLong, minLat, maxLong, maxLat)
}
}
const getPopupOptions = (e: MapMouseEvent): PopupOptions => {
const prop: any = e.shapes![0]
let coordinates = prop.getCoordinates();
return {
closeButton: true,
position: coordinates,
pixelOffset: [0, -5],
showPointer: true
}
}
const getPopupProperties = (e: MapMouseEvent) => {
const prop: any = e.shapes![0];
return prop.getProperties();
}
const onRenderPlainCard = (items: string[]): JSX.Element => {
return (
items.length > 0 ?
<div className={invalidRecordsStyle.compactCard}>
<div>Invalid Records</div>
{items.map((item, index) => <div className={invalidRecordsStyle.invalidItem} key={index}>{item}</div>)}
</div>
: <div></div>
);
};
const renderPoint = (record: DataSetInterfaces.EntityRecord, keys: any, defaultMarkerColor: string) => {
return (
<AzureMapFeature
key={record.getRecordId()}
id={record.getRecordId()}
type="Point"
coordinate={[record.getValue(keys.long) as number, record.getValue(keys.lat) as number]}
properties={{
id: record.getRecordId(),
entityName: (record as any).getNamedReference().entityName,
name: record.getValue(keys.name),
description: keys.description && record.getValue(keys.description) ? record.getValue(keys.description) : "",
color: keys.color && record.getValue(keys.color) ? record.getValue(keys.color).toString() : defaultMarkerColor
}}
/>
)
}
const getFieldName = (dataSet: ComponentFramework.PropertyTypes.DataSet ,fieldName: string): string => {
//if the field name does not contain a . then just return the field name
if (fieldName.indexOf('.') == -1) return fieldName;
//otherwise we need to determine the alias of the linked entity
var linkedFieldParts = fieldName.split('.');
linkedFieldParts[0] = dataSet.linking.getLinkedEntities().find(e => e.name === linkedFieldParts[0].toLowerCase())?.alias || "";
return linkedFieldParts.join('.');
}
const compareLocationValues = (key: 'latitude' | 'longitude', order: 'asc' | 'desc' = 'asc'): any => {
return function innerSort([a, b]: data.Position, [c, d]: data.Position): number {
const loc = key === 'latitude' ? {a: b, b: d} : {a: a, b: c};
let comparison = 0;
if (loc.a > loc.b) {
comparison = 1;
} else if (loc.a < loc.b) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
}
}
const checkLatitude = (lat: any): boolean => {
//check for null or undefined
if (!lat) return false;
lat = isNumber(lat) ? lat.toString() : lat;
let latExpression: RegExp = /^(\+|-)?(?:90(?:(?:\.0{1,10})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,10})?))$/;
return latExpression.test(lat);
}
const checkLongitude = (long: any): boolean => {
//check for null or undefined
if (!long) return false;
long = isNumber(long) ? long.toString() : long;
let longExpression: RegExp = /^(\+|-)?(?:180(?:(?:\.0{1,10})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,10})?))$/;
return longExpression.test(long);
} | the_stack |
import { LifecycleFlags as LF, LifecycleFlags, SelectValueObserver } from '@aurelia/runtime-html';
import { h, TestContext, verifyEqual, assert, createFixture } from '@aurelia/testing';
type Anything = any;
// TODO: need many more tests here, this is just preliminary
describe('3-runtime-html/select-value-observer.spec.ts', function () {
describe('[UNIT]', function () {
function createFixture(initialValue: Anything = '', options = [], multiple = false) {
const ctx = TestContext.create();
const { platform, observerLocator } = ctx;
const optionElements = options.map(o => `<option value="${o}">${o}</option>`).join('\n');
const markup = `<select ${multiple ? 'multiple' : ''}>\n${optionElements}\n</select>`;
const el = ctx.createElementFromMarkup(markup) as HTMLSelectElement;
const sut = observerLocator.getObserver(el, 'value') as SelectValueObserver;
sut.setValue(initialValue, LF.fromBind);
return { ctx, el, sut, platform };
}
describe('setValue()', function () {
const valuesArr = [['', 'foo', 'bar']];
const initialArr = ['', 'foo', 'bar'];
const nextArr = ['', 'foo', 'bar'];
for (const values of valuesArr) {
for (const initial of initialArr) {
for (const next of nextArr) {
it(`sets 'value' from "${initial}" to "${next}"`, function () {
const { el, sut } = createFixture(initial, values);
assert.strictEqual(el.value, initial, `el.value`);
sut.setValue(next, LifecycleFlags.none);
assert.strictEqual(el.value, next, `el.value`);
});
}
}
}
});
describe('synchronizeOptions', function () {
return;
});
describe('synchronizeValue()', function () {
describe('<select />', function () {
return;
});
// There is subtle difference in behavior of synchronization for SelectObserver
// When synchronzing value without synchronizing Options prior
// the behavior is different, as such, if currentValue is an array
// 1. With synchronizeOptions: source => target => source. Or selected <option/> are based on value array
// 2. Without synchronizeOptions: target => source. Or selected values are based on selected <option/>
describe('<select multiple="true" />', function () {
it('retrieves value freshly when not observing', function () {
const initialValue = [];
const { sut } = createMutiSelectSut(initialValue, [
option({ text: 'A', selected: true }),
option({ text: 'B', selected: true }),
option({ text: 'C' })
]);
assert.notStrictEqual(initialValue, sut.getValue());
assert.deepEqual(['A', 'B'], sut.getValue(), `currentValue`);
});
it('disregards null existing value when not observing', function () {
const { sut } = createMutiSelectSut(null, [
option({ text: 'A', selected: true }),
option({ text: 'B', selected: true }),
option({ text: 'C' })
]);
assert.deepEqual(['A', 'B'], sut.getValue(), `currentValue`);
});
it('disregard existing value when not observing', function () {
const { sut } = createMutiSelectSut(undefined, [
option({ text: 'A', selected: true }),
option({ text: 'B', selected: true }),
option({ text: 'C' })
]);
assert.deepEqual(['A', 'B'], sut.getValue(), `currentValue`);
});
it('retrieves <option /> "model" if has', function () {
const { sut } = createMutiSelectSut([], [
option({ text: 'A', _model: { id: 1, name: 'select 1' }, selected: true }),
option({ text: 'B', _model: { id: 2, name: 'select 2' }, selected: true }),
option({ text: 'C' })
]);
verifyEqual(
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' }
],
sut.getValue()
);
});
it('synchronizes with array (3): disregard "value" when there is model', function () {
const { sut } = createMutiSelectSut([], [
option({ text: 'A', value: 'AA', _model: { id: 1, name: 'select 1' }, selected: true }),
option({ text: 'B', value: 'BB', _model: { id: 2, name: 'select 2' }, selected: true }),
option({ text: 'C', value: 'CC' })
]);
const currentValue = sut.getValue() as any[];
sut.syncValue();
assert.deepEqual(currentValue, sut.getValue(), `currentValue`);
assert.strictEqual(currentValue.length, 2, `currentValue['length']`);
verifyEqual(
currentValue,
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' }
]
);
});
it('synchronize regardless disabled state of <option/>', function () {
const { sut } = createMutiSelectSut([], [
option({ text: 'A', value: 'AA', _model: { id: 1, name: 'select 1' }, selected: true }),
option({ text: 'B', value: 'BB', disabled: true, _model: { id: 2, name: 'select 2' }, selected: true }),
option({ text: 'C', value: 'CC', disabled: true, selected: true })
]);
const currentValue = sut.getValue() as any[];
sut.syncValue();
assert.deepEqual(currentValue, sut.getValue(), `currentValue`);
verifyEqual(
currentValue,
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' },
'CC'
]
);
});
it('syncs array & <option/> mutation (from repeat etc...)', async function () {
const { sut, el, ctx } = createMutiSelectSut([], [
option({ text: 'A', value: 'AA', _model: { id: 1, name: 'select 1' }, selected: true }),
option({ text: 'B', value: 'BB', disabled: true, _model: { id: 2, name: 'select 2' }, selected: true }),
option({ text: 'C', value: 'CC', disabled: true, selected: true })
]);
let handleChangeCallCount = 0;
let currentValue = sut.getValue() as any[];
const noopSubscriber = {
handleChange() {
handleChangeCallCount++;
},
};
sut.syncValue();
assert.deepEqual(currentValue, sut.getValue(), `currentValue`);
sut.subscribe(noopSubscriber);
el.add(option({ text: 'DD', value: 'DD', selected: true })(ctx));
await Promise.resolve();
// currentValue = sut.getValue() as any[];
assert.strictEqual(handleChangeCallCount, 0);
assert.strictEqual(el.options[3].value, 'DD');
assert.strictEqual(el.options[3].selected, false);
currentValue = sut.getValue() as any[];
assert.deepEqual(
currentValue,
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' },
'CC',
]
);
currentValue.push('DD');
assert.strictEqual(handleChangeCallCount, 0);
assert.strictEqual(el.options[3].value, 'DD');
assert.strictEqual(el.options[3].selected, true);
assert.deepEqual(
currentValue,
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' },
'CC',
'DD'
]
);
sut.unsubscribe(noopSubscriber);
});
describe('with <optgroup>', function () {
it('synchronizes with array', function () {
const { sut } = createMutiSelectSut([], [
optgroup(
{},
option({ text: 'A', _model: { id: 1, name: 'select 1' }, selected: true }),
option({ text: 'B', _model: { id: 2, name: 'select 2' }, selected: true }),
),
option({ text: 'C', value: 'CC' })
]);
let currentValue = sut.getValue() as any[];
assert.strictEqual(currentValue.length, 2, `currentValue.length`);
sut.syncValue();
currentValue = sut.getValue() as any[];
assert.deepEqual(
sut.getValue(),
[
{ id: 1, name: 'select 1' },
{ id: 2, name: 'select 2' }
]
);
});
});
type SelectValidChild = HTMLOptionElement | HTMLOptGroupElement;
function createMutiSelectSut(initialValue: Anything[], optionFactories: ((ctx: TestContext) => SelectValidChild)[]) {
const ctx = TestContext.create();
const { observerLocator } = ctx;
const el = select(...optionFactories.map(create => create(ctx)))(ctx);
const sut = observerLocator.getObserver(el, 'value') as SelectValueObserver;
sut.setValue(initialValue, LifecycleFlags.noFlush);
return { ctx, el, sut };
}
function select(...options: SelectValidChild[]): (ctx: TestContext) => HTMLSelectElement {
return function (ctx: TestContext) {
return h(
'select',
{ multiple: true },
...options
);
};
}
});
});
function option(attributes: Record<string, any>) {
return function (ctx: TestContext) {
return h('option', attributes);
};
}
function optgroup(attributes: Record<string, any>, ...optionFactories: ((ctx: TestContext) => HTMLOptionElement)[]) {
return function (ctx: TestContext) {
return h('optgroup', attributes, ...optionFactories.map(create => create(ctx)));
};
}
});
it('handles source change', async function () {
const { ctx, startPromise, component, tearDown } = createFixture(
`<h3>Select Product</h3>
<select value.bind="selectedProductId" ref="selectEl">
<option model.bind="null">Choose...</option>
<option repeat.for="product of products" model.bind="product.id">
\${product.id} - \${product.name}
</option>
</select>
<h3>Data</h3>
Selected product ID: \${selectedProductId}
<button click.trigger="clear()">clear</button>`,
class App {
public selectEl: HTMLSelectElement;
public products = [
{ id: 0, name: "Motherboard" },
{ id: 1, name: "CPU" },
{ id: 2, name: "Memory" }
];
public selectedProductId = null;
public clear() {
this.selectedProductId = null;
}
}
);
await startPromise;
component.selectEl.selectedIndex = 2;
component.selectEl.dispatchEvent(new ctx.CustomEvent('change'));
assert.strictEqual(component.selectedProductId, 1);
component.clear();
assert.strictEqual(component.selectEl.selectedIndex, 2);
ctx.platform.domWriteQueue.flush();
assert.strictEqual(component.selectEl.selectedIndex, 0);
await tearDown();
});
}); | the_stack |
import { createServer } from "http";
import { readFileSync } from "fs";
import fetch from "node-fetch";
import { sign } from "@octokit/webhooks-methods";
// import without types
const express = require("express");
import { Webhooks, createNodeMiddleware } from "../../src";
const pushEventPayload = readFileSync(
"test/fixtures/push-payload.json",
"utf-8"
);
let signatureSha256: string;
describe("createNodeMiddleware(webhooks)", () => {
beforeAll(async () => {
signatureSha256 = await sign(
{ secret: "mySecret", algorithm: "sha256" },
pushEventPayload
);
});
afterEach(() => {
jest.useRealTimers();
});
test("README example", async () => {
expect.assertions(3);
const webhooks = new Webhooks({
secret: "mySecret",
});
webhooks.on("push", (event) => {
expect(event.id).toBe("123e4567-e89b-12d3-a456-426655440000");
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
expect(response.status).toEqual(200);
await expect(response.text()).resolves.toBe("ok\n");
server.close();
});
test("request.body already parsed (e.g. Lambda)", async () => {
expect.assertions(3);
const webhooks = new Webhooks({
secret: "mySecret",
});
const dataChunks: any[] = [];
const middleware = createNodeMiddleware(webhooks);
const server = createServer((req, res) => {
req.once("data", (chunk) => dataChunks.push(chunk));
req.once("end", () => {
// @ts-expect-error - TS2339: Property 'body' does not exist on type 'IncomingMessage'.
req.body = JSON.parse(Buffer.concat(dataChunks).toString());
middleware(req, res);
});
}).listen();
webhooks.on("push", (event) => {
expect(event.id).toBe("123e4567-e89b-12d3-a456-426655440000");
});
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
expect(response.status).toEqual(200);
expect(await response.text()).toEqual("ok\n");
server.close();
});
test("Handles invalid JSON", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: "invalid",
}
);
expect(response.status).toEqual(400);
await expect(response.text()).resolves.toMatch(/SyntaxError: Invalid JSON/);
server.close();
});
test("Handles non POST request", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "PUT",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: "invalid",
}
);
expect(response.status).toEqual(404);
await expect(response.text()).resolves.toMatch(
/Unknown route: PUT \/api\/github\/webhooks/
);
server.close();
});
test("custom non-found handler", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
const server = createServer(
createNodeMiddleware(webhooks, {
onUnhandledRequest(_request, response) {
response.writeHead(404);
response.end("nope");
},
})
).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "PUT",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: "invalid",
}
);
expect(response.status).toEqual(404);
await expect(response.text()).resolves.toEqual("nope");
server.close();
});
test("Handles missing headers", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
// "X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: "invalid",
}
);
expect(response.status).toEqual(400);
await expect(response.text()).resolves.toMatch(
/Required headers missing: x-github-event/
);
server.close();
});
test("Handles non-request errors", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
webhooks.on("push", () => {
throw new Error("boom");
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
await expect(response.text()).resolves.toMatch(/boom/);
expect(response.status).toEqual(500);
server.close();
});
test("Handles timeout", async () => {
jest.useFakeTimers();
const webhooks = new Webhooks({
secret: "mySecret",
});
webhooks.on("push", async () => {
jest.advanceTimersByTime(10000);
server.close();
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
await expect(response.text()).resolves.toMatch(/still processing/);
expect(response.status).toEqual(202);
});
test("Handles timeout with error", async () => {
jest.useFakeTimers();
const webhooks = new Webhooks({
secret: "mySecret",
});
webhooks.on("push", async () => {
jest.advanceTimersByTime(10000);
server.close();
throw new Error("oops");
});
const server = createServer(createNodeMiddleware(webhooks)).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
await expect(response.text()).resolves.toMatch(/still processing/);
expect(response.status).toEqual(202);
});
test("express middleware no mount path 404", async () => {
const app = express();
const webhooks = new Webhooks({
secret: "mySecret",
});
app.use(createNodeMiddleware(webhooks));
app.all("*", (_request: any, response: any) =>
response.status(404).send("Dafuq")
);
const server = app.listen();
const { port } = server.address();
const response = await fetch(`http://localhost:${port}/test`, {
method: "POST",
body: pushEventPayload,
});
await expect(response.text()).resolves.toBe("Dafuq");
expect(response.status).toEqual(404);
server.close();
});
test("express middleware no mount path no next", async () => {
const app = express();
const webhooks = new Webhooks({
secret: "mySecret",
});
app.all("/foo", (_request: any, response: any) => response.end("ok\n"));
app.use(createNodeMiddleware(webhooks));
const server = app.listen();
const { port } = server.address();
const response = await fetch(`http://localhost:${port}/test`, {
method: "POST",
body: pushEventPayload,
});
await expect(response.text()).resolves.toContain("Cannot POST /test");
expect(response.status).toEqual(404);
const responseForFoo = await fetch(`http://localhost:${port}/foo`, {
method: "POST",
body: pushEventPayload,
});
await expect(responseForFoo.text()).resolves.toContain("ok\n");
expect(responseForFoo.status).toEqual(200);
server.close();
});
test("express middleware no mount path with options.path", async () => {
const app = express();
const webhooks = new Webhooks({
secret: "mySecret",
});
app.use(createNodeMiddleware(webhooks, { path: "/test" }));
app.all("*", (_request: any, response: any) =>
response.status(404).send("Dafuq")
);
const server = app.listen();
const { port } = server.address();
const response = await fetch(`http://localhost:${port}/test`, {
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
});
await expect(response.text()).resolves.toBe("ok\n");
expect(response.status).toEqual(200);
server.close();
});
test("express middleware with mount path with options.path", async () => {
const app = express();
const webhooks = new Webhooks({
secret: "mySecret",
});
app.post("/test", createNodeMiddleware(webhooks, { path: "/test" }));
app.all("*", (_request: any, response: any) =>
response.status(404).send("Dafuq")
);
const server = app.listen();
const { port } = server.address();
const response = await fetch(`http://localhost:${port}/test`, {
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
});
await expect(response.text()).resolves.toBe("ok\n");
expect(response.status).toEqual(200);
server.close();
});
test("Handles invalid URL", async () => {
const webhooks = new Webhooks({
secret: "mySecret",
});
let middlewareWasRan: () => void;
const untilMiddlewareIsRan = new Promise<void>(function (resolve) {
middlewareWasRan = resolve;
});
const actualMiddleware = createNodeMiddleware(webhooks);
const mockedMiddleware = async function (
...[req, ...rest]: Parameters<typeof actualMiddleware>
) {
req.url = "//";
await actualMiddleware(req, ...rest);
middlewareWasRan();
};
const server = createServer(mockedMiddleware).listen();
// @ts-expect-error complains about { port } although it's included in returned AddressInfo interface
const { port } = server.address();
const response = await fetch(
`http://localhost:${port}/api/github/webhooks`,
{
method: "POST",
headers: {
"X-GitHub-Delivery": "123e4567-e89b-12d3-a456-426655440000",
"X-GitHub-Event": "push",
"X-Hub-Signature-256": signatureSha256,
},
body: pushEventPayload,
}
);
await untilMiddlewareIsRan;
expect(response.status).toEqual(422);
expect(await response.text()).toMatch(/Request URL could not be parsed/);
server.close();
});
}); | the_stack |
import "expect-puppeteer";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { ElementHandle, CoverageEntry } from "puppeteer";
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const pti = require("puppeteer-to-istanbul");
const totalJsCoverage: CoverageEntry[] = [];
describe.each(["flat", "nested"])("interaction tests %s", (type) => {
beforeAll(async () => {
await page.coverage.startJSCoverage();
await page.goto(`http://localhost:3000/?type=${type}`);
});
test("resize images on create", async () => {
const fourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
expect(
await fourthImg.evaluate((node: HTMLElement): string => node.style.width)
).toBe("25%");
const fifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#five");
expect(
await fifthImg.evaluate((node: HTMLElement): string => node.style.width)
).toBe("10.3093%");
});
test(`click to open dataset lightbox`, async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
const img: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
const imgSrc = await img.evaluate(
(node: HTMLImageElement): string => node.src
);
const imgHigh = await img.evaluate(
(node: HTMLElement): string => node.dataset.highres as string
);
await expect(page).toClick("#four");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await img.evaluate((node: HTMLElement): DOMTokenList => node.classList)
)
).toContain("active");
expect(
await img.evaluate((node: HTMLElement): string => node.style.transform)
).toBe("translate(-300%, 0%) scale(4)");
expect(
await img.evaluate((node: HTMLImageElement): string => node.src)
).toBe(imgHigh);
expect(
await img.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
)
).toBe(imgSrc);
});
test(`click to close dataset lightbox`, async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const img: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
const imgLow = await img.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
);
await expect(page).toClick("#four");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
expect(
Object.values(
await img.evaluate((node: HTMLElement): DOMTokenList => node.classList)
)
).not.toContain("active");
expect(
await img.evaluate((node: HTMLElement): string => node.style.transform)
).toBe("translate(0px, 0px) scale(1)");
expect(
await img.evaluate((node: HTMLImageElement): string => node.src)
).toBe(imgLow);
});
test(`click to advance dataset lightbox`, async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
const img: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#six");
const imgSrc = await img.evaluate(
(node: HTMLImageElement): string => node.src
);
const imgHigh = await img.evaluate(
(node: HTMLElement): string => node.dataset.highres as string
);
await page.waitFor(200);
await expect(page).toClick("#five");
await page.waitFor(200);
await expect(page).toClick("#six");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await img.evaluate((node: HTMLElement): DOMTokenList => node.classList)
)
).toContain("active");
expect(
await img.evaluate((node: HTMLElement): string => node.style.transform)
).toBe("translate(-44.4444%, -109.167%) scale(4.35556)");
expect(
await img.evaluate((node: HTMLImageElement): string => node.src)
).toBe(imgHigh);
expect(
await img.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
)
).toBe(imgSrc);
await expect(page).toClick("#six"); // close lightbox
});
test(`click to open srcset lightbox`, async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
const img: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#ten");
await expect(page).toClick("#ten");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await img.evaluate((node: HTMLElement): DOMTokenList => node.classList)
)
).toContain("active");
expect(
await img.evaluate((node: HTMLElement): string => node.style.transform)
).toBe("translate(-638.613%, -110.084%) scale(4.97479)");
expect(
await img.evaluate((node: HTMLImageElement): string => node.sizes)
).toBe("100vw");
expect(
await img.evaluate(
(node: HTMLElement): string => node.dataset.sizes as string
)
).toBe("(max-width: 800px) 10vw, 853px");
});
test(`click to close srcset lightbox`, async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const img: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#ten");
await expect(page).toClick("#ten");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
expect(
Object.values(
await img.evaluate((node: HTMLElement): DOMTokenList => node.classList)
)
).not.toContain("active");
expect(
await img.evaluate((node: HTMLElement): string => node.style.transform)
).toBe("translate(0px, 0px) scale(1)");
expect(
await img.evaluate((node: HTMLImageElement): string => node.sizes)
).toBe("(max-width: 800px) 10vw, 853px");
});
test("right arrow to advance to next image", async () => {
const gallery = await expect(page).toMatchElement("#gallery");
// open lightbox
await expect(page).toClick("#four");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const fourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
const fifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#five");
const fifthImgSrc = await fifthImg.evaluate(
(node: HTMLImageElement): string => node.src
);
const fifthImgHigh = await fifthImg.evaluate(
(node: HTMLElement): string => node.dataset.highres as string
);
await page.keyboard.press("ArrowRight");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await fourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await fifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).toContain("active");
const fifthTransform = await fifthImg.evaluate(
(node: HTMLElement): string => node.style.transform
);
const fifthTransformSplit = fifthTransform.split(" ");
expect(fifthTransformSplit[0]).toBe("translate(243.333%,");
// flat: -109.167, nested: -108.264 (close enough?)
expect(parseFloat(fifthTransformSplit[1].slice(0, -2))).toBeCloseTo(
-109.167,
-1
);
expect(fifthTransformSplit[2]).toBe("scale(4.93333)");
expect(
await fifthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(fifthImgHigh);
expect(
await fifthImg.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
)
).toBe(fifthImgSrc);
});
test("left arrow to go to previous image", async () => {
const gallery = await expect(page).toMatchElement("#gallery");
const fourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
const fifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#five");
const fourthImgSrc = await fourthImg.evaluate(
(node: HTMLImageElement): string => node.src
);
const fourthImgHigh = await fourthImg.evaluate(
(node: HTMLElement): string => node.dataset.highres as string
);
await page.keyboard.press("ArrowLeft");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await fourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).toContain("active");
expect(
Object.values(
await fifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
await fourthImg.evaluate(
(node: HTMLElement): string => node.style.transform
)
).toBe("translate(-300%, 0%) scale(4)");
expect(
await fourthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(fourthImgHigh);
expect(
await fourthImg.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
)
).toBe(fourthImgSrc);
});
test("escape closes lightbox", async () => {
const gallery = await expect(page).toMatchElement("#gallery");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const fourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#four");
const fifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#five");
await page.keyboard.press("Escape");
expect(
Object.values(
await gallery.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
expect(
Object.values(
await fourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await fifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
await fifthImg.evaluate(
(node: HTMLElement): string => node.style.transform
)
).toBe("translate(0px, 0px) scale(1)");
expect(
await fourthImg.evaluate(
(node: HTMLElement): string => node.style.transform
)
).toBe("translate(0px, 0px) scale(1)");
expect(
await fourthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAACnAQMAAAACMtNXAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAADUExURX9/f5DKGyMAAAAcSURBVBgZ7cExAQAAAMIg+6deCj9gAAAAAAA8BRWHAAFREbyXAAAAAElFTkSuQmCC"
);
expect(
await fifthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKcAAAD6AQMAAAD+yMWGAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAADUExURaGhoWkNFFsAAAAcSURBVBgZ7cExAQAAAMIg+6deCU9gAAAAAADcBRV8AAE4UWJ7AAAAAElFTkSuQmCC"
);
});
afterAll(async () => {
const jsCoverage = await page.coverage.stopJSCoverage();
totalJsCoverage.push(...jsCoverage.slice(1));
});
});
describe("multiple galleries with keyboards", () => {
beforeAll(async () => {
await page.coverage.startJSCoverage();
await page.goto(`http://localhost:3000/?type=multi`);
});
test("right arrow to advance to next image in second gallery", async () => {
const flat = await expect(page).toMatchElement("#flat");
const nested = await expect(page).toMatchElement("#nested");
// open second lightbox
await expect(page).toClick("#nested-four");
expect(
Object.values(
await nested.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const fourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#nested-four");
const fifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#nested-five");
const fifthImgSrc = await fifthImg.evaluate(
(node: HTMLImageElement): string => node.src
);
const fifthImgHigh = await fifthImg.evaluate(
(node: HTMLElement): string => node.dataset.highres as string
);
await page.keyboard.press("ArrowRight");
expect(
Object.values(
await flat.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
expect(
Object.values(
await nested.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await fourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await fifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).toContain("active");
const fifthTransform = await fifthImg.evaluate(
(node: HTMLElement): string => node.style.transform
);
const fifthTransformSplit = fifthTransform.split(" ");
expect(fifthTransformSplit[0]).toBe("translate(337.819%,");
// flat: -109.167, nested: -108.264 (close enough?)
expect(parseFloat(fifthTransformSplit[1].slice(0, -2))).toBeCloseTo(
-109.167,
-1
);
expect(fifthTransformSplit[2]).toBe("scale(3.04362)");
expect(
await fifthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(fifthImgHigh);
expect(
await fifthImg.evaluate(
(node: HTMLElement): string => node.dataset.lowres as string
)
).toBe(fifthImgSrc);
});
test("escape closes first lightbox", async () => {
const flat = await expect(page).toMatchElement("#flat");
// open first lightbox
await expect(page).toClick("#flat-four");
expect(
Object.values(
await flat.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const nested = await expect(page).toMatchElement("#nested");
expect(
Object.values(
await nested.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
const firstFourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#flat-four");
const firstFifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#flat-five");
const secondFourthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#nested-four");
const secondFifthImg: ElementHandle<HTMLImageElement> = await expect(
page
).toMatchElement("#nested-five");
await page.keyboard.press("Escape");
expect(
Object.values(
await flat.evaluate((node: Element): DOMTokenList => node.classList)
)
).not.toContain("lightbox");
expect(
Object.values(
await nested.evaluate((node: Element): DOMTokenList => node.classList)
)
).toContain("lightbox");
expect(
Object.values(
await firstFourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await firstFifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await secondFourthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).not.toContain("active");
expect(
Object.values(
await secondFifthImg.evaluate(
(node: HTMLElement): DOMTokenList => node.classList
)
)
).toContain("active");
expect(
await firstFifthImg.evaluate(
(node: HTMLElement): string => node.style.transform
)
).toBe("translate(0px, 0px) scale(1)");
expect(
await firstFourthImg.evaluate(
(node: HTMLElement): string => node.style.transform
)
).toBe("translate(0px, 0px) scale(1)");
expect(
await firstFourthImg.evaluate(
(node: HTMLImageElement): string => node.src
)
).toBe(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPoAAACnAQMAAAACMtNXAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAADUExURX9/f5DKGyMAAAAcSURBVBgZ7cExAQAAAMIg+6deCj9gAAAAAAA8BRWHAAFREbyXAAAAAElFTkSuQmCC"
);
expect(
await firstFifthImg.evaluate((node: HTMLImageElement): string => node.src)
).toBe(
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKcAAAD6AQMAAAD+yMWGAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAADUExURaGhoWkNFFsAAAAcSURBVBgZ7cExAQAAAMIg+6deCU9gAAAAAADcBRV8AAE4UWJ7AAAAAElFTkSuQmCC"
);
});
afterAll(async () => {
const jsCoverage = await page.coverage.stopJSCoverage();
totalJsCoverage.push(...jsCoverage.slice(1));
});
});
afterAll(async () => {
// skips the javascript in the html file
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
await pti.write(totalJsCoverage, {
includeHostname: false,
});
}); | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormQueueItem_Information {
interface tab_general_Sections {
information: DevKit.Controls.Section;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface Tabs {
general: tab_general;
}
interface Body {
Tab: Tabs;
/** Shows the date the record was assigned to the queue. */
EnteredOn: DevKit.Controls.DateTime;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn: DevKit.Controls.DateTime;
/** Choose the queue that the item is assigned to. */
QueueId: DevKit.Controls.Lookup;
/** Shows who is working on the queue item. */
WorkerId: DevKit.Controls.Lookup;
}
interface Footer extends DevKit.Controls.IFooter {
/** Shows whether the queue record is active or inactive. Inactive queue records are read-only and can't be edited unless they are reactivated. */
StateCode: DevKit.Controls.OptionSet;
}
}
class FormQueueItem_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form QueueItem_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form QueueItem_Information */
Body: DevKit.FormQueueItem_Information.Body;
/** The Footer section of form QueueItem_Information */
Footer: DevKit.FormQueueItem_Information.Footer;
}
class QueueItemApi {
/**
* DynamicsCrm.DevKit QueueItemApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date the record was assigned to the queue. */
EnteredOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Unique identifier of the data import or data migration that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who last modified the queueitem. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Liveworkstream this queue item belongs to */
msdyn_liveworkstreamid: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_activitypointer: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_appointment: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_bulkoperation: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_campaignactivity: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_campaignresponse: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_email: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_fax: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_incident: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_knowledgearticle: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_letter: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_approval: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_bookingalert: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_iotalert: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_liveconversation: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_ocsession: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_project: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_projecttask: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_resourcerequest: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_timegroup: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_workorder: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_workorderincident: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_workorderservice: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msfp_alert: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msfp_surveyinvite: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_msfp_surveyresponse: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_phonecall: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_serviceappointment: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_socialactivity: DevKit.WebApi.LookupValue;
/** Choose the activity, case, or article assigned to the queue. */
objectid_task: DevKit.WebApi.LookupValue;
/** Select the type of the queue item, such as activity, case, or appointment. */
ObjectTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Unique identifier of the organization with which the queue item is associated. */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the business unit that owns the queue item. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the queue item. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Choose the queue that the item is assigned to. */
QueueId: DevKit.WebApi.LookupValue;
/** Unique identifier of the queue item. */
QueueItemId: DevKit.WebApi.GuidValue;
/** Shows whether the queue record is active or inactive. Inactive queue records are read-only and can't be edited unless they are reactivated. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the item's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the title or name that describes the queue record. This value is copied from the record that was assigned to the queue. */
Title: DevKit.WebApi.StringValueReadonly;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the queue item. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** Shows who is working on the queue item. */
workerid_systemuser: DevKit.WebApi.LookupValue;
/** Shows who is working on the queue item. */
workerid_team: DevKit.WebApi.LookupValue;
/** Shows the date and time when the queue item was last assigned to a user. */
WorkerIdModifiedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly;
}
}
declare namespace OptionSet {
namespace QueueItem {
enum ObjectTypeCode {
/** 4200 */
Activity,
/** 10414 */
Agreement_Booking_Date,
/** 10419 */
Agreement_Booking_Setup,
/** 10420 */
Agreement_Invoice_Date,
/** 10422 */
Agreement_Invoice_Setup,
/** 4201 */
Appointment,
/** 10294 */
Booking_Alert,
/** 4402 */
Campaign_Activity,
/** 4401 */
Campaign_Response,
/** 112 */
Case,
/** 10564 */
Conversation,
/** 10238 */
Customer_Voice_alert,
/** 10248 */
Customer_Voice_survey_invite,
/** 10250 */
Customer_Voice_survey_response,
/** 4202 */
Email,
/** 4204 */
Fax,
/** 10317 */
Fulfillment_Preference,
/** 10442 */
Inventory_Adjustment,
/** 10445 */
Inventory_Transfer,
/** 10126 */
IoT_Alert,
/** 9953 */
Knowledge_Article,
/** 10061 */
Knowledge_Article_Template,
/** 4207 */
Letter,
/** 10558 */
Ongoing_conversation_Deprecated,
/** 10673 */
Outbound_message,
/** 4210 */
Phone_Call,
/** 10363 */
Project,
/** 10324 */
Project_Service_Approval,
/** 10368 */
Project_Task,
/** 4406 */
Quick_Campaign,
/** 4251 */
Recurring_Appointment,
/** 10386 */
Resource_Request,
/** 4214 */
Service_Activity,
/** 10573 */
Session,
/** 4216 */
Social_Activity,
/** 4212 */
Task,
/** 10318 */
Time_Group_Detail,
/** 10485 */
Work_Order,
/** 10488 */
Work_Order_Incident,
/** 10491 */
Work_Order_Service,
/** 10492 */
Work_Order_Service_Task
}
enum StateCode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum StatusCode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {hasModifierKey, TAB} from '@angular/cdk/keycodes';
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
DoCheck,
ElementRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Self,
ViewEncapsulation,
} from '@angular/core';
import {
ControlValueAccessor,
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from '@angular/forms';
import {
CanUpdateErrorState,
ErrorStateMatcher,
mixinErrorState,
} from '@angular/material-experimental/mdc-core';
import {MatFormFieldControl} from '@angular/material-experimental/mdc-form-field';
import {MatChipTextControl} from './chip-text-control';
import {Observable, Subject, merge} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {MatChipEvent} from './chip';
import {MatChipRow} from './chip-row';
import {MatChipSet} from './chip-set';
import {Directionality} from '@angular/cdk/bidi';
/** Change event object that is emitted when the chip grid value has changed. */
export class MatChipGridChange {
constructor(
/** Chip grid that emitted the event. */
public source: MatChipGrid,
/** Value of the chip grid when the event was emitted. */
public value: any,
) {}
}
/**
* Boilerplate for applying mixins to MatChipGrid.
* @docs-private
*/
class MatChipGridBase extends MatChipSet {
/**
* Emits whenever the component state changes and should cause the parent
* form-field to update. Implemented as part of `MatFormFieldControl`.
* @docs-private
*/
readonly stateChanges = new Subject<void>();
constructor(
elementRef: ElementRef,
changeDetectorRef: ChangeDetectorRef,
dir: Directionality,
public _defaultErrorStateMatcher: ErrorStateMatcher,
public _parentForm: NgForm,
public _parentFormGroup: FormGroupDirective,
/**
* Form control bound to the component.
* Implemented as part of `MatFormFieldControl`.
* @docs-private
*/
public ngControl: NgControl,
) {
super(elementRef, changeDetectorRef, dir);
}
}
const _MatChipGridMixinBase = mixinErrorState(MatChipGridBase);
/**
* An extension of the MatChipSet component used with MatChipRow chips and
* the matChipInputFor directive.
*/
@Component({
selector: 'mat-chip-grid',
template: `
<span class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</span>
`,
styleUrls: ['chip-set.css'],
inputs: ['tabIndex'],
host: {
'class': 'mat-mdc-chip-set mat-mdc-chip-grid mdc-evolution-chip-set',
'[attr.role]': 'role',
'[tabIndex]': '_chips && _chips.length === 0 ? -1 : tabIndex',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': 'errorState',
'[class.mat-mdc-chip-list-disabled]': 'disabled',
'[class.mat-mdc-chip-list-invalid]': 'errorState',
'[class.mat-mdc-chip-list-required]': 'required',
'(focus)': 'focus()',
'(blur)': '_blur()',
},
providers: [{provide: MatFormFieldControl, useExisting: MatChipGrid}],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatChipGrid
extends _MatChipGridMixinBase
implements
AfterContentInit,
AfterViewInit,
CanUpdateErrorState,
ControlValueAccessor,
DoCheck,
MatFormFieldControl<any>,
OnDestroy
{
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
readonly controlType: string = 'mat-chip-grid';
/** The chip input to add more chips */
protected _chipInput: MatChipTextControl;
protected override _defaultRole = 'grid';
/**
* List of element ids to propagate to the chipInput's aria-describedby attribute.
*/
private _ariaDescribedbyIds: string[] = [];
/**
* Function when touched. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onTouched = () => {};
/**
* Function when changed. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onChange: (value: any) => void = () => {};
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
override get disabled(): boolean {
return this.ngControl ? !!this.ngControl.disabled : this._disabled;
}
override set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
this._syncChipsState();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get id(): string {
return this._chipInput.id;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
override get empty(): boolean {
return (
(!this._chipInput || this._chipInput.empty) && (!this._chips || this._chips.length === 0)
);
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get placeholder(): string {
return this._chipInput ? this._chipInput.placeholder : this._placeholder;
}
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
protected _placeholder: string;
/** Whether any chips or the matChipInput inside of this chip-grid has focus. */
override get focused(): boolean {
return this._chipInput.focused || this._hasFocusedChip();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get required(): boolean {
return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
}
set required(value: BooleanInput) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
protected _required: boolean | undefined;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get shouldLabelFloat(): boolean {
return !this.empty || this.focused;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get value(): any {
return this._value;
}
set value(value: any) {
this._value = value;
}
protected _value: any[] = [];
/** An object used to control when error messages are shown. */
@Input() override errorStateMatcher: ErrorStateMatcher;
/** Combined stream of all of the child chips' blur events. */
get chipBlurChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onBlur);
}
/** Emits when the chip grid value has been changed by the user. */
@Output() readonly change: EventEmitter<MatChipGridChange> =
new EventEmitter<MatChipGridChange>();
/**
* Emits whenever the raw value of the chip-grid changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() readonly valueChange: EventEmitter<any> = new EventEmitter<any>();
@ContentChildren(MatChipRow, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
override _chips: QueryList<MatChipRow>;
constructor(
elementRef: ElementRef,
changeDetectorRef: ChangeDetectorRef,
@Optional() dir: Directionality,
@Optional() parentForm: NgForm,
@Optional() parentFormGroup: FormGroupDirective,
defaultErrorStateMatcher: ErrorStateMatcher,
@Optional() @Self() ngControl: NgControl,
) {
super(
elementRef,
changeDetectorRef,
dir,
defaultErrorStateMatcher,
parentForm,
parentFormGroup,
ngControl,
);
if (this.ngControl) {
this.ngControl.valueAccessor = this;
}
}
ngAfterContentInit() {
this.chipBlurChanges.pipe(takeUntil(this._destroyed)).subscribe(() => {
this._blur();
this.stateChanges.next();
});
merge(this.chipFocusChanges, this._chips.changes)
.pipe(takeUntil(this._destroyed))
.subscribe(() => this.stateChanges.next());
}
override ngAfterViewInit() {
super.ngAfterViewInit();
if (!this._chipInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('mat-chip-grid must be used in combination with matChipInputFor.');
}
}
ngDoCheck() {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
}
}
override ngOnDestroy() {
super.ngOnDestroy();
this.stateChanges.complete();
}
/** Associates an HTML input element with this chip grid. */
registerInput(inputElement: MatChipTextControl): void {
this._chipInput = inputElement;
this._chipInput.setDescribedByIds(this._ariaDescribedbyIds);
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
onContainerClick(event: MouseEvent) {
if (!this.disabled && !this._originatesFromChip(event)) {
this.focus();
}
}
/**
* Focuses the first chip in this chip grid, or the associated input when there
* are no eligible chips.
*/
override focus(): void {
if (this.disabled || this._chipInput.focused) {
return;
}
if (!this._chips.length || this._chips.first.disabled) {
// Delay until the next tick, because this can cause a "changed after checked"
// error if the input does something on focus (e.g. opens an autocomplete).
Promise.resolve().then(() => this._chipInput.focus());
} else if (this._chips.length) {
this._keyManager.setFirstItemActive();
}
this.stateChanges.next();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
setDescribedByIds(ids: string[]) {
// We must keep this up to date to handle the case where ids are set
// before the chip input is registered.
this._ariaDescribedbyIds = ids;
if (this._chipInput) {
// Use a setTimeout in case this is being run during change detection
// and the chip input has already determined its host binding for
// aria-describedBy.
setTimeout(() => {
this._chipInput.setDescribedByIds(ids);
}, 0);
}
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
writeValue(value: any): void {
// The user is responsible for creating the child chips, so we just store the value.
this._value = value;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.stateChanges.next();
}
/** When blurred, mark the field as touched when focus moved outside the chip grid. */
_blur() {
if (!this.disabled) {
// Check whether the focus moved to chip input.
// If the focus is not moved to chip input, mark the field as touched. If the focus moved
// to chip input, do nothing.
// Timeout is needed to wait for the focus() event trigger on chip input.
setTimeout(() => {
if (!this.focused) {
this._propagateChanges();
this._markAsTouched();
}
});
}
}
/**
* Removes the `tabindex` from the chip grid and resets it back afterwards, allowing the
* user to tab out of it. This prevents the grid from capturing focus and redirecting
* it back to the first chip, creating a focus trap, if it user tries to tab away.
*/
protected override _allowFocusEscape() {
if (!this._chipInput.focused) {
super._allowFocusEscape();
}
}
/** Handles custom keyboard events. */
override _handleKeydown(event: KeyboardEvent) {
if (event.keyCode === TAB) {
if (
this._chipInput.focused &&
hasModifierKey(event, 'shiftKey') &&
this._chips.length &&
!this._chips.last.disabled
) {
event.preventDefault();
if (this._keyManager.activeItem) {
this._keyManager.setActiveItem(this._keyManager.activeItem);
} else {
this._focusLastChip();
}
} else {
// Use the super method here since it doesn't check for the input
// focused state. This allows focus to escape if there's only one
// disabled chip left in the list.
super._allowFocusEscape();
}
} else if (!this._chipInput.focused) {
super._handleKeydown(event);
}
this.stateChanges.next();
}
_focusLastChip() {
if (this._chips.length) {
this._chips.last.focus();
}
}
/** Emits change event to set the model value. */
private _propagateChanges(): void {
const valueToEmit = this._chips.length ? this._chips.toArray().map(chip => chip.value) : [];
this._value = valueToEmit;
this.change.emit(new MatChipGridChange(this, valueToEmit));
this.valueChange.emit(valueToEmit);
this._onChange(valueToEmit);
this._changeDetectorRef.markForCheck();
}
/** Mark the field as touched */
private _markAsTouched() {
this._onTouched();
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
} | the_stack |
import React, { Component } from 'react'
import { PropTypes, connect, Link, replace, _ } from '../../family'
import { serve } from '../../relatives/services/constant'
import { Spin } from '../utils'
import RepositoryForm from '../repository/RepositoryForm'
import RepositorySearcher from './RepositorySearcher'
import ModuleList from './ModuleList'
import InterfaceList from './InterfaceList'
import InterfaceEditor from './InterfaceEditor'
import DuplicatedInterfacesWarning from './DuplicatedInterfacesWarning'
import { addRepository, updateRepository, clearRepository, fetchRepository } from '../../actions/repository'
import { addModule, updateModule, deleteModule, sortModuleList } from '../../actions/module'
import { addInterface, updateInterface, deleteInterface, lockInterface, unlockInterface } from '../../actions/interface'
import { addProperty, updateProperty, deleteProperty, updateProperties, sortPropertyList } from '../../actions/property'
import { GoRepo, GoVersions, GoPlug, GoDatabase, GoCode, GoLinkExternal, GoPencil, GoEllipsis } from 'react-icons/go'
import { FaHistory } from 'react-icons/fa'
import './RepositoryEditor.css'
import ExportPostmanForm from '../repository/ExportPostmanForm'
import ImportSwaggerRepositoryForm from '../repository/ImportSwaggerRepositoryForm'
import { RootState, Repository, Module, Interface } from 'actions/types'
import DefaultValueModal from './DefaultValueModal'
import RapperInstallerModal from './RapperInstallerModal'
import HistoryLogDrawer from './HistoryLogDrawer'
import Joyride from 'react-joyride'
import { Typography } from '@material-ui/core'
import { doFetchUserSettings, updateUserSetting } from 'actions/account'
import Markdown from 'markdown-to-jsx'
import { CACHE_KEY, ENTITY_TYPE } from 'utils/consts'
// DONE 2.1 import Spin from '../utils/Spin'
// TODO 2.2 缺少测试器
// DONE 2.2 各种空数据下的视觉效果:空仓库、空模块、空接口、空属性
// TODO 2.1 大数据测试,含有大量模块、接口、属性的仓库
interface Props {
auth: any
repository: any
location: any
onClearRepository: any
replace: any
router: any
doFetchUserSettings: typeof doFetchUserSettings
updateUserSetting: typeof updateUserSetting
}
interface States {
rapperInstallerModalOpen: boolean
defaultValuesModalOpen: boolean
historyLogDrawerOpen: boolean
update: boolean
exportPostman: boolean
importSwagger: boolean
guideOpen: boolean
}
// 展示组件
class RepositoryEditor extends Component<Props, States> {
static propTypes = {
auth: PropTypes.object.isRequired,
repository: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
onClearRepository: PropTypes.func.isRequired,
}
static childContextTypes = {
onAddRepository: PropTypes.func.isRequired,
onUpdateRepository: PropTypes.func.isRequired,
onAddModule: PropTypes.func.isRequired,
onUpdateModule: PropTypes.func.isRequired,
onDeleteModule: PropTypes.func.isRequired,
onSortModuleList: PropTypes.func.isRequired,
onAddInterface: PropTypes.func.isRequired,
onUpdateInterface: PropTypes.func.isRequired,
onDeleteInterface: PropTypes.func.isRequired,
onLockInterface: PropTypes.func.isRequired,
onUnlockInterface: PropTypes.func.isRequired,
onAddProperty: PropTypes.func.isRequired,
onUpdateProperty: PropTypes.func.isRequired,
onUpdateProperties: PropTypes.func.isRequired,
onDeleteProperty: PropTypes.func.isRequired,
onSortPropertyList: PropTypes.func.isRequired,
}
constructor(props: any) {
super(props)
this.state = {
update: false,
exportPostman: false,
rapperInstallerModalOpen: false,
defaultValuesModalOpen: false,
importSwagger: false,
historyLogDrawerOpen: false,
guideOpen: false,
}
}
getChildContext() {
return _.pick(this.props, Object.keys(RepositoryEditor.childContextTypes))
}
changeDocumentTitle() {
const repository = this.props.repository.data
if (repository && repository.name) {
document.title = `RAP2 ${repository.name}`
}
}
componentDidUpdate() {
this.changeDocumentTitle()
}
componentDidMount() {
this.changeDocumentTitle()
this.props.doFetchUserSettings([CACHE_KEY.GUIDE_20200714], (isOk, payload) => {
const open = !payload.data?.GUIDE_20200714
if (open) {
this.setState({ guideOpen: true })
this.props.updateUserSetting(CACHE_KEY.GUIDE_20200714, '1')
}
})
}
componentWillUnmount() {
document.title = `RAP2`
}
render() {
const {
location: { params },
} = this.props
const { repository: repositoryAsync } = this.props
if (!repositoryAsync.fetching && !repositoryAsync.data) {
return <div className="p100 fontsize-30 text-center">未找到对应仓库</div>
}
if (repositoryAsync.fetching || !repositoryAsync.data || !repositoryAsync.data.id) {
return <Spin />
}
const repository: Repository = repositoryAsync.data
if (repository.name) {
document.title = `RAP2 ${repository.name}`
}
let mod =
repository && repository.modules && repository.modules.length
? repository.modules.find((item: any) => item.id === +params.mod) || repository.modules[0]
: null
if (!(+params.mod > 0) && +params.itf > 0) {
const tryMods = repository?.modules?.filter(m => m.interfaces.map(x => x.id).indexOf(+params.itf) > -1)
if (tryMods && tryMods[0]) {
mod = tryMods[0]
}
}
const itf =
mod?.interfaces && mod?.interfaces?.length
? mod?.interfaces?.find((item: any) => item.id === +params.itf) || mod?.interfaces[0]
: {}
const ownerlink = repository.organization
? `/organization/repository?organization=${repository.organization.id}`
: `/repository/joined?user=${repository.owner.id}`
return (
<article className="RepositoryEditor">
<div className="header">
<span className="title">
<GoRepo className="mr6 color-9" />
<Link to={`${ownerlink}`} className="g-link">
{repository.organization ? repository.organization.name : repository.owner.fullname}
</Link>
<span className="slash"> / </span>
<span>{repository.name}</span>
</span>
<div className="toolbar">
{/* 编辑权限:拥有者或者成员 */}
{repository.canUserEdit ? (
<span className="g-link edit mr1" onClick={() => this.setState({ update: true })}>
<GoPencil /> 编辑
</span>
) : null}
<RepositoryForm
open={this.state.update}
onClose={ok => {
ok && this.handleUpdate()
this.setState({ update: false })
}}
title="编辑仓库"
repository={repository}
/>
<a
href={`${serve}/app/plugin/${repository.id}`}
target="_blank"
rel="noopener noreferrer"
className="g-link"
>
<GoPlug /> 插件
</a>
<a
href={`${serve}/repository/get?id=${repository.id}&token=${repository.token}`}
target="_blank"
rel="noopener noreferrer"
className="g-link"
>
<GoDatabase /> 数据
</a>
<span className="g-link edit mr1" onClick={() => this.setState({ importSwagger: true })}>
<GoLinkExternal /> 导入
</span>
<ImportSwaggerRepositoryForm
open={this.state.importSwagger}
onClose={ok => {
ok && this.handleUpdate()
this.setState({ importSwagger: false })
}}
repositoryId={repository.id}
orgId={(repository.organization || {}).id}
modId={+mod?.id || 0}
mode="manual"
/>
<span className="g-link edit mr1" onClick={() => this.setState({ exportPostman: true })}>
<GoLinkExternal /> 导出
</span>
<ExportPostmanForm
title="导出"
open={this.state.exportPostman}
repoId={repository.id}
onClose={() => this.setState({ exportPostman: false })}
/>
<span
className="g-link edit mr1"
onClick={() => this.setState({ defaultValuesModalOpen: true })}
>
<GoEllipsis /> 默认值
</span>
<span
className="g-link edit mr1 guide-1"
onClick={() => this.setState({ historyLogDrawerOpen: true })}
>
<FaHistory /> 历史
</span>
<DefaultValueModal
open={this.state.defaultValuesModalOpen}
handleClose={() => this.setState({ defaultValuesModalOpen: false })}
repositoryId={repository.id}
/>
<HistoryLogDrawer
open={this.state.historyLogDrawerOpen}
onClose={() => this.setState({ historyLogDrawerOpen: false })}
entityId={repository?.id}
entityType={ENTITY_TYPE.REPOSITORY}
/>
<span
className="g-link edit"
onClick={() => this.setState({ rapperInstallerModalOpen: true })}
>
<GoCode /> Rapper
</span>
<RapperInstallerModal
open={this.state.rapperInstallerModalOpen}
handleClose={() => this.setState({ rapperInstallerModalOpen: false })}
repository={repository}
/>
</div>
<RepositorySearcher repository={repository} />
<div className="desc"><Markdown>{repository.description || ''}</Markdown></div>
{this.renderRelatedProjects()}
<DuplicatedInterfacesWarning repository={repository} />
</div>
<div className="body">
<ModuleList mods={repository.modules} repository={repository} mod={mod} />
<div className="InterfaceWrapper">
<InterfaceList itfs={mod?.interfaces || []} repository={repository} mod={mod} itf={itf} />
<InterfaceEditor itf={itf} mod={mod} repository={repository} />
</div>
</div>
<Joyride
continuous={true}
scrollToFirstStep={true}
showProgress={true}
showSkipButton={true}
run={this.state.guideOpen}
locale={{
skip: '跳过',
next: '下一步',
back: '上一步',
last: '完成',
}}
steps={[
{
title: '历史记录上线',
disableBeacon: true,
content: <Typography variant="h6">现在您可以查看项目修改历史了!</Typography>,
placement: 'top',
target: '.guide-1',
},
{
title: '历史记录上线',
disableBeacon: true,
content: <Typography variant="h6">您也可以查看指定接口的所有改动记录。</Typography>,
placement: 'top',
target: '.guide-2',
}, {
title: '皮肤自定义上线',
disableBeacon: true,
content: <Typography variant="h6">在系统偏好设置里,选择一个喜爱的颜色吧!比如原谅绿?</Typography>,
placement: 'top',
target: '.guide-3',
}
]}
/>
</article>
)
}
renderRelatedProjects() {
const { repository } = this.props
const { collaborators } = repository.data
return (
<div className="RelatedProjects">
{collaborators &&
Array.isArray(collaborators) &&
collaborators.map(collab => (
<div className="CollabProject Project" key={`collab-${collab.id}`}>
<span className="title">
<GoVersions className="mr5" />
协同
</span>
<Link to={`/repository/editor?id=${collab.id}`}>{collab.name}</Link>
</div>
))}
</div>
)
}
handleUpdate = () => {
const { pathname, hash, search } = this.props.router.location
this.props.replace(pathname + search + hash)
}
}
// 容器组件
const mapStateToProps = (state: RootState) => ({
auth: state.auth,
repository: state.repository,
router: state.router,
})
const mapDispatchToProps = {
onFetchRepository: fetchRepository,
onAddRepository: addRepository,
onUpdateRepository: updateRepository,
onClearRepository: clearRepository,
onAddModule: addModule,
onUpdateModule: updateModule,
onDeleteModule: deleteModule,
onSortModuleList: sortModuleList,
onAddInterface: addInterface,
onUpdateInterface: updateInterface,
onDeleteInterface: deleteInterface,
onLockInterface: lockInterface,
onUnlockInterface: unlockInterface,
onAddProperty: addProperty,
onUpdateProperty: updateProperty,
onUpdateProperties: updateProperties,
onDeleteProperty: deleteProperty,
onSortPropertyList: sortPropertyList,
replace,
doFetchUserSettings,
updateUserSetting,
}
export default connect(mapStateToProps, mapDispatchToProps)(RepositoryEditor) | the_stack |
import * as path from 'path';
import {
BlockDeviceVolume,
} from '@aws-cdk/aws-autoscaling';
import {
AmazonLinuxGeneration,
Connections,
IConnectable,
InstanceType,
ISecurityGroup,
IVolume,
IVpc,
MachineImage,
SubnetSelection,
UserData,
Volume,
} from '@aws-cdk/aws-ec2';
import {
IGrantable,
IPrincipal,
IRole,
} from '@aws-cdk/aws-iam';
import {
IKey,
} from '@aws-cdk/aws-kms';
import {
ARecord,
IPrivateHostedZone,
RecordTarget,
} from '@aws-cdk/aws-route53';
import {
Asset,
} from '@aws-cdk/aws-s3-assets';
import {
ISecret,
Secret,
} from '@aws-cdk/aws-secretsmanager';
import {
Construct,
Duration,
IConstruct,
Names,
Size,
} from '@aws-cdk/core';
import {
BlockVolumeFormat,
CloudWatchAgent,
CloudWatchConfigBuilder,
IScriptHost,
IX509CertificatePem,
LogGroupFactory,
LogGroupFactoryProps,
MongoDbInstaller,
MongoDbSsplLicenseAcceptance,
MongoDbVersion,
MountableBlockVolume,
StaticPrivateIpServer,
} from './';
import {
tagConstruct,
} from './runtime-info';
/**
* Specification for a when a new volume is being created by a MongoDbInstance.
*/
export interface MongoDbInstanceNewVolumeProps {
/**
* The size, in Gigabytes, of a new encrypted volume to be created to hold the MongoDB database
* data for this instance. A new volume is created only if a value for the volume property
* is not provided.
*
* @default 20 GiB
*/
readonly size?: Size;
/**
* If creating a new EBS Volume, then this property provides a KMS key to use to encrypt
* the Volume's data. If you do not provide a value for this property, then your default
* service-owned KMS key will be used to encrypt the new Volume.
*
* @default Your service-owned KMS key is used to encrypt a new volume.
*/
readonly encryptionKey?: IKey;
}
/**
* Specification of the Amazon Elastic Block Storage (EBS) Volume that will be used by
* a {@link MongoDbInstance} to store the MongoDB database's data.
*
* You must provide either an existing EBS Volume to mount to the instance, or the
* {@link MongoDbInstance} will create a new EBS Volume of the given size that is
* encrypted. The encryption will be with the given KMS key, if one is provided.
*/
export interface MongoDbInstanceVolumeProps {
/**
* An existing EBS volume. This volume is mounted to the {@link MongoDbInstace} using
* the scripting in {@link MountableEbs}, and is subject to the restrictions outlined
* in that class.
*
* The Volume must not be partitioned. The volume will be mounted to /var/lib/mongo on this instance,
* and all files on it will be changed to be owned by the mongod user on the instance.
*
* This volume will contain all of the data that you store in MongoDB, so we recommend that you
* encrypt this volume.
*
* @default A new encrypted volume is created for use by the instance.
*/
readonly volume?: IVolume;
/**
* Properties for a new volume that will be constructed for use by this instance.
*
* @default A service-key encrypted 20Gb volume will be created.
*/
readonly volumeProps?: MongoDbInstanceNewVolumeProps;
}
/**
* Settings for the MongoDB application that will be running on a {@link MongoDbInstance}.
*/
export interface MongoDbApplicationProps {
/**
* MongoDB Community edition is licensed under the terms of the SSPL (see: https://www.mongodb.com/licensing/server-side-public-license ).
* Users of MongoDbInstance must explicitly signify their acceptance of the terms of the SSPL through this
* property before the {@link MongoDbInstance} will be allowed to install MongoDB.
*
* @default MongoDbSsplLicenseAcceptance.USER_REJECTS_SSPL
*/
readonly userSsplAcceptance?: MongoDbSsplLicenseAcceptance;
/**
* What version of MongoDB to install on the instance.
*/
readonly version: MongoDbVersion;
/**
* Private DNS zone to register the MongoDB hostname within. An A Record will automatically be created
* within this DNS zone for the provided hostname to allow connection to MongoDB's static private IP.
*/
readonly dnsZone: IPrivateHostedZone;
/**
* The hostname to register the MongoDB's listening interface as. The hostname must be
* from 1 to 63 characters long and may contain only the letters from a-z, digits from 0-9,
* and the hyphen character.
*
* The fully qualified domain name (FQDN) of this host will be this hostname dot the zoneName
* of the given dnsZone.
*/
readonly hostname: string;
/**
* A certificate that provides proof of identity for the MongoDB application. The DomainName, or
* CommonName, of the provided certificate must exactly match the fully qualified host name
* of this host. This certificate must not be self-signed; that is the given certificate must have
* a defined certChain property.
*
* This certificate will be used to secure encrypted network connections to the MongoDB application
* with the clients that connect to it.
*/
readonly serverCertificate: IX509CertificatePem;
/**
* A secret containing credentials for the admin user of the database. The contents of this
* secret must be a JSON document with the keys "username" and "password". ex:
* {
* "username": <admin user name>,
* "password": <admin user password>,
* }
* If this user already exists in the database, then its credentials will not be modified in any way
* to match the credentials in this secret. Doing so automatically would be a security risk.
*
* If created, then the admin user will have the database role:
* [ { role: 'userAdminAnyDatabase', db: 'admin' }, 'readWriteAnyDatabase' ]
*
* @default Credentials will be randomly generated for the admin user.
*/
readonly adminUser?: ISecret;
/**
* Specification of the Amazon Elastic Block Storage (EBS) Volume that will be used by
* the instance to store the MongoDB database's data.
*
* The Volume must not be partitioned. The volume will be mounted to /var/lib/mongo on this instance,
* and all files on it will be changed to be owned by the mongod user on the instance.
*
* @default A new 20 GiB encrypted EBS volume is created to store the MongoDB database data.
*/
readonly mongoDataVolume?: MongoDbInstanceVolumeProps;
}
/**
* Properties for a newly created {@link MongoDbInstance}.
*/
export interface MongoDbInstanceProps {
/**
* Properties for the MongoDB application that will be running on the instance.
*/
readonly mongoDb: MongoDbApplicationProps;
/**
* The VPC in which to create the MongoDbInstance.
*/
readonly vpc: IVpc;
/**
* Where to place the instance within the VPC.
*
* @default The instance is placed within a Private subnet.
*/
readonly vpcSubnets?: SubnetSelection;
/**
* The type of instance to launch. Note that this must be an x86-64 instance type.
*
* @default r5.large
*/
readonly instanceType?: InstanceType;
/**
* Name of the EC2 SSH keypair to grant access to the instance.
*
* @default No SSH access will be possible.
*/
readonly keyName?: string;
/**
* Properties for setting up the MongoDB Instance's LogGroup in CloudWatch
*
* @default - LogGroup will be created with all properties' default values to the LogGroup: /renderfarm/<construct id>
*/
readonly logGroupProps?: LogGroupFactoryProps;
/**
* An IAM role to associate with the instance profile that is assigned to this instance.
* The role must be assumable by the service principal `ec2.amazonaws.com`
*
* @default A role will automatically be created, it can be accessed via the `role` property.
*/
readonly role?: IRole;
/**
* The security group to assign to this instance.
*
* @default A new security group is created for this instance.
*/
readonly securityGroup?: ISecurityGroup;
}
/**
* Essential properties of a MongoDB database.
*/
export interface IMongoDb extends IConnectable, IConstruct {
/**
* Credentials for the admin user of the database. This user has database role:
* [ { role: 'userAdminAnyDatabase', db: 'admin' }, 'readWriteAnyDatabase' ]
*/
readonly adminUser: ISecret;
/**
* The certificate chain of trust for the MongoDB application's server certificate.
* The contents of this secret is a single string containing the trust chain in PEM format, and
* can be saved to a file that is then passed as the --sslCAFile option when connecting to MongoDB
* using the mongo shell.
*/
readonly certificateChain: ISecret;
/**
* The full host name that can be used to connect to the MongoDB application running on this
* instance.
*/
readonly fullHostname: string;
/**
* The port to connect to for MongoDB.
*/
readonly port: number;
/**
* The version of MongoDB that is running on this instance.
*/
readonly version: MongoDbVersion;
/**
* Adds security groups to the database.
* @param securityGroups The security groups to add.
*/
addSecurityGroup(...securityGroups: ISecurityGroup[]): void;
}
/**
* This construct provides a {@link StaticPrivateIpServer} that is hosting MongoDB. The data for this MongoDB database
* is stored in an Amazon Elastic Block Storage (EBS) Volume that is automatically attached to the instance when it is
* launched, and is separate from the instance's root volume; it is recommended that you set up a backup schedule for
* this volume.
*
* When this instance is first launched, or relaunched after an instance replacement, it will:
* 1. Attach an EBS volume to /var/lib/mongo upon which the MongoDB data is stored;
* 2. Automatically install the specified version of MongoDB, from the official Mongo Inc. sources;
* 3. Create an admin user in that database if one has not yet been created -- the credentials for this user
* can be provided by you, or randomly generated;
* 4. Configure MongoDB to require authentication, and only allow encrypted connections over TLS.
*
* The instance's launch logs and MongoDB logs will be automatically stored in Amazon CloudWatch logs; the
* default log group name is: /renderfarm/<this construct ID>
*
* Resources Deployed
* ------------------------
* - {@link StaticPrivateIpServer} that hosts MongoDB.
* - An A-Record in the provided PrivateHostedZone to create a DNS entry for this server's static private IP.
* - A Secret in AWS SecretsManager that contains the administrator credentials for MongoDB.
* - An encrypted Amazon Elastic Block Store (EBS) Volume on which the MongoDB data is stored.
* - Amazon CloudWatch log group that contains instance-launch and MongoDB application logs.
*
* Security Considerations
* ------------------------
* - The administrator credentials for MongoDB are stored in a Secret within AWS SecretsManager. You must strictly limit
* access to this secret to only entities that require it.
* - The instances deployed by this construct download and run scripts from your CDK bootstrap bucket when that instance
* is launched. You must limit write access to your CDK bootstrap bucket to prevent an attacker from modifying the actions
* performed by these scripts. We strongly recommend that you either enable Amazon S3 server access logging on your CDK
* bootstrap bucket, or enable AWS CloudTrail on your account to assist in post-incident analysis of compromised production
* environments.
* - The EBS Volume that is created by, or provided to, this construct is used to store the contents of your MongoDB data. To
* protect the sensitive data in your database, you should not grant access to this EBS Volume to any principal or instance
* other than the instance created by this construct. Furthermore, we recommend that you ensure that the volume that is
* used for this purpose is encrypted at rest.
* - This construct uses this package's {@link StaticPrivateIpServer}, {@link MongoDbInstaller}, {@link CloudWatchAgent},
* {@link ExportingLogGroup}, and {@link MountableBlockVolume}. Security considerations that are outlined by the documentation
* for those constructs should also be taken into account.
*/
export class MongoDbInstance extends Construct implements IMongoDb, IGrantable {
// How often Cloudwatch logs will be flushed.
private static CLOUDWATCH_LOG_FLUSH_INTERVAL: Duration = Duration.seconds(15);
// Default prefix for a LogGroup if one isn't provided in the props.
private static DEFAULT_LOG_GROUP_PREFIX: string = '/renderfarm/';
// Size of the EBS volume for MongoDB data, if we create one.
private static DEFAULT_MONGO_DEVICE_SIZE = Size.gibibytes(20);
// Mount point for the MongoDB data volume.
private static MONGO_DEVICE_MOUNT_POINT = '/var/lib/mongo';
// Size of the root device volume on the instance.
private static ROOT_DEVICE_SIZE = Size.gibibytes(10);
/**
* Credentials for the admin user of the database. This user has database role:
* [ { role: 'userAdminAnyDatabase', db: 'admin' }, 'readWriteAnyDatabase' ]
*/
public readonly adminUser: ISecret;
/**
* @inheritdoc
*/
public readonly certificateChain: ISecret;
/**
* Allows for providing security group connections to/from this instance.
*/
public readonly connections: Connections;
/**
* The principal to grant permission to. Granting permissions to this principal will grant
* those permissions to the instance role.
*/
public readonly grantPrincipal: IPrincipal;
/**
* @inheritdoc
*/
public readonly fullHostname: string;
/**
* The server that this construct creates to host MongoDB.
*/
public readonly server: StaticPrivateIpServer;
/**
* The EBS Volume on which we are storing the MongoDB database data.
*/
public readonly mongoDataVolume: IVolume;
/**
* The port to connect to for MongoDB.
*/
public readonly port: number;
/**
* The IAM role that is assumed by the instance.
*/
public readonly role: IRole;
/**
* The UserData for this instance.
* UserData is a script that is run automatically by the instance the very first time that a new instance is started.
*/
public readonly userData: UserData;
/**
* The version of MongoDB that is running on this instance.
*/
public readonly version: MongoDbVersion;
constructor(scope: Construct, id: string, props: MongoDbInstanceProps) {
super(scope, id);
this.version = props.mongoDb.version;
// Select the subnet for this instance.
const { subnets } = props.vpc.selectSubnets(props.vpcSubnets);
if (subnets.length === 0) {
throw new Error(`Did not find any subnets matching ${JSON.stringify(props.vpcSubnets)}. Please use a different selection.`);
}
const subnet = subnets[0];
this.server = new StaticPrivateIpServer(this, 'Server', {
vpc: props.vpc,
vpcSubnets: { subnets: [ subnet ] },
instanceType: props.instanceType ?? new InstanceType('r5.large'),
machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }),
blockDevices: [
{
deviceName: '/dev/xvda', // Root volume
volume: BlockDeviceVolume.ebs(MongoDbInstance.ROOT_DEVICE_SIZE.toGibibytes(), { encrypted: true }),
},
],
keyName: props.keyName,
resourceSignalTimeout: Duration.minutes(5),
role: props.role,
securityGroup: props.securityGroup,
});
new ARecord(this, 'ARecord', {
target: RecordTarget.fromIpAddresses(this.server.privateIpAddress),
zone: props.mongoDb.dnsZone,
recordName: props.mongoDb.hostname,
});
this.adminUser = props.mongoDb.adminUser ?? new Secret(this, 'AdminUser', {
description: `Admin credentials for the MongoDB database ${Names.uniqueId(this)}`,
generateSecretString: {
excludeCharacters: '"()$\'', // Exclude characters that might interact with command shells.
excludePunctuation: true,
includeSpace: false,
passwordLength: 24,
requireEachIncludedType: true,
generateStringKey: 'password',
secretStringTemplate: JSON.stringify({ username: 'admin' }),
},
});
this.mongoDataVolume = props.mongoDb.mongoDataVolume?.volume ?? new Volume(this, 'MongoDbData', {
size: MongoDbInstance.DEFAULT_MONGO_DEVICE_SIZE, // First so it can be overriden by the next entry
...props.mongoDb.mongoDataVolume?.volumeProps,
availabilityZone: subnet.availabilityZone,
encrypted: true,
});
const volumeMount = new MountableBlockVolume(this, {
blockVolume: this.mongoDataVolume,
volumeFormat: BlockVolumeFormat.XFS,
});
const mongoInstaller = new MongoDbInstaller(this, {
version: props.mongoDb.version,
userSsplAcceptance: props.mongoDb.userSsplAcceptance,
});
// Set up the server's UserData.
this.server.userData.addCommands('set -xefuo pipefail');
this.server.userData.addSignalOnExitCommand(this.server.autoscalingGroup);
this.configureCloudWatchLogStreams(this.server, id, props.logGroupProps); // MUST BE FIRST
volumeMount.mountToLinuxInstance(this.server, {
location: MongoDbInstance.MONGO_DEVICE_MOUNT_POINT,
});
mongoInstaller.installOnLinuxInstance(this.server);
this.configureMongoDb(this.server, props.mongoDb);
this.certificateChain = props.mongoDb.serverCertificate.certChain!;
this.connections = this.server.connections;
this.grantPrincipal = this.server.grantPrincipal;
this.port = 27017;
this.role = this.server.role;
this.userData = this.server.userData;
this.fullHostname = `${props.mongoDb.hostname}.${props.mongoDb.dnsZone.zoneName}`;
this.node.defaultChild = this.server;
// Tag deployed resources with RFDK meta-data
tagConstruct(this);
}
/**
* @inheritdoc
*/
public addSecurityGroup(...securityGroups: ISecurityGroup[]): void {
securityGroups?.forEach(securityGroup => this.server.autoscalingGroup.addSecurityGroup(securityGroup));
}
/**
* Adds UserData commands to install & configure the CloudWatch Agent onto the instance.
*
* The commands configure the agent to stream the following logs to a new CloudWatch log group:
* - The cloud-init log
* - The MongoDB application log.
*
* @param host The instance/host to setup the CloudWatchAgent upon.
* @param groupName Name to append to the log group prefix when forming the log group name.
* @param logGroupProps Properties for the log group
*/
protected configureCloudWatchLogStreams(host: IScriptHost, groupName: string, logGroupProps?: LogGroupFactoryProps) {
const prefix = logGroupProps?.logGroupPrefix ?? MongoDbInstance.DEFAULT_LOG_GROUP_PREFIX;
const defaultedLogGroupProps = {
...logGroupProps,
logGroupPrefix: prefix,
};
const logGroup = LogGroupFactory.createOrFetch(this, 'MongoDbInstanceLogGroupWrapper', groupName, defaultedLogGroupProps);
logGroup.grantWrite(host.grantPrincipal);
const cloudWatchConfigurationBuilder = new CloudWatchConfigBuilder(MongoDbInstance.CLOUDWATCH_LOG_FLUSH_INTERVAL);
cloudWatchConfigurationBuilder.addLogsCollectList(logGroup.logGroupName,
'cloud-init-output',
'/var/log/cloud-init-output.log');
cloudWatchConfigurationBuilder.addLogsCollectList(logGroup.logGroupName,
'MongoDB',
'/var/log/mongodb/mongod.log');
new CloudWatchAgent(this, 'MongoDbInstanceLogsConfig', {
cloudWatchConfig: cloudWatchConfigurationBuilder.generateCloudWatchConfiguration(),
host,
});
}
/**
* Adds commands to the userData of the instance to install MongoDB, create an admin user if one does not exist, and
* to to start mongod running.
*/
protected configureMongoDb(instance: StaticPrivateIpServer, settings: MongoDbApplicationProps) {
const scriptsAsset = new Asset(this, 'MongoSetup', {
path: path.join(__dirname, '..', 'scripts', 'mongodb', settings.version),
});
scriptsAsset.grantRead(instance.grantPrincipal);
const scriptZipfile = instance.userData.addS3DownloadCommand({
bucket: scriptsAsset.bucket,
bucketKey: scriptsAsset.s3ObjectKey,
});
instance.userData.addCommands(
// Ensure mongod is installed and stopped before we go any further
'which mongod && test -f /etc/mongod.conf',
'sudo service mongod stop',
// We're going to make a temporary RAM filesystem for the mongo setup files.
// This will let us write sensitive data to "disk" without worrying about it
// being persisted in any physical disk, even temporarily.
'MONGO_SETUP_DIR=$(mktemp -d)',
'mkdir -p "${MONGO_SETUP_DIR}"',
'sudo mount -t tmpfs -o size=50M tmpfs "${MONGO_SETUP_DIR}"',
'pushd "${MONGO_SETUP_DIR}"',
`unzip ${scriptZipfile}`,
// Backup mongod.conf for now
'cp /etc/mongod.conf .',
);
const cert = settings.serverCertificate;
instance.userData.addCommands(
`bash serverCertFromSecrets.sh "${cert.cert.secretArn}" "${cert.certChain!.secretArn}" "${cert.key.secretArn}" "${cert.passphrase.secretArn}"`,
);
cert.cert.grantRead(instance.grantPrincipal);
cert.certChain!.grantRead(instance.grantPrincipal);
cert.key.grantRead(instance.grantPrincipal);
cert.passphrase.grantRead(instance.grantPrincipal);
const certsDirectory = '/etc/mongod_certs';
instance.userData.addCommands(
// Move the certificates into place
`sudo mkdir -p ${certsDirectory}`,
`sudo mv ./ca.crt ./key.pem ${certsDirectory}`,
'sudo chown root.mongod -R /etc/mongod_certs/', // Something weird about shell interpretation. Can't use '*' on this or next line.
'sudo chmod 640 -R /etc/mongod_certs/',
'sudo chmod 750 /etc/mongod_certs/', // Directory needs to be executable.
// mongod user id might, potentially change on reboot. Make sure we own all mongo data
`sudo chown mongod.mongod -R ${MongoDbInstance.MONGO_DEVICE_MOUNT_POINT}`,
// Configure mongod
'bash ./setMongoLimits.sh',
`bash ./setStoragePath.sh "${MongoDbInstance.MONGO_DEVICE_MOUNT_POINT}"`,
'bash ./setMongoNoAuth.sh',
'sudo service mongod start',
`bash ./setAdminCredentials.sh "${this.adminUser.secretArn}"`,
);
this.adminUser.grantRead(instance.grantPrincipal);
instance.userData.addCommands(
// Setup for live deployment, and start mongod
'sudo service mongod stop',
'bash ./setLiveConfiguration.sh',
'sudo systemctl enable mongod', // Enable restart on reboot
'sudo service mongod start',
'popd',
);
instance.userData.addOnExitCommands(
// Clean up the temporary RAM filesystem
'test "${MONGO_SETUP_DIR} != "" && sudo umount "${MONGO_SETUP_DIR}',
);
}
} | the_stack |
import * as moment from "moment";
export interface Domain {
readonly id?: string;
readonly name?: string;
/**
* Possible values include: 'Classification', 'ObjectDetection'
*/
readonly type?: string;
readonly exportable?: boolean;
readonly enabled?: boolean;
}
/**
* Entry associating a tag to an image.
*/
export interface ImageTagCreateEntry {
/**
* Id of the image.
*/
imageId?: string;
/**
* Id of the tag.
*/
tagId?: string;
}
/**
* Batch of image tags.
*/
export interface ImageTagCreateBatch {
/**
* Image Tag entries to include in this batch.
*/
tags?: ImageTagCreateEntry[];
}
export interface ImageTagCreateSummary {
created?: ImageTagCreateEntry[];
duplicated?: ImageTagCreateEntry[];
exceeded?: ImageTagCreateEntry[];
}
/**
* Entry associating a region to an image.
*/
export interface ImageRegionCreateEntry {
/**
* Id of the image.
*/
imageId: string;
/**
* Id of the tag associated with this region.
*/
tagId: string;
/**
* Coordinate of the left boundary.
*/
left: number;
/**
* Coordinate of the top boundary.
*/
top: number;
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
/**
* Batch of image region information to create.
*/
export interface ImageRegionCreateBatch {
regions?: ImageRegionCreateEntry[];
}
export interface ImageRegionCreateResult {
readonly imageId?: string;
readonly regionId?: string;
readonly tagName?: string;
readonly created?: Date;
/**
* Id of the tag associated with this region.
*/
tagId: string;
/**
* Coordinate of the left boundary.
*/
left: number;
/**
* Coordinate of the top boundary.
*/
top: number;
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
export interface ImageRegionCreateSummary {
created?: ImageRegionCreateResult[];
duplicated?: ImageRegionCreateEntry[];
exceeded?: ImageRegionCreateEntry[];
}
export interface ImageTag {
readonly tagId?: string;
readonly tagName?: string;
readonly created?: Date;
}
export interface ImageRegion {
readonly regionId?: string;
readonly tagName?: string;
readonly created?: Date;
/**
* Id of the tag associated with this region.
*/
tagId: string;
/**
* Coordinate of the left boundary.
*/
left: number;
/**
* Coordinate of the top boundary.
*/
top: number;
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
/**
* Image model to be sent as JSON.
*/
export interface Image {
/**
* Id of the image.
*/
readonly id?: string;
/**
* Date the image was created.
*/
readonly created?: Date;
/**
* Width of the image.
*/
readonly width?: number;
/**
* Height of the image.
*/
readonly height?: number;
/**
* The URI to the (resized) image used for training.
*/
readonly resizedImageUri?: string;
/**
* The URI to the thumbnail of the original image.
*/
readonly thumbnailUri?: string;
/**
* The URI to the original uploaded image.
*/
readonly originalImageUri?: string;
/**
* Tags associated with this image.
*/
readonly tags?: ImageTag[];
/**
* Regions associated with this image.
*/
readonly regions?: ImageRegion[];
}
export interface ImageCreateResult {
/**
* Source URL of the image.
*/
readonly sourceUrl?: string;
/**
* Status of the image creation. Possible values include: 'OK', 'OKDuplicate', 'ErrorSource',
* 'ErrorImageFormat', 'ErrorImageSize', 'ErrorStorage', 'ErrorLimitExceed',
* 'ErrorTagLimitExceed', 'ErrorRegionLimitExceed', 'ErrorUnknown',
* 'ErrorNegativeAndRegularTagOnSameImage'
*/
readonly status?: string;
/**
* The image.
*/
readonly image?: Image;
}
export interface ImageCreateSummary {
/**
* True if all of the images in the batch were created successfully, otherwise false.
*/
readonly isBatchSuccessful?: boolean;
/**
* List of the image creation results.
*/
readonly images?: ImageCreateResult[];
}
export interface Region {
/**
* Id of the tag associated with this region.
*/
tagId: string;
/**
* Coordinate of the left boundary.
*/
left: number;
/**
* Coordinate of the top boundary.
*/
top: number;
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
export interface ImageFileCreateEntry {
name?: string;
contents?: Buffer;
tagIds?: string[];
regions?: Region[];
}
export interface ImageFileCreateBatch {
images?: ImageFileCreateEntry[];
tagIds?: string[];
}
export interface ImageUrlCreateEntry {
/**
* Url of the image.
*/
url: string;
tagIds?: string[];
regions?: Region[];
}
export interface ImageUrlCreateBatch {
images?: ImageUrlCreateEntry[];
tagIds?: string[];
}
export interface ImageIdCreateEntry {
/**
* Id of the image.
*/
id?: string;
tagIds?: string[];
regions?: Region[];
}
export interface ImageIdCreateBatch {
images?: ImageIdCreateEntry[];
tagIds?: string[];
}
/**
* Bounding box that defines a region of an image.
*/
export interface BoundingBox {
/**
* Coordinate of the left boundary.
*/
left: number;
/**
* Coordinate of the top boundary.
*/
top: number;
/**
* Width.
*/
width: number;
/**
* Height.
*/
height: number;
}
export interface RegionProposal {
readonly confidence?: number;
readonly boundingBox?: BoundingBox;
}
export interface ImageRegionProposal {
readonly projectId?: string;
readonly imageId?: string;
readonly proposals?: RegionProposal[];
}
/**
* Image url.
*/
export interface ImageUrl {
/**
* Url of the image.
*/
url: string;
}
/**
* Prediction result.
*/
export interface Prediction {
/**
* Probability of the tag.
*/
readonly probability?: number;
/**
* Id of the predicted tag.
*/
readonly tagId?: string;
/**
* Name of the predicted tag.
*/
readonly tagName?: string;
/**
* Bounding box of the prediction.
*/
readonly boundingBox?: BoundingBox;
}
/**
* Result of an image prediction request.
*/
export interface ImagePrediction {
/**
* Prediction Id.
*/
readonly id?: string;
/**
* Project Id.
*/
readonly project?: string;
/**
* Iteration Id.
*/
readonly iteration?: string;
/**
* Date this prediction was created.
*/
readonly created?: Date;
/**
* List of predictions.
*/
readonly predictions?: Prediction[];
}
export interface PredictionQueryTag {
readonly id?: string;
readonly minThreshold?: number;
readonly maxThreshold?: number;
}
export interface PredictionQueryToken {
session?: string;
continuation?: string;
maxCount?: number;
/**
* Possible values include: 'Newest', 'Oldest', 'Suggested'
*/
orderBy?: string;
tags?: PredictionQueryTag[];
iterationId?: string;
startTime?: Date;
endTime?: Date;
application?: string;
}
/**
* result of an image classification request.
*/
export interface StoredImagePrediction {
/**
* The URI to the (resized) prediction image.
*/
readonly resizedImageUri?: string;
/**
* The URI to the thumbnail of the original prediction image.
*/
readonly thumbnailUri?: string;
/**
* The URI to the original prediction image.
*/
readonly originalImageUri?: string;
/**
* Domain used for the prediction.
*/
readonly domain?: string;
/**
* Prediction Id.
*/
readonly id?: string;
/**
* Project Id.
*/
readonly project?: string;
/**
* Iteration Id.
*/
readonly iteration?: string;
/**
* Date this prediction was created.
*/
readonly created?: Date;
/**
* List of predictions.
*/
readonly predictions?: Prediction[];
}
export interface PredictionQueryResult {
readonly token?: PredictionQueryToken;
readonly results?: StoredImagePrediction[];
}
/**
* Represents performance data for a particular tag in a trained iteration.
*/
export interface TagPerformance {
readonly id?: string;
readonly name?: string;
/**
* Gets the precision.
*/
readonly precision?: number;
/**
* Gets the standard deviation for the precision.
*/
readonly precisionStdDeviation?: number;
/**
* Gets the recall.
*/
readonly recall?: number;
/**
* Gets the standard deviation for the recall.
*/
readonly recallStdDeviation?: number;
/**
* Gets the average precision when applicable.
*/
readonly averagePrecision?: number;
}
/**
* Represents the detailed performance data for a trained iteration.
*/
export interface IterationPerformance {
/**
* Gets the per-tag performance details for this iteration.
*/
readonly perTagPerformance?: TagPerformance[];
/**
* Gets the precision.
*/
readonly precision?: number;
/**
* Gets the standard deviation for the precision.
*/
readonly precisionStdDeviation?: number;
/**
* Gets the recall.
*/
readonly recall?: number;
/**
* Gets the standard deviation for the recall.
*/
readonly recallStdDeviation?: number;
/**
* Gets the average precision when applicable.
*/
readonly averagePrecision?: number;
}
/**
* Image performance model.
*/
export interface ImagePerformance {
readonly predictions?: Prediction[];
readonly id?: string;
readonly created?: Date;
readonly width?: number;
readonly height?: number;
readonly imageUri?: string;
readonly thumbnailUri?: string;
readonly tags?: ImageTag[];
readonly regions?: ImageRegion[];
}
/**
* Represents settings associated with a project.
*/
export interface ProjectSettings {
/**
* Gets or sets the id of the Domain to use with this project.
*/
domainId?: string;
/**
* Gets or sets the classification type of the project. Possible values include: 'Multiclass',
* 'Multilabel'
*/
classificationType?: string;
/**
* A list of ExportPlatform that the trained model should be able to support.
*/
targetExportPlatforms?: string[];
}
/**
* Represents a project.
*/
export interface Project {
/**
* Gets the project id.
*/
readonly id?: string;
/**
* Gets or sets the name of the project.
*/
name: string;
/**
* Gets or sets the description of the project.
*/
description: string;
/**
* Gets or sets the project settings.
*/
settings: ProjectSettings;
/**
* Gets the date this project was created.
*/
readonly created?: Date;
/**
* Gets the date this project was last modified.
*/
readonly lastModified?: Date;
/**
* Gets the thumbnail url representing the image.
*/
readonly thumbnailUri?: string;
/**
* Gets if the DR mode is on.
*/
readonly drModeEnabled?: boolean;
}
/**
* Iteration model to be sent over JSON.
*/
export interface Iteration {
/**
* Gets the id of the iteration.
*/
readonly id?: string;
/**
* Gets or sets the name of the iteration.
*/
name: string;
/**
* Gets the current iteration status.
*/
readonly status?: string;
/**
* Gets the time this iteration was completed.
*/
readonly created?: Date;
/**
* Gets the time this iteration was last modified.
*/
readonly lastModified?: Date;
/**
* Gets the time this iteration was last modified.
*/
readonly trainedAt?: Date;
/**
* Gets the project id of the iteration.
*/
readonly projectId?: string;
/**
* Whether the iteration can be exported to another format for download.
*/
readonly exportable?: boolean;
/**
* A set of platforms this iteration can export to.
*/
readonly exportableTo?: string[];
/**
* Get or sets a guid of the domain the iteration has been trained on.
*/
readonly domainId?: string;
/**
* Gets the classification type of the project. Possible values include: 'Multiclass',
* 'Multilabel'
*/
readonly classificationType?: string;
/**
* Gets the training type of the iteration. Possible values include: 'Regular', 'Advanced'
*/
readonly trainingType?: string;
/**
* Gets the reserved advanced training budget for the iteration.
*/
readonly reservedBudgetInHours?: number;
/**
* Name of the published model.
*/
readonly publishName?: string;
/**
* Resource Provider Id this iteration was originally published to.
*/
readonly originalPublishResourceId?: string;
}
export interface ExportModel {
/**
* Platform of the export. Possible values include: 'CoreML', 'TensorFlow', 'DockerFile', 'ONNX',
* 'VAIDK'
*/
readonly platform?: string;
/**
* Status of the export. Possible values include: 'Exporting', 'Failed', 'Done'
*/
readonly status?: string;
/**
* URI used to download the model.
*/
readonly downloadUri?: string;
/**
* Flavor of the export. Possible values include: 'Linux', 'Windows', 'ONNX10', 'ONNX12', 'ARM'
*/
readonly flavor?: string;
/**
* Indicates an updated version of the export package is available and should be re-exported for
* the latest changes.
*/
readonly newerVersionAvailable?: boolean;
}
/**
* Represents a Tag.
*/
export interface Tag {
/**
* Gets the Tag ID.
*/
readonly id?: string;
/**
* Gets or sets the name of the tag.
*/
name: string;
/**
* Gets or sets the description of the tag.
*/
description: string;
/**
* Gets or sets the type of the tag. Possible values include: 'Regular', 'Negative'
*/
type: string;
/**
* Gets the number of images with this tag.
*/
readonly imageCount?: number;
}
export interface CustomVisionError {
/**
* The error code. Possible values include: 'NoError', 'BadRequest',
* 'BadRequestExceededBatchSize', 'BadRequestNotSupported', 'BadRequestInvalidIds',
* 'BadRequestProjectName', 'BadRequestProjectNameNotUnique', 'BadRequestProjectDescription',
* 'BadRequestProjectUnknownDomain', 'BadRequestProjectUnknownClassification',
* 'BadRequestProjectUnsupportedDomainTypeChange', 'BadRequestProjectUnsupportedExportPlatform',
* 'BadRequestIterationName', 'BadRequestIterationNameNotUnique',
* 'BadRequestIterationDescription', 'BadRequestIterationIsNotTrained',
* 'BadRequestWorkspaceCannotBeModified', 'BadRequestWorkspaceNotDeletable', 'BadRequestTagName',
* 'BadRequestTagNameNotUnique', 'BadRequestTagDescription', 'BadRequestTagType',
* 'BadRequestMultipleNegativeTag', 'BadRequestImageTags', 'BadRequestImageRegions',
* 'BadRequestNegativeAndRegularTagOnSameImage', 'BadRequestRequiredParamIsNull',
* 'BadRequestIterationIsPublished', 'BadRequestInvalidPublishName',
* 'BadRequestInvalidPublishTarget', 'BadRequestUnpublishFailed',
* 'BadRequestIterationNotPublished', 'BadRequestSubscriptionApi',
* 'BadRequestExceedProjectLimit', 'BadRequestExceedIterationPerProjectLimit',
* 'BadRequestExceedTagPerProjectLimit', 'BadRequestExceedTagPerImageLimit',
* 'BadRequestExceededQuota', 'BadRequestCannotMigrateProjectWithName',
* 'BadRequestNotLimitedTrial', 'BadRequestImageBatch', 'BadRequestImageStream',
* 'BadRequestImageUrl', 'BadRequestImageFormat', 'BadRequestImageSizeBytes',
* 'BadRequestImageExceededCount', 'BadRequestTrainingNotNeeded',
* 'BadRequestTrainingNotNeededButTrainingPipelineUpdated', 'BadRequestTrainingValidationFailed',
* 'BadRequestClassificationTrainingValidationFailed',
* 'BadRequestMultiClassClassificationTrainingValidationFailed',
* 'BadRequestMultiLabelClassificationTrainingValidationFailed',
* 'BadRequestDetectionTrainingValidationFailed', 'BadRequestTrainingAlreadyInProgress',
* 'BadRequestDetectionTrainingNotAllowNegativeTag', 'BadRequestInvalidEmailAddress',
* 'BadRequestDomainNotSupportedForAdvancedTraining',
* 'BadRequestExportPlatformNotSupportedForAdvancedTraining',
* 'BadRequestReservedBudgetInHoursNotEnoughForAdvancedTraining',
* 'BadRequestExportValidationFailed', 'BadRequestExportAlreadyInProgress',
* 'BadRequestPredictionIdsMissing', 'BadRequestPredictionIdsExceededCount',
* 'BadRequestPredictionTagsExceededCount', 'BadRequestPredictionResultsExceededCount',
* 'BadRequestPredictionInvalidApplicationName', 'BadRequestPredictionInvalidQueryParameters',
* 'BadRequestInvalid', 'UnsupportedMediaType', 'Forbidden', 'ForbiddenUser',
* 'ForbiddenUserResource', 'ForbiddenUserSignupDisabled',
* 'ForbiddenUserSignupAllowanceExceeded', 'ForbiddenUserDoesNotExist', 'ForbiddenUserDisabled',
* 'ForbiddenUserInsufficientCapability', 'ForbiddenDRModeEnabled', 'ForbiddenInvalid',
* 'NotFound', 'NotFoundProject', 'NotFoundProjectDefaultIteration', 'NotFoundIteration',
* 'NotFoundIterationPerformance', 'NotFoundTag', 'NotFoundImage', 'NotFoundDomain',
* 'NotFoundApimSubscription', 'NotFoundInvalid', 'Conflict', 'ConflictInvalid', 'ErrorUnknown',
* 'ErrorProjectInvalidWorkspace', 'ErrorProjectInvalidPipelineConfiguration',
* 'ErrorProjectInvalidDomain', 'ErrorProjectTrainingRequestFailed',
* 'ErrorProjectExportRequestFailed', 'ErrorFeaturizationServiceUnavailable',
* 'ErrorFeaturizationQueueTimeout', 'ErrorFeaturizationInvalidFeaturizer',
* 'ErrorFeaturizationAugmentationUnavailable', 'ErrorFeaturizationUnrecognizedJob',
* 'ErrorFeaturizationAugmentationError', 'ErrorExporterInvalidPlatform',
* 'ErrorExporterInvalidFeaturizer', 'ErrorExporterInvalidClassifier',
* 'ErrorPredictionServiceUnavailable', 'ErrorPredictionModelNotFound',
* 'ErrorPredictionModelNotCached', 'ErrorPrediction', 'ErrorPredictionStorage',
* 'ErrorRegionProposal', 'ErrorInvalid'
*/
code: string;
/**
* A message explaining the error reported by the service.
*/
message: string;
} | the_stack |
import * as H from 'history'
import { uniq } from 'lodash'
import * as React from 'react'
import { combineLatest, merge, Observable, of, Subject, Subscription } from 'rxjs'
import {
catchError,
debounceTime,
delay,
distinctUntilChanged,
filter,
map,
skip,
startWith,
switchMap,
takeUntil,
tap,
scan,
share,
} from 'rxjs/operators'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/shared/src/util/errors'
import { ConnectionNodes, ConnectionNodesState, ConnectionNodesDisplayProps, ConnectionProps } from './ConnectionNodes'
import { Connection, ConnectionQueryArguments } from './ConnectionType'
import { QUERY_KEY } from './constants'
import { FilteredConnectionFilter, FilteredConnectionFilterValue } from './FilterControl'
import { ConnectionError, ConnectionLoading, ConnectionForm, ConnectionContainer } from './ui'
import type { ConnectionFormProps } from './ui/ConnectionForm'
import { getFilterFromURL, getUrlQuery, parseQueryInt, hasID } from './utils'
/**
* Fields that belong in FilteredConnectionProps and that don't depend on the type parameters. These are the fields
* that are most likely to be needed by callers, and it's simpler for them if they are in a parameter-less type.
*/
interface FilteredConnectionDisplayProps extends ConnectionNodesDisplayProps, ConnectionFormProps {
history: H.History
location: H.Location
/** CSS class name for the root element. */
className?: string
/** CSS class name for the loader element. */
loaderClassName?: string
/** Whether to display it more compactly. */
compact?: boolean
/** Whether to display centered summary. */
withCenteredSummary?: boolean
/**
* An observable that upon emission causes the connection to refresh the data (by calling queryConnection).
*
* In most cases, it's simpler to use updateOnChange.
*/
updates?: Observable<void>
/**
* Refresh the data when this value changes. It is typically constructed as a key from the query args.
*/
updateOnChange?: string
/** The number of items to fetch, by default. */
defaultFirst?: number
/** Hides filters and search when the list of nodes is empty */
hideControlsWhenEmpty?: boolean
/** Whether we will use the URL query string to reflect the filter and pagination state or not. */
useURLQuery?: boolean
/**
* A subject that will force update the filtered connection's current search query, as if typed
* by the user.
*/
querySubject?: Subject<string>
}
/**
* Props for the FilteredConnection component.
*
* @template C The GraphQL connection type, such as GQL.IRepositoryConnection.
* @template N The node type of the GraphQL connection, such as GQL.IRepository (if C is GQL.IRepositoryConnection)
* @template NP Props passed to `nodeComponent` in addition to `{ node: N }`
* @template HP Props passed to `headComponent` in addition to `{ nodes: N[]; totalCount?: number | null }`.
*/
interface FilteredConnectionProps<C extends Connection<N>, N, NP = {}, HP = {}>
extends ConnectionProps<N, NP, HP>,
FilteredConnectionDisplayProps {
/** Called to fetch the connection data to populate this component. */
queryConnection: (args: FilteredConnectionQueryArguments) => Observable<C>
/** Called when the queryConnection Observable emits. */
onUpdate?: (value: C | ErrorLike | undefined, query: string) => void
/**
* Set to true when the GraphQL response is expected to emit an `PageInfo.endCursor` value when
* there is a subsequent page of results. This will request the next page of results and append
* them onto the existing list of results instead of requesting twice as many results and
* replacing the existing results.
*/
cursorPaging?: boolean
}
/**
* The arguments for the Props.queryConnection function.
*/
export interface FilteredConnectionQueryArguments extends ConnectionQueryArguments {}
interface FilteredConnectionState<C extends Connection<N>, N> extends ConnectionNodesState {
activeValues: Map<string, FilteredConnectionFilterValue>
/** The fetched connection data or an error (if an error occurred). */
connectionOrError?: C | ErrorLike
/** The `PageInfo.endCursor` value from the previous request. */
after?: string
/**
* The number of results that were visible from previous requests. The initial request of
* a result set will load `visible` items, then will request `first` items on each subsequent
* request. This has the effect of loading the correct number of visible results when a URL
* is copied during pagination. This value is only useful with cursor-based paging.
*/
visible?: number
}
/**
* Displays a collection of items with filtering and pagination. It is called
* "connection" because it is intended for use with GraphQL, which calls it that
* (see http://graphql.org/learn/pagination/).
*
* @template N The node type of the GraphQL connection, such as `GQL.IRepository` (if `C` is `GQL.IRepositoryConnection`)
* @template NP Props passed to `nodeComponent` in addition to `{ node: N }`
* @template HP Props passed to `headComponent` in addition to `{ nodes: N[]; totalCount?: number | null }`.
* @template C The GraphQL connection type, such as `GQL.IRepositoryConnection`.
*/
export class FilteredConnection<
N,
NP = {},
HP = {},
C extends Connection<N> = Connection<N>
> extends React.PureComponent<FilteredConnectionProps<C, N, NP, HP>, FilteredConnectionState<C, N>> {
public static defaultProps: Partial<FilteredConnectionProps<any, any>> = {
defaultFirst: 20,
useURLQuery: true,
}
private queryInputChanges = new Subject<string>()
private activeValuesChanges = new Subject<Map<string, FilteredConnectionFilterValue>>()
private showMoreClicks = new Subject<void>()
private componentUpdates = new Subject<FilteredConnectionProps<C, N, NP, HP>>()
private subscriptions = new Subscription()
private filterRef: HTMLInputElement | null = null
constructor(props: FilteredConnectionProps<C, N, NP, HP>) {
super(props)
const searchParameters = new URLSearchParams(this.props.location.search)
// Note: in the initial state, do not set `after` from the URL, as this doesn't
// track the number of results on the previous page. This makes the count look
// broken when coming to a page in the middle of a set of results.
//
// For example:
// (1) come to page with first = 20
// (2) set first and after cursor in URL
// (3) reload page; will skip 20 results but will display (first 20 of X)
//
// Instead, we use `ConnectionStateCommon.visible` to load the correct number of
// visible results on the initial request.
this.state = {
loading: true,
query: (!this.props.hideSearch && this.props.useURLQuery && searchParameters.get(QUERY_KEY)) || '',
activeValues:
(this.props.useURLQuery && getFilterFromURL(searchParameters, this.props.filters)) ||
new Map<string, FilteredConnectionFilterValue>(),
first: (this.props.useURLQuery && parseQueryInt(searchParameters, 'first')) || this.props.defaultFirst!,
visible: (this.props.useURLQuery && parseQueryInt(searchParameters, 'visible')) || 0,
}
}
public componentDidMount(): void {
const activeValuesChanges = this.activeValuesChanges.pipe(startWith(this.state.activeValues))
const queryChanges = (this.props.querySubject
? merge(this.queryInputChanges, this.props.querySubject)
: this.queryInputChanges
).pipe(
distinctUntilChanged(),
tap(query => !this.props.hideSearch && this.setState({ query })),
debounceTime(200),
startWith(this.state.query)
)
/**
* Emits `{ forceRefresh: false }` when loading a subsequent page (keeping the existing result set),
* and emits `{ forceRefresh: true }` on all other refresh conditions (clearing the existing result set).
*/
const refreshRequests = new Subject<{ forceRefresh: boolean }>()
this.subscriptions.add(
activeValuesChanges
.pipe(
tap(values => {
if (this.props.filters === undefined || this.props.onValueSelect === undefined) {
return
}
for (const filter of this.props.filters) {
if (this.props.onValueSelect) {
const value = values.get(filter.id)
if (value === undefined) {
continue
}
this.props.onValueSelect(filter, value)
}
}
})
)
.subscribe()
)
this.subscriptions.add(
// Use this.activeFilterChanges not activeFilterChanges so that it doesn't trigger on the initial mount
// (it doesn't need to).
this.activeValuesChanges.subscribe(values => {
this.setState({ activeValues: new Map(values) })
})
)
this.subscriptions.add(
combineLatest([
queryChanges,
activeValuesChanges,
refreshRequests.pipe(
startWith<{ forceRefresh: boolean }>({ forceRefresh: false })
),
])
.pipe(
// Track whether the query or the active filter changed
scan<
[string, Map<string, FilteredConnectionFilterValue> | undefined, { forceRefresh: boolean }],
{
query: string
values: Map<string, FilteredConnectionFilterValue> | undefined
shouldRefresh: boolean
queryCount: number
}
>(
({ query, values, queryCount }, [currentQuery, currentValues, { forceRefresh }]) => ({
query: currentQuery,
values: currentValues,
shouldRefresh: forceRefresh || query !== currentQuery || values !== currentValues,
queryCount: queryCount + 1,
}),
{
query: this.state.query,
values: this.state.activeValues,
shouldRefresh: false,
queryCount: 0,
}
),
switchMap(({ query, values, shouldRefresh, queryCount }) => {
const result = this.props
.queryConnection({
// If this is our first query and we were supplied a value for `visible`,
// load that many results. If we weren't given such a value or this is a
// subsequent request, only ask for one page of results.
first: (queryCount === 1 && this.state.visible) || this.state.first,
after: shouldRefresh ? undefined : this.state.after,
query,
...(values ? this.buildArgs(values) : {}),
})
.pipe(
catchError(error => [asError(error)]),
map(
(connectionOrError): PartialStateUpdate => ({
connectionOrError,
connectionQuery: query,
loading: false,
})
),
share()
)
return (shouldRefresh
? merge(
result,
of({
connectionOrError: undefined,
loading: true,
}).pipe(delay(250), takeUntil(result))
)
: result
).pipe(map(stateUpdate => ({ shouldRefresh, ...stateUpdate })))
}),
scan<PartialStateUpdate & { shouldRefresh: boolean }, PartialStateUpdate & { previousPage: N[] }>(
({ previousPage }, { shouldRefresh, connectionOrError, ...rest }) => {
// Set temp variable in case we update its nodes. We cannot directly update connectionOrError.nodes as they are read-only props.
let temporaryConnection: C | ErrorLike | undefined = connectionOrError
let nodes: N[] = previousPage
let after: string | undefined
if (this.props.cursorPaging && connectionOrError && !isErrorLike(connectionOrError)) {
nodes = !shouldRefresh
? [...previousPage, ...connectionOrError.nodes]
: connectionOrError.nodes
// Deduplicate any elements that occur between pages. This can happen as results are added during pagination.
nodes = [
...new Map(
nodes.map((node, index) => [hasID(node) ? node.id : index, node])
).values(),
]
temporaryConnection = { ...connectionOrError, nodes }
const pageInfo = temporaryConnection.pageInfo
after = pageInfo?.endCursor || undefined
}
return {
connectionOrError: temporaryConnection,
previousPage: nodes,
after,
...rest,
}
},
{
previousPage: [],
after: undefined,
connectionOrError: undefined,
connectionQuery: undefined,
loading: true,
}
)
)
.subscribe(
({ connectionOrError, previousPage, ...rest }) => {
if (this.props.useURLQuery) {
const searchFragment = this.urlQuery({ visibleResultCount: previousPage.length })
if (this.props.location.search !== searchFragment) {
this.props.history.replace({
search: searchFragment,
hash: this.props.location.hash,
})
}
}
if (this.props.onUpdate) {
this.props.onUpdate(connectionOrError, this.state.query)
}
this.setState({ connectionOrError, ...rest })
},
error => console.error(error)
)
)
type PartialStateUpdate = Pick<
FilteredConnectionState<C, N>,
'connectionOrError' | 'connectionQuery' | 'loading' | 'after'
>
this.subscriptions.add(
this.showMoreClicks
.pipe(
map(() =>
// If we're doing cursor paging, we rely on the `endCursor` from the previous
// response's `PageInfo` object to make our next request. Otherwise, we'll
// fallback to our legacy 'request-more' paging technique and not supply a
// cursor to the subsequent request.
({ first: this.props.cursorPaging ? this.state.first : this.state.first * 2 })
)
)
.subscribe(({ first }) =>
this.setState({ first, loading: true }, () => refreshRequests.next({ forceRefresh: false }))
)
)
if (this.props.updates) {
this.subscriptions.add(
this.props.updates.subscribe(() => {
this.setState({ loading: true }, () => refreshRequests.next({ forceRefresh: true }))
})
)
}
this.subscriptions.add(
this.componentUpdates
.pipe(
distinctUntilChanged((a, b) => a.updateOnChange === b.updateOnChange),
filter(({ updateOnChange }) => updateOnChange !== undefined),
// Skip the very first emission as the FilteredConnection already fetches on component creation.
// Otherwise, 2 requests would be triggered immediately.
skip(1)
)
.subscribe(() => {
this.setState({ loading: true, connectionOrError: undefined }, () =>
refreshRequests.next({ forceRefresh: true })
)
})
)
// Reload collection when the query callback changes.
this.subscriptions.add(
this.componentUpdates
.pipe(
map(({ queryConnection }) => queryConnection),
distinctUntilChanged(),
skip(1), // prevent from triggering on initial mount
tap(() => this.focusFilter())
)
.subscribe(() =>
this.setState({ loading: true, connectionOrError: undefined }, () =>
refreshRequests.next({ forceRefresh: true })
)
)
)
this.componentUpdates.next(this.props)
}
private urlQuery({
first,
query,
values,
visibleResultCount,
}: {
first?: number
query?: string
values?: Map<string, FilteredConnectionFilterValue>
visibleResultCount?: number
}): string {
if (!first) {
first = this.state.first
}
if (!query) {
query = this.state.query
}
if (!values) {
values = this.state.activeValues
}
return getUrlQuery({
query,
first: {
actual: first,
// Always set through `defaultProps`
default: this.props.defaultFirst!,
},
values,
visibleResultCount,
search: this.props.location.search,
filters: this.props.filters,
})
}
public componentDidUpdate(): void {
this.componentUpdates.next(this.props)
}
public componentWillUnmount(): void {
this.subscriptions.unsubscribe()
}
public render(): JSX.Element | null {
const errors: string[] = []
if (isErrorLike(this.state.connectionOrError)) {
errors.push(...uniq(this.state.connectionOrError.message.split('\n')))
}
if (
this.state.connectionOrError &&
!isErrorLike(this.state.connectionOrError) &&
this.state.connectionOrError.error
) {
errors.push(this.state.connectionOrError.error)
}
// const shouldShowControls =
// this.state.connectionOrError &&
// !isErrorLike(this.state.connectionOrError) &&
// this.state.connectionOrError.nodes &&
// this.state.connectionOrError.nodes.length > 0 &&
// this.props.hideControlsWhenEmpty
return (
<ConnectionContainer compact={this.props.compact} className={this.props.className}>
{
/* shouldShowControls && */ (!this.props.hideSearch || this.props.filters) && (
<ConnectionForm
ref={this.setFilterRef}
hideSearch={this.props.hideSearch}
inputClassName={this.props.inputClassName}
inputPlaceholder={this.props.inputPlaceholder || `Search ${this.props.pluralNoun}...`}
inputValue={this.state.query}
onInputChange={this.onChange}
autoFocus={this.props.autoFocus}
filters={this.props.filters}
onValueSelect={this.onDidSelectValue}
values={this.state.activeValues}
compact={this.props.compact}
formClassName={this.props.formClassName}
/>
)
}
{errors.length > 0 && <ConnectionError errors={errors} compact={this.props.compact} />}
{this.state.connectionOrError && !isErrorLike(this.state.connectionOrError) && (
<ConnectionNodes
connection={this.state.connectionOrError}
loading={this.state.loading}
connectionQuery={this.state.connectionQuery}
first={this.state.first}
query={this.state.query}
noun={this.props.noun}
pluralNoun={this.props.pluralNoun}
listComponent={this.props.listComponent}
listClassName={this.props.listClassName}
summaryClassName={this.props.summaryClassName}
headComponent={this.props.headComponent}
headComponentProps={this.props.headComponentProps}
footComponent={this.props.footComponent}
showMoreClassName={this.props.showMoreClassName}
nodeComponent={this.props.nodeComponent}
nodeComponentProps={this.props.nodeComponentProps}
noShowMore={this.props.noShowMore}
noSummaryIfAllNodesVisible={this.props.noSummaryIfAllNodesVisible}
onShowMore={this.onClickShowMore}
location={this.props.location}
emptyElement={this.props.emptyElement}
totalCountSummaryComponent={this.props.totalCountSummaryComponent}
withCenteredSummary={this.props.withCenteredSummary}
/>
)}
{this.state.loading && (
<ConnectionLoading compact={this.props.compact} className={this.props.loaderClassName} />
)}
</ConnectionContainer>
)
}
private setFilterRef = (element: HTMLInputElement | null): void => {
this.filterRef = element
if (element && this.props.autoFocus) {
// TODO(sqs): The 30 msec delay is needed, or else the input is not
// reliably focused. Find out why.
setTimeout(() => element.focus(), 30)
}
}
private focusFilter = (): void => {
if (this.filterRef) {
this.filterRef.focus()
}
}
private onChange: React.ChangeEventHandler<HTMLInputElement> = event => {
this.queryInputChanges.next(event.currentTarget.value)
}
private onDidSelectValue = (filter: FilteredConnectionFilter, value: FilteredConnectionFilterValue): void => {
if (this.props.filters === undefined) {
return
}
const values = new Map(this.state.activeValues)
values.set(filter.id, value)
this.activeValuesChanges.next(values)
}
private onClickShowMore = (): void => {
this.showMoreClicks.next()
}
private buildArgs = (
values: Map<string, FilteredConnectionFilterValue>
): { [name: string]: string | number | boolean } => {
let args: { [name: string]: string | number | boolean } = {}
for (const key of values.keys()) {
const value = values.get(key)
if (value === undefined) {
continue
}
args = { ...args, ...value.args }
}
return args
}
}
/**
* Resets the `FilteredConnection` URL query string parameters to the defaults
*
* @param parameters the current URL search parameters
*/
export const resetFilteredConnectionURLQuery = (parameters: URLSearchParams): void => {
parameters.delete('visible')
parameters.delete('first')
parameters.delete('after')
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.