text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {
setUnion,
setUnionInto,
setMap,
setFilter,
iterableFind,
iterableSome,
iterableMinBy,
setGroupBy,
setFilterMap,
iterableFirst,
iterableEvery,
mapMergeInto
} from "collection-utils";
import { defined, assert, panic } from "./support/Support";
export class Namespace {
readonly forbiddenNamespaces: ReadonlySet<Namespace>;
readonly additionalForbidden: ReadonlySet<Name>;
private readonly _children = new Set<Namespace>();
private readonly _members = new Set<Name>();
constructor(
_name: string,
parent: Namespace | undefined,
forbiddenNamespaces: Iterable<Namespace>,
additionalForbidden: Iterable<Name>
) {
this.forbiddenNamespaces = new Set(forbiddenNamespaces);
this.additionalForbidden = new Set(additionalForbidden);
if (parent !== undefined) {
parent.addChild(this);
}
}
private addChild(child: Namespace): void {
this._children.add(child);
}
get children(): ReadonlySet<Namespace> {
return this._children;
}
get members(): ReadonlySet<Name> {
return this._members;
}
get forbiddenNameds(): ReadonlySet<Name> {
// FIXME: cache
return setUnion(this.additionalForbidden, ...Array.from(this.forbiddenNamespaces).map(ns => ns.members));
}
add<TName extends Name>(named: TName): TName {
this._members.add(named);
return named;
}
}
export type NameStyle = (rawName: string) => string;
// `Namer`s are invoked to figure out what names to assign non-fixed `Name`s,
// and in particular to resolve conflicts. Those arise under two circumstances,
// which can also combine:
//
// 1. A proposed name is the same as an already assigned name that's forbidden
// for the name to be assigned.
// 2. There is more than one `Name` about to be assigned a name that all have
// the same proposed name.
//
// The namer is invoked with the set of all assigned, forbidden names,
// the requested name, and the `Name`s to assign names to.
//
// `Namer` is a class so that we can compare namers and put them into immutable
// collections.
export class Namer {
private readonly _prefixes: ReadonlySet<string>;
constructor(readonly name: string, readonly nameStyle: NameStyle, prefixes: string[]) {
this._prefixes = new Set(prefixes);
}
// The namesIterable comes directly out of the context and will
// be modified if we assign
assignNames(
names: ReadonlyMap<Name, string>,
forbiddenNamesIterable: Iterable<string>,
namesToAssignIterable: Iterable<Name>
): ReadonlyMap<Name, string> {
const forbiddenNames = new Set(forbiddenNamesIterable);
const namesToAssign = Array.from(namesToAssignIterable);
assert(namesToAssign.length > 0, "Number of names can't be less than 1");
const allAssignedNames = new Map<Name, string>();
let namesToPrefix: Name[] = [];
for (const name of namesToAssign) {
const proposedNames = name.proposeUnstyledNames(names);
const namingFunction = name.namingFunction;
// Find the first proposed name that isn't proposed by
// any of the other names and that isn't already forbidden.
const maybeUniqueName = iterableFind(
proposedNames,
proposed =>
!forbiddenNames.has(namingFunction.nameStyle(proposed)) &&
namesToAssign.every(n => n === name || !n.proposeUnstyledNames(names).has(proposed))
);
if (maybeUniqueName !== undefined) {
const styledName = namingFunction.nameStyle(maybeUniqueName);
const assigned = name.nameAssignments(forbiddenNames, styledName);
if (assigned !== null) {
mapMergeInto(allAssignedNames, assigned);
setUnionInto(forbiddenNames, assigned.values());
continue;
}
}
// There's no unique name, or it couldn't be assigned, so
// we need to prefix-name this one.
namesToPrefix.push(name);
}
let prefixes = this._prefixes.values();
let suffixNumber = 1;
for (const name of namesToPrefix) {
const originalName: string = defined(iterableFirst(name.proposeUnstyledNames(names)));
for (;;) {
let nameToTry: string;
const { done, value: prefix } = prefixes.next();
if (!done) {
nameToTry = `${prefix}_${originalName}`;
} else {
nameToTry = `${originalName}_${suffixNumber.toString()}`;
suffixNumber++;
}
const styledName = name.namingFunction.nameStyle(nameToTry);
const assigned = name.nameAssignments(forbiddenNames, styledName);
if (assigned === null) continue;
mapMergeInto(allAssignedNames, assigned);
setUnionInto(forbiddenNames, assigned.values());
break;
}
}
return allAssignedNames;
}
}
const funPrefixes = [
"Purple",
"Fluffy",
"Tentacled",
"Sticky",
"Indigo",
"Indecent",
"Hilarious",
"Ambitious",
"Cunning",
"Magenta",
"Frisky",
"Mischievous",
"Braggadocious"
];
export function funPrefixNamer(name: string, nameStyle: NameStyle): Namer {
return new Namer(name, nameStyle, funPrefixes);
}
// FIXME: I think the type hierarchy is somewhat wrong here. `FixedName`
// should be a `Name`, but the non-fixed names should probably have their
// own common superclass. Most methods of `Name` make sense only either
// for `FixedName` or the non-fixed names.
export abstract class Name {
private readonly _associates = new Set<AssociatedName>();
// If a Named is fixed, the namingFunction is undefined.
constructor(private readonly _namingFunction: Namer | undefined, readonly order: number) {}
addAssociate(associate: AssociatedName): void {
this._associates.add(associate);
}
abstract get dependencies(): ReadonlyArray<Name>;
isFixed(): this is FixedName {
return this instanceof FixedName;
}
get namingFunction(): Namer {
return defined(this._namingFunction);
}
// Must return at least one proposal. The proposals are considered in order.
abstract proposeUnstyledNames(names: ReadonlyMap<Name, string>): ReadonlySet<string>;
firstProposedName(names: ReadonlyMap<Name, string>): string {
return defined(iterableFirst(this.proposeUnstyledNames(names)));
}
nameAssignments(forbiddenNames: ReadonlySet<string>, assignedName: string): ReadonlyMap<Name, string> | null {
if (forbiddenNames.has(assignedName)) return null;
const assignments = new Map<Name, string>([[this, assignedName]]);
for (const an of this._associates) {
const associatedAssignedName = an.getName(assignedName);
if (forbiddenNames.has(associatedAssignedName)) {
return null;
}
assignments.set(an, associatedAssignedName);
}
return assignments;
}
}
// FIXME: FixedNameds should optionally be user-configurable
export class FixedName extends Name {
constructor(private readonly _fixedName: string) {
super(undefined, 0);
}
get dependencies(): ReadonlyArray<Name> {
return [];
}
addAssociate(_: AssociatedName): never {
return panic("Cannot add associates to fixed names");
}
get fixedName(): string {
return this._fixedName;
}
proposeUnstyledNames(_?: ReadonlyMap<Name, string>): ReadonlySet<string> {
return panic("Only fixedName should be called on FixedName.");
}
}
export class SimpleName extends Name {
private readonly _unstyledNames: ReadonlySet<string>;
constructor(unstyledNames: Iterable<string>, namingFunction: Namer, order: number) {
super(namingFunction, order);
this._unstyledNames = new Set(unstyledNames);
}
get dependencies(): ReadonlyArray<Name> {
return [];
}
proposeUnstyledNames(_?: ReadonlyMap<Name, string>): ReadonlySet<string> {
return this._unstyledNames;
}
}
export class AssociatedName extends Name {
constructor(private readonly _sponsor: Name, order: number, readonly getName: (sponsorName: string) => string) {
super(undefined, order);
}
get dependencies(): ReadonlyArray<Name> {
return [this._sponsor];
}
proposeUnstyledNames(_?: ReadonlyMap<Name, string>): never {
return panic("AssociatedName must be assigned via its sponsor");
}
}
export class DependencyName extends Name {
private readonly _dependencies: ReadonlySet<Name>;
constructor(
namingFunction: Namer | undefined,
order: number,
private readonly _proposeUnstyledName: (lookup: (n: Name) => string) => string
) {
super(namingFunction, order);
const dependencies: Name[] = [];
_proposeUnstyledName(n => {
dependencies.push(n);
return "0xDEADBEEF";
});
this._dependencies = new Set(dependencies);
}
get dependencies(): ReadonlyArray<Name> {
return Array.from(this._dependencies);
}
proposeUnstyledNames(names: ReadonlyMap<Name, string>): ReadonlySet<string> {
return new Set([
this._proposeUnstyledName(n => {
assert(this._dependencies.has(n), "DependencyName proposer is not pure");
return defined(names.get(n));
})
]);
}
}
export function keywordNamespace(name: string, keywords: string[]) {
const ns = new Namespace(name, undefined, [], []);
for (const kw of keywords) {
ns.add(new FixedName(kw));
}
return ns;
}
function allNamespacesRecursively(namespaces: Iterable<Namespace>): ReadonlySet<Namespace> {
return setUnion(namespaces, ...Array.from(setMap(namespaces, ns => allNamespacesRecursively(ns.children))));
}
class NamingContext {
private readonly _names: Map<Name, string> = new Map();
private readonly _namedsForName: Map<string, Set<Name>> = new Map();
readonly namespaces: ReadonlySet<Namespace>;
constructor(rootNamespaces: Iterable<Namespace>) {
this.namespaces = allNamespacesRecursively(rootNamespaces);
}
get names(): ReadonlyMap<Name, string> {
return this._names;
}
isReadyToBeNamed = (named: Name): boolean => {
if (this._names.has(named)) return false;
return named.dependencies.every((n: Name) => this._names.has(n));
};
areForbiddensFullyNamed(namespace: Namespace): boolean {
return iterableEvery(namespace.forbiddenNameds, n => this._names.has(n));
}
isConflicting = (namedNamespace: Namespace, proposed: string): boolean => {
const namedsForProposed = this._namedsForName.get(proposed);
// If the name is not assigned at all, there is no conflict.
if (namedsForProposed === undefined) return false;
// The name is assigned, but it might still not be forbidden.
for (const n of namedsForProposed) {
if (namedNamespace.members.has(n) || namedNamespace.forbiddenNameds.has(n)) {
return true;
}
}
return false;
};
assign = (named: Name, namedNamespace: Namespace, name: string): void => {
assert(!this.names.has(named), `Name "${name}" assigned twice`);
assert(!this.isConflicting(namedNamespace, name), `Assigned name "${name}" conflicts`);
this._names.set(named, name);
let namedsForName = this._namedsForName.get(name);
if (namedsForName === undefined) {
namedsForName = new Set();
this._namedsForName.set(name, namedsForName);
}
namedsForName.add(named);
};
}
// Naming algorithm
export function assignNames(rootNamespaces: Iterable<Namespace>): ReadonlyMap<Name, string> {
const ctx = new NamingContext(rootNamespaces);
// Assign all fixed names.
for (const ns of ctx.namespaces) {
for (const n of ns.members) {
if (!n.isFixed()) continue;
ctx.assign(n, ns, n.fixedName);
}
}
for (;;) {
// 1. Find a namespace whose forbiddens are all fully named, and which has
// at least one unnamed Named that has all its dependencies satisfied.
// If no such namespace exists we're either done, or there's an unallowed
// cycle.
const unfinishedNamespaces = setFilter(ctx.namespaces, ns => ctx.areForbiddensFullyNamed(ns));
const readyNamespace = iterableFind(unfinishedNamespaces, ns => iterableSome(ns.members, ctx.isReadyToBeNamed));
if (readyNamespace === undefined) {
// FIXME: Check for cycles?
return ctx.names;
}
const allForbiddenNames = setUnion(readyNamespace.members, readyNamespace.forbiddenNameds);
let forbiddenNames = setFilterMap(allForbiddenNames, n => ctx.names.get(n));
// 2. From low order to high order, sort those names into sets where all
// members of a set propose the same name and have the same naming
// function.
for (;;) {
const allReadyNames = setFilter(readyNamespace.members, ctx.isReadyToBeNamed);
const minOrderName = iterableMinBy(allReadyNames, n => n.order);
if (minOrderName === undefined) break;
const minOrder = minOrderName.order;
const readyNames = setFilter(allReadyNames, n => n.order === minOrder);
// It would be nice if we had tuples, then we wouldn't have to do this in
// two steps.
const byNamingFunction = setGroupBy(readyNames, n => n.namingFunction);
for (const [namer, namedsForNamingFunction] of byNamingFunction) {
const byProposed = setGroupBy(namedsForNamingFunction, n =>
n.namingFunction.nameStyle(n.firstProposedName(ctx.names))
);
for (const [, nameds] of byProposed) {
// 3. Use each set's naming function to name its members.
const names = namer.assignNames(ctx.names, forbiddenNames, nameds);
for (const [name, assigned] of names) {
ctx.assign(name, readyNamespace, assigned);
}
setUnionInto(forbiddenNames, names.values());
}
}
}
}
} | the_stack |
import { ErrorObject } from "ajv";
import React, { PureComponent } from "react";
import { withHandlers, compose } from "recompose";
import { BaseFactory, schemaFieldFactory } from "fx-schema-form-core";
import { Action } from "redux-act";
import { UtilsHocOutProps } from "./utils";
import { DefaultProps } from "../components";
import { RC, schemaFormTypes } from "../models";
import { fromJS } from "immutable";
import { errorFactory } from "../factory";
import { ASN } from "../reducers/schema.form";
export interface ValidateHocOutProps {
updateItemData: (props: DefaultProps, data: any, meta?: any) => void;
updateItemMeta: (props: DefaultProps, data: any, meta?: any, noChange?: boolean) => Promise<void>;
removeItemData: (props: DefaultProps, meta?: any) => void;
removeMetaKeys: (props: DefaultProps, removeMetaKeys?: ASN[]) => void;
updateItemDataRaw: (props: DefaultProps, data: any, meta?: any) => void;
updateItemMetaRaw: (props: DefaultProps, data: any, meta?: any, noChange?: boolean) => Promise<void>;
removeItemDataRaw: (props: DefaultProps, meta?: any) => void;
removeMetaKeysRaw: (props: DefaultProps, removeMetaKeys?: ASN[]) => void;
combineActions: (...actions: Action<any>[]) => void;
validate: (props: DefaultProps, data: any, meta?: any) => Promise<any>;
}
export interface ValidateHocSetting {
root?: boolean;
errorsText?: (errors: ErrorObject[], props: DefaultProps) => string;
}
export const name = "validate";
/**
* 包装validate的组件HOC
* @param hocFactory hoc的工厂方法
* @param Component 需要包装的组件
* 加入属性
*/
export const hoc = (hocFactory: BaseFactory<any>) => {
return (settings: ValidateHocSetting = {}) => {
return (Component: any): RC<DefaultProps, any> => {
@(compose(
hocFactory.get("data")({
root: settings.root
}),
withHandlers<any, any>({
/**
* 验证单个数据
* 使用当前组件中的uiSchema,以及传递过来的数据做验证
* 这里可能有远程验证
*/
validate: (propsCur: DefaultProps & UtilsHocOutProps) => {
return async (props: DefaultProps & UtilsHocOutProps, data: any, meta: any = {}) => {
const result: any = { dirty: true, isValid: false, isLoading: false };
const { uiSchema, parentKeys, ajv, getTitle, getOptions } = props;
const schema = Object.assign({}, uiSchema);
const options = getOptions(props, schemaFormTypes.hoc, name, fromJS(settings));
const timeId = setTimeout(() => {
propsCur.getActions(propsCur).updateItemMeta({
parentKeys: parentKeys,
keys: (schema as any).keys,
meta: { isLoading: true, isValid: false, errorText: false }
});
}, 200);
// 这里做一层try catch处理
try {
let validateFunc;
// 使用schema.schemaPath来确定schema
if (schema.schemaPath && ajv.getSchema(schema.schemaPath)) {
validateFunc = ajv.getSchema(schema.schemaPath);
} else if (schema.$id) {
validateFunc = ajv.getSchema(schema.$id);
} else {
let schemaInCache = Object.assign({}, schemaFieldFactory.get(schema.schemaPath || ""));
delete schemaInCache.$id;
delete schemaInCache.$ref;
validateFunc = ajv.compile(schemaInCache);
}
if (propsCur.formItemData) {
result.isValid = await validateFunc(data, undefined, undefined,
undefined, propsCur.formItemData.toJS());
} else {
result.isValid = await validateFunc(data);
}
// 如果验证出错,则抛出错误
if (!result.isValid) {
let error: any = new Error();
error.errors = validateFunc.errors;
throw error;
}
} catch (err) {
// 处理错误消息
if (options.errorsText) {
result.errorText = options.errorsText(err.errors, props);
} else {
result.errorText = errorFactory.get("validate")(err.errors, props, []);
// err.errors ?
// ajv.errorsText(err.errors, {
// dataVar: getTitle(props).toString()
// }) : err.message;
}
}
finally {
clearTimeout(timeId);
}
return Object.assign({}, meta, result);
};
}
}),
hocFactory.get("resetKey")({
excludeKeys: ["formItemData"]
}),
withHandlers<any, any>({
/**
* 更新一个数据
*/
updateItemData: (propsCur: DefaultProps & UtilsHocOutProps) => {
return (raw: boolean, { parentKeys, uiSchema }: DefaultProps, data: any, meta?: any) => {
const { keys = [] } = uiSchema || {};
return propsCur.getActions(propsCur, raw).updateItemData({
parentKeys,
keys,
data,
meta
});
};
},
/**
* 更新一个元数据
*/
updateItemMeta: (propsCur: DefaultProps & UtilsHocOutProps & ValidateHocOutProps) => {
return async (raw: boolean, props: DefaultProps, data: any, meta: any = null, noChange = false) => {
const { parentKeys, uiSchema } = props;
const { keys = [] } = uiSchema || {};
return propsCur.getActions(propsCur, raw).updateItemMeta({
parentKeys,
keys,
meta: meta || await propsCur.validate(props, data),
noChange
});
};
},
/**
* 删除一个元素的meta和data
*/
removeItemData: (propsCur: DefaultProps & UtilsHocOutProps) => {
return (raw: boolean, { parentKeys, uiSchema }: DefaultProps, meta = true) => {
const { keys = [] } = uiSchema || {};
return propsCur.getActions(propsCur, raw).removeItemData({
parentKeys,
keys,
meta
});
};
},
/**
* 删除一个元素meta中的部分键值
*/
removeMetaKeys: (propsCur: DefaultProps & UtilsHocOutProps) => {
return (raw: boolean, { parentKeys, uiSchema }: DefaultProps, removeMetaKeys: ASN[]) => {
const { keys = [] } = uiSchema || {};
return propsCur.getActions(propsCur, raw).removeMetaKeys({
parentKeys,
keys,
removeMetaKeys
});
};
},
/**
* 合并多个action
*/
combineActions: (propsCur: DefaultProps & UtilsHocOutProps) => {
return (...actions: Action<any>[]) => {
return propsCur.getActions(propsCur).combineActions(actions);
};
},
}),
withHandlers<any, any>({
updateItemData: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.updateItemData.bind(null, false);
},
updateItemMeta: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.updateItemMeta.bind(null, false);
},
removeItemData: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.removeItemData.bind(null, false);
},
updateItemDataRaw: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.updateItemData.bind(null, true);
},
updateItemMetaRaw: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.updateItemMeta.bind(null, true);
},
removeItemDataRaw: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.removeItemData.bind(null, true);
},
removeMetaKeysRaw: (propsCur: DefaultProps & ValidateHocOutProps) => {
return propsCur.removeMetaKeys.bind(null, true);
}
})) as any)
class ArrayComponentHoc extends PureComponent<DefaultProps, any> {
public render(): JSX.Element {
return <Component {...this.props} />;
}
}
return ArrayComponentHoc as any;
};
};
};
export default {
name,
hoc
}; | the_stack |
import { CommonErrors, MongoshInvalidInputError, MongoshRuntimeError } from '@mongosh/errors';
import { bson, Document, FindCursor as ServiceProviderCursor, ServiceProvider } from '@mongosh/service-provider-core';
import chai, { expect } from 'chai';
import { EventEmitter } from 'events';
import semver from 'semver';
import sinonChai from 'sinon-chai';
import sinon, { StubbedInstance, stubInterface } from 'ts-sinon';
import { ensureMaster } from '../../../testing/helpers';
import { MongodSetup, skipIfServerVersion, startTestCluster, skipIfApiStrict } from '../../../testing/integration-testing-hooks';
import { CliServiceProvider } from '../../service-provider-server';
import Database from './database';
import {
ADMIN_DB,
ALL_PLATFORMS,
ALL_SERVER_VERSIONS,
ALL_API_VERSIONS,
ALL_TOPOLOGIES
} from './enums';
import { signatures, toShellResult } from './index';
import Mongo from './mongo';
import ReplicaSet, { ReplSetConfig, ReplSetMemberConfig } from './replica-set';
import ShellInstanceState, { EvaluationListener } from './shell-instance-state';
chai.use(sinonChai);
function deepClone<T>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
describe('ReplicaSet', () => {
skipIfApiStrict();
describe('help', () => {
const apiClass: any = new ReplicaSet({} as any);
it('calls help function', async() => {
expect((await toShellResult(apiClass.help())).type).to.equal('Help');
expect((await toShellResult(apiClass.help)).type).to.equal('Help');
});
it('calls help function for methods', async() => {
expect((await toShellResult(apiClass.initiate.help())).type).to.equal('Help');
expect((await toShellResult(apiClass.initiate.help)).type).to.equal('Help');
});
});
describe('signatures', () => {
it('type', () => {
expect(signatures.ReplicaSet.type).to.equal('ReplicaSet');
});
it('attributes', () => {
expect(signatures.ReplicaSet.attributes.initiate).to.deep.equal({
type: 'function',
returnsPromise: true,
deprecated: false,
returnType: { type: 'unknown', attributes: {} },
platforms: ALL_PLATFORMS,
topologies: ALL_TOPOLOGIES,
apiVersions: ALL_API_VERSIONS,
serverVersions: ALL_SERVER_VERSIONS,
isDirectShellCommand: false,
acceptsRawInput: false,
shellCommandCompleter: undefined
});
});
});
describe('unit', () => {
let mongo: Mongo;
let serviceProvider: StubbedInstance<ServiceProvider>;
let evaluationListener: StubbedInstance<EvaluationListener>;
let rs: ReplicaSet;
let bus: StubbedInstance<EventEmitter>;
let instanceState: ShellInstanceState;
let db: Database;
beforeEach(() => {
bus = stubInterface<EventEmitter>();
serviceProvider = stubInterface<ServiceProvider>();
serviceProvider.initialDb = 'test';
serviceProvider.bsonLibrary = bson;
serviceProvider.runCommand.resolves({ ok: 1 });
serviceProvider.runCommandWithCheck.resolves({ ok: 1 });
evaluationListener = stubInterface<EvaluationListener>();
instanceState = new ShellInstanceState(serviceProvider, bus);
instanceState.setEvaluationListener(evaluationListener);
mongo = new Mongo(instanceState, undefined, undefined, undefined, serviceProvider);
db = new Database(mongo, 'testdb');
rs = new ReplicaSet(db);
});
describe('initiate', () => {
const configDoc = {
_id: 'my_replica_set',
members: [
{ _id: 0, host: 'rs1.example.net:27017' },
{ _id: 1, host: 'rs2.example.net:27017' },
{ _id: 2, host: 'rs3.example.net', arbiterOnly: true },
]
};
it('calls serviceProvider.runCommandWithCheck without optional arg', async() => {
await rs.initiate();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetInitiate: {}
}
);
});
it('calls serviceProvider.runCommandWithCheck with arg', async() => {
await rs.initiate(configDoc);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetInitiate: configDoc
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.initiate(configDoc);
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.initiate(configDoc)
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('config', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
const expectedResult = { config: { version: 1, members: [], settings: {} } };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
await rs.config();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetGetConfig: 1
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
// not using the full object for expected result, as we should check this in an e2e test.
const expectedResult = { config: { version: 1, members: [], settings: {} } };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.config();
expect(result).to.deep.equal(expectedResult.config);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedResult = { config: { version: 1, members: [], settings: {} } };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.config()
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
it('calls find if serviceProvider.runCommandWithCheck rejects with command not found', async() => {
const expectedError = new Error() as any;
expectedError.codeName = 'CommandNotFound';
serviceProvider.runCommandWithCheck.rejects(expectedError);
const expectedResult = { res: true };
const findCursor = stubInterface<ServiceProviderCursor>();
findCursor.tryNext.resolves(expectedResult);
serviceProvider.find.returns(findCursor);
const conf = await rs.config();
expect(serviceProvider.find).to.have.been.calledWith(
'local', 'system.replset', {}, {}
);
expect(conf).to.deep.equal(expectedResult);
});
});
describe('reconfig', () => {
const configDoc: Partial<ReplSetConfig> = {
_id: 'my_replica_set',
members: [
{ _id: 0, host: 'rs1.example.net:27017' },
{ _id: 1, host: 'rs2.example.net:27017' },
{ _id: 2, host: 'rs3.example.net', arbiterOnly: true },
]
};
it('calls serviceProvider.runCommandWithCheck without optional arg', async() => {
serviceProvider.runCommandWithCheck.resolves({ config: { version: 1, protocolVersion: 1 } });
await rs.reconfig(configDoc);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
_id: 'my_replica_set',
members: [
{ _id: 0, host: 'rs1.example.net:27017' },
{ _id: 1, host: 'rs2.example.net:27017' },
{ _id: 2, host: 'rs3.example.net', arbiterOnly: true },
],
version: 2,
protocolVersion: 1
}
}
);
});
it('calls serviceProvider.runCommandWithCheck with arg', async() => {
serviceProvider.runCommandWithCheck.resolves({ config: 1, protocolVersion: 1 });
await rs.reconfig(configDoc, { force: true });
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
_id: 'my_replica_set',
members: [
{ _id: 0, host: 'rs1.example.net:27017' },
{ _id: 1, host: 'rs2.example.net:27017' },
{ _id: 2, host: 'rs3.example.net', arbiterOnly: true },
],
version: 1,
protocolVersion: 1
},
force: true
}
);
});
describe('retry on errors', () => {
let oldConfig: Partial<ReplSetConfig>;
let reconfigCalls: ReplSetConfig[];
let reconfigResults: Document[];
let sleepStub: any;
beforeEach(() => {
sleepStub = sinon.stub();
instanceState.shellApi.sleep = sleepStub;
reconfigCalls = [];
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db: string, cmd: Document) => {
if (cmd.replSetGetConfig) {
return { config: { ...oldConfig, version: oldConfig.version ?? 1 } };
}
if (cmd.replSetReconfig) {
const result = reconfigResults.shift();
reconfigCalls.push(deepClone(cmd.replSetReconfig));
if (result.ok) {
return result;
}
oldConfig = { ...oldConfig, version: (oldConfig.version ?? 1) + 1 };
throw new Error(`Reconfig failed: ${JSON.stringify(result)}`);
}
});
});
it('does three reconfigs if the first two fail due to known issue', async() => {
oldConfig = deepClone(configDoc);
reconfigResults = [ { ok: 0 }, { ok: 0 }, { ok: 1 } ];
const origConfig = deepClone(configDoc);
await rs.reconfig(configDoc);
expect(reconfigCalls).to.deep.equal([
{ ...origConfig, version: 2 },
{ ...origConfig, version: 3 },
{ ...origConfig, version: 4 }
]);
expect(sleepStub).to.have.been.calledWith(1000);
expect(sleepStub).to.have.been.calledWith(1300);
});
it('gives up after a number of attempts', async() => {
oldConfig = deepClone(configDoc);
reconfigResults = [...Array(20).keys()].map(() => ({ ok: 0 }));
try {
await rs.reconfig(configDoc);
expect.fail('missed exception');
} catch (err) {
expect(err.message).to.equal('Reconfig failed: {"ok":0}');
}
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Reconfig did not succeed yet, starting new attempt...')
]);
const totalSleepLength = sleepStub.getCalls()
.map(({ firstArg }) => firstArg)
.reduce((x, y) => x + y, 0);
// Expect to spend about a minute sleeping here.
expect(totalSleepLength).to.be.closeTo(60_000, 5_000);
expect(reconfigCalls).to.have.lengthOf(12);
});
});
});
describe('status', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
await rs.status();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetGetStatus: 1
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.status();
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.status()
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('isMaster', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
await rs.isMaster();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
isMaster: 1
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.isMaster();
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.isMaster()
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('hello', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
await rs.hello();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
hello: 1
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.hello();
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.hello()
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('add', () => {
it('calls serviceProvider.runCommandWithCheck with no arb and string hostport', async() => {
const configDoc = { version: 1, members: [{ _id: 0 }, { _id: 1 }] };
const hostname = 'localhost:27017';
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const result = await rs.add(hostname);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
version: 2,
members: [
{ _id: 0 },
{ _id: 1 },
{ _id: 2, host: hostname }
]
}
}
);
expect(result).to.deep.equal(expectedResult);
});
it('calls serviceProvider.runCommandWithCheck with arb and string hostport', async() => {
const configDoc = { version: 1, members: [{ _id: 0 }, { _id: 1 }] };
const hostname = 'localhost:27017';
serviceProvider.countDocuments.resolves(1);
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const result = await rs.add(hostname, true);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
version: 2,
members: [
{ _id: 0 },
{ _id: 1 },
{ _id: 2, arbiterOnly: true, host: hostname }
]
}
}
);
expect(result).to.deep.equal(expectedResult);
});
it('calls serviceProvider.runCommandWithCheck with no arb and obj hostport', async() => {
const configDoc = { version: 1, members: [{ _id: 0 }, { _id: 1 }] };
const hostname = {
host: 'localhost:27017'
};
serviceProvider.countDocuments.resolves(1);
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const result = await rs.add(hostname);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
version: 2,
members: [
{ _id: 0 },
{ _id: 1 },
{ _id: 2, host: hostname.host }
]
}
}
);
expect(result).to.deep.equal(expectedResult);
});
it('calls serviceProvider.runCommandWithCheck with no arb and obj hostport, uses _id', async() => {
const configDoc = { version: 1, members: [{ _id: 0 }, { _id: 1 }] };
const hostname = {
host: 'localhost:27017', _id: 10
};
serviceProvider.countDocuments.resolves(1);
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const result = await rs.add(hostname);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
version: 2,
members: [
{ _id: 0 },
{ _id: 1 },
hostname
]
}
}
);
expect(result).to.deep.equal(expectedResult);
});
it('throws with arb and object hostport', async() => {
const configDoc = { version: 1, members: [{ _id: 0 }, { _id: 1 }] };
const hostname = { host: 'localhost:27017' };
serviceProvider.countDocuments.resolves(1);
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const error = await rs.add(hostname, true).catch(e => e);
expect(error).to.be.instanceOf(MongoshInvalidInputError);
expect(error.code).to.equal(CommonErrors.InvalidArgument);
});
it('throws if local.system.replset.findOne has no docs', async() => {
const hostname = { host: 'localhost:27017' };
serviceProvider.runCommandWithCheck.resolves({ ok: 1 });
const error = await rs.add(hostname, true).catch(e => e);
expect(error).to.be.instanceOf(MongoshRuntimeError);
expect(error.code).to.equal(CommonErrors.CommandFailed);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.add('hostname')
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('remove', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
const configDoc = { version: 1, members: [{ _id: 0, host: 'localhost:0' }, { _id: 1, host: 'localhost:1' }] };
const hostname = 'localhost:0';
const expectedResult = { ok: 1 };
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db, command) => {
if (command.replSetGetConfig) {return { ok: 1, config: configDoc };}
return expectedResult;
});
const result = await rs.remove(hostname);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetReconfig: {
version: 2,
members: [
{ _id: 1, host: 'localhost:1' }
]
}
}
);
expect(result).to.deep.equal(expectedResult);
});
it('throws with object hostport', async() => {
const hostname = { host: 'localhost:27017' } as any;
const error = await rs.remove(hostname).catch(e => e);
expect(error.name).to.equal('MongoshInvalidInputError');
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.remove('localhost:1')
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
it('throws if hostname not in members', async() => {
const configDoc = { version: 1, members: [{ _id: 0, host: 'localhost:0' }, { _id: 1, host: 'lcoalhost:1' }] };
serviceProvider.runCommandWithCheck.resolves({ ok: 1, config: configDoc });
const caughtError = await rs.remove('localhost:2')
.catch(e => e);
expect(caughtError).to.be.instanceOf(MongoshInvalidInputError);
expect(caughtError.code).to.equal(CommonErrors.InvalidArgument);
});
});
describe('freeze', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
await rs.freeze(100);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetFreeze: 100
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.freeze(100);
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.freeze(100)
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('syncFrom', () => {
it('calls serviceProvider.runCommandWithCheck', async() => {
await rs.syncFrom('localhost:27017');
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetSyncFrom: 'localhost:27017'
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.syncFrom('localhost:27017');
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.syncFrom('localhost:27017')
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('stepDown', () => {
it('calls serviceProvider.runCommandWithCheck without any arg', async() => {
await rs.stepDown();
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetStepDown: 60
}
);
});
it('calls serviceProvider.runCommandWithCheck without second optional arg', async() => {
await rs.stepDown(10);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetStepDown: 10
}
);
});
it('calls serviceProvider.runCommandWithCheck with arg', async() => {
await rs.stepDown(10, 30);
expect(serviceProvider.runCommandWithCheck).to.have.been.calledWith(
ADMIN_DB,
{
replSetStepDown: 10,
secondaryCatchUpPeriodSecs: 30
}
);
});
it('returns whatever serviceProvider.runCommandWithCheck returns', async() => {
const expectedResult = { ok: 1 };
serviceProvider.runCommandWithCheck.resolves(expectedResult);
const result = await rs.stepDown(10);
expect(result).to.deep.equal(expectedResult);
});
it('throws if serviceProvider.runCommandWithCheck rejects', async() => {
const expectedError = new Error();
serviceProvider.runCommandWithCheck.rejects(expectedError);
const caughtError = await rs.stepDown(10)
.catch(e => e);
expect(caughtError).to.equal(expectedError);
});
});
describe('reconfigForPSASet', () => {
let secondary: ReplSetMemberConfig;
let config: Partial<ReplSetConfig>;
let oldConfig: ReplSetConfig;
let reconfigCalls: ReplSetConfig[];
let reconfigResults: Document[];
let sleepStub: any;
beforeEach(() => {
sleepStub = sinon.stub();
instanceState.shellApi.sleep = sleepStub;
secondary = {
_id: 2, host: 'secondary.mongodb.net', priority: 1, votes: 1
};
oldConfig = {
_id: 'replSet',
members: [
{ _id: 0, host: 'primary.monogdb.net', priority: 1, votes: 1 },
{ _id: 1, host: 'arbiter.monogdb.net', priority: 1, votes: 0, arbiterOnly: true }
],
protocolVersion: 1,
version: 1
};
config = deepClone(oldConfig);
config.members.push(secondary);
reconfigResults = [ { ok: 1 }, { ok: 1 } ];
reconfigCalls = [];
// eslint-disable-next-line @typescript-eslint/require-await
serviceProvider.runCommandWithCheck.callsFake(async(db: string, cmd: Document) => {
if (cmd.replSetGetConfig) {
return { config: oldConfig };
}
if (cmd.replSetReconfig) {
const result = reconfigResults.shift();
reconfigCalls.push(deepClone(cmd.replSetReconfig));
if (result.ok) {
oldConfig = deepClone(cmd.replSetReconfig);
return result;
}
throw new Error(`Reconfig failed: ${JSON.stringify(result)}`);
}
});
});
it('fails if index is incorrect', async() => {
try {
await rs.reconfigForPSASet(3, config);
expect.fail('missed exception');
} catch (err) {
expect(err.message).to.equal('[COMMON-10001] Node at index 3 does not exist in the new config');
}
});
it('fails if secondary.votes != 1', async() => {
secondary.votes = 0;
try {
await rs.reconfigForPSASet(2, config);
expect.fail('missed exception');
} catch (err) {
expect(err.message).to.equal('[COMMON-10001] Node at index 2 must have { votes: 1 } in the new config (actual: { votes: 0 })');
}
});
it('fails if old note had votes', async() => {
oldConfig.members.push(secondary);
try {
await rs.reconfigForPSASet(2, config);
expect.fail('missed exception');
} catch (err) {
expect(err.message).to.equal('[COMMON-10001] Node at index 2 must have { votes: 0 } in the old config (actual: { votes: 1 })');
}
});
it('warns if there is an existing member with the same host', async() => {
oldConfig.members.push(deepClone(secondary));
secondary._id = 3;
await rs.reconfigForPSASet(2, config);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult(
'Warning: Node at index 2 has { host: "secondary.mongodb.net" }, ' +
'which is also present in the old config, but with a different _id field.')
]);
});
it('skips the second reconfig if priority is 0', async() => {
secondary.priority = 0;
await rs.reconfigForPSASet(2, config);
expect(reconfigCalls).to.deep.equal([
{ ...config, version: 2 }
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running first reconfig to give member at index 2 { votes: 1, priority: 0 }')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('No second reconfig necessary because .priority = 0')
]);
});
it('does two reconfigs if priority is 1', async() => {
const origConfig = deepClone(config);
await rs.reconfigForPSASet(2, config);
expect(reconfigCalls).to.deep.equal([
{ ...origConfig, members: [ config.members[0], config.members[1], { ...secondary, priority: 0 } ], version: 2 },
{ ...origConfig, version: 3 }
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running first reconfig to give member at index 2 { votes: 1, priority: 0 }')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running second reconfig to give member at index 2 { priority: 1 }')
]);
});
it('does three reconfigs the second one fails', async() => {
reconfigResults = [{ ok: 1 }, { ok: 0 }, { ok: 1 }];
const origConfig = deepClone(config);
await rs.reconfigForPSASet(2, config);
expect(reconfigCalls).to.deep.equal([
{ ...origConfig, members: [ config.members[0], config.members[1], { ...secondary, priority: 0 } ], version: 2 },
{ ...origConfig, version: 3 },
{ ...origConfig, version: 3 }
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running first reconfig to give member at index 2 { votes: 1, priority: 0 }')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running second reconfig to give member at index 2 { priority: 1 }')
]);
expect(sleepStub).to.have.been.calledWith(1000);
});
it('gives up after a number of attempts', async() => {
reconfigResults = [...Array(20).keys()].map((i) => ({ ok: i === 0 ? 1 : 0 }));
try {
await rs.reconfigForPSASet(2, config);
expect.fail('missed exception');
} catch (err) {
expect(err.message).to.equal('Reconfig failed: {"ok":0}');
}
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running first reconfig to give member at index 2 { votes: 1, priority: 0 }')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Running second reconfig to give member at index 2 { priority: 1 }')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Reconfig did not succeed yet, starting new attempt...')
]);
expect(evaluationListener.onPrint).to.have.been.calledWith([
await toShellResult('Second reconfig did not succeed, giving up')
]);
const totalSleepLength = sleepStub.getCalls()
.map(({ firstArg }) => firstArg)
.reduce((x, y) => x + y, 0);
// Expect to spend about a minute sleeping here.
expect(totalSleepLength).to.be.closeTo(60_000, 5_000);
expect(reconfigCalls).to.have.lengthOf(1 + 12);
});
});
});
describe('integration (standard setup)', () => {
const replId = 'rs0';
const [ srv0, srv1, srv2, srv3 ] = startTestCluster(
['--single', '--replSet', replId],
['--single', '--replSet', replId],
['--single', '--replSet', replId],
['--single', '--replSet', replId]
);
let cfg: Partial<ReplSetConfig>;
let additionalServer: MongodSetup;
let serviceProvider: CliServiceProvider;
let instanceState: ShellInstanceState;
let db: Database;
let rs: ReplicaSet;
before(async function() {
this.timeout(100_000);
cfg = {
_id: replId,
members: [
{ _id: 0, host: `${await srv0.hostport()}`, priority: 1 },
{ _id: 1, host: `${await srv1.hostport()}`, priority: 0 },
{ _id: 2, host: `${await srv2.hostport()}`, priority: 0 }
]
};
additionalServer = srv3;
serviceProvider = await CliServiceProvider.connect(`${await srv0.connectionString()}?directConnection=true`, {}, {}, new EventEmitter());
instanceState = new ShellInstanceState(serviceProvider);
db = instanceState.currentDb;
rs = new ReplicaSet(db);
// check replset uninitialized
try {
await rs.status();
expect.fail();
} catch (error) {
expect(error.message).to.include('no replset config');
}
const result = await rs.initiate(cfg);
expect(result.ok).to.equal(1);
// https://jira.mongodb.org/browse/SERVER-55371
// expect(result.$clusterTime).to.not.be.undefined;
});
beforeEach(async() => {
await ensureMaster(rs, 1000, await srv0.hostport());
expect((await rs.conf()).members.length).to.equal(3);
});
after(() => {
return serviceProvider.close(true);
});
describe('replica set info', () => {
it('returns the status', async() => {
const result = await rs.status();
expect(result.set).to.equal(replId);
});
it('returns the config', async() => {
const result = await rs.conf();
expect(result._id).to.equal(replId);
});
it('is connected to master', async() => {
const result = await rs.isMaster();
expect(result.ismaster).to.be.true;
});
it('returns StatsResult for print secondary replication info', async() => {
const result = await rs.printSecondaryReplicationInfo();
expect(result.type).to.equal('StatsResult');
});
it('returns StatsResult for print replication info', async() => {
const result = await rs.printReplicationInfo();
expect(result.type).to.equal('StatsResult');
});
it('returns data for db.getReplicationInfo', async() => {
const result = await rs._database.getReplicationInfo();
expect(Object.keys(result)).to.include('logSizeMB');
});
});
describe('watch', () => {
afterEach(async() => {
await db.dropDatabase();
});
it('allows watching changes as they happen', async() => {
const coll = db.getCollection('cstest');
const cs = await coll.watch();
await coll.insertOne({ i: 42 });
expect((await cs.next()).fullDocument.i).to.equal(42);
});
it('allow to resume watching changes as they happen', async() => {
const coll = db.getCollection('cstest');
const cs = await coll.watch();
await coll.insertOne({ i: 123 });
expect((await cs.next()).fullDocument.i).to.equal(123);
const token = cs.getResumeToken();
await coll.insertOne({ i: 456 });
expect((await cs.next()).fullDocument.i).to.equal(456);
const cs2 = await coll.watch({ resumeAfter: token });
expect((await cs2.next()).fullDocument.i).to.equal(456);
});
});
describe('reconfig', () => {
it('reconfig with one less secondary', async() => {
const newcfg: Partial<ReplSetConfig> = {
_id: replId,
members: [ cfg.members[0], cfg.members[1] ]
};
const version = (await rs.conf()).version;
const result = await rs.reconfig(newcfg);
expect(result.ok).to.equal(1);
const status = await rs.conf();
expect(status.members.length).to.equal(2);
expect(status.version).to.be.greaterThan(version);
});
afterEach(async() => {
await rs.reconfig(cfg);
const status = await rs.conf();
expect(status.members.length).to.equal(3);
});
});
describe('add member', () => {
skipIfServerVersion(srv0, '< 4.4');
it('adds a regular member to the config', async() => {
const version = (await rs.conf()).version;
const result = await rs.add(`${await additionalServer.hostport()}`);
expect(result.ok).to.equal(1);
const conf = await rs.conf();
expect(conf.members.length).to.equal(4);
expect(conf.version).to.be.greaterThan(version);
});
it('adds a arbiter member to the config', async() => {
if (semver.gte(await instanceState.currentDb.version(), '4.4.0')) { // setDefaultRWConcern is 4.4+ only
await instanceState.currentDb.getSiblingDB('admin').runCommand({
setDefaultRWConcern: 1,
defaultWriteConcern: { w: 'majority' }
});
}
const version = (await rs.conf()).version;
const result = await rs.addArb(`${await additionalServer.hostport()}`);
expect(result.ok).to.equal(1);
const conf = await rs.conf();
expect(conf.members.length).to.equal(4);
expect(conf.members[3].arbiterOnly).to.equal(true);
expect(conf.version).to.be.greaterThan(version);
});
afterEach(async() => {
await rs.reconfig(cfg);
const status = await rs.conf();
expect(status.members.length).to.equal(3);
});
});
describe('remove member', () => {
it('removes a member of the config', async() => {
const version = (await rs.conf()).version;
const result = await rs.remove(cfg.members[2].host);
expect(result.ok).to.equal(1);
const conf = await rs.conf();
expect(conf.members.length).to.equal(2);
expect(conf.version).to.be.greaterThan(version);
});
afterEach(async() => {
await rs.reconfig(cfg);
const status = await rs.conf();
expect(status.members.length).to.equal(3);
});
});
});
describe('integration (PA to PSA transition)', () => {
const replId = 'rspsa';
const [ srv0, srv1, srv2 ] = startTestCluster(
['--single', '--replSet', replId],
['--single', '--replSet', replId],
['--single', '--replSet', replId]
);
let serviceProvider: CliServiceProvider;
beforeEach(async() => {
serviceProvider = await CliServiceProvider.connect(`${await srv0.connectionString()}?directConnection=true`, {}, {}, new EventEmitter());
});
afterEach(async() => {
return await serviceProvider.close(true);
});
it('fails with rs.reconfig but works with rs.reconfigForPSASet', async function() {
this.timeout(100_000);
const [primary, secondary, arbiter] = await Promise.all([
srv0.hostport(),
srv1.hostport(),
srv2.hostport()
]);
const cfg = {
_id: replId,
members: [
{ _id: 0, host: primary, priority: 1 }
]
};
const instanceState = new ShellInstanceState(serviceProvider);
const db = instanceState.currentDb;
const rs = new ReplicaSet(db);
expect((await rs.initiate(cfg)).ok).to.equal(1);
await ensureMaster(rs, 1000, primary);
if (semver.gte(await db.version(), '4.4.0')) { // setDefaultRWConcern is 4.4+ only
await db.getSiblingDB('admin').runCommand({
setDefaultRWConcern: 1,
defaultWriteConcern: { w: 'majority' }
});
}
await rs.addArb(arbiter);
if (semver.gt(await db.version(), '4.9.0')) { // Exception currently 5.0+ only
try {
await rs.add(secondary);
expect.fail('missed assertion');
} catch (err) {
expect(err.codeName).to.equal('NewReplicaSetConfigurationIncompatible');
}
}
const conf = await rs.conf();
conf.members.push({ _id: 2, host: secondary, votes: 1, priority: 1 });
await rs.reconfigForPSASet(2, conf);
const { members } = await rs.status();
expect(members).to.have.lengthOf(3);
expect(members.filter(member => member.stateStr === 'PRIMARY')).to.have.lengthOf(1);
});
});
}); | the_stack |
import AWSStorageProvider from '../src/providers/AWSS3Provider';
import { Storage as StorageClass } from '../src/Storage';
import { Storage as StorageCategory, StorageProvider } from '../src';
import axios, { CancelToken } from 'axios';
import { AWSS3UploadTask } from '../src/providers/AWSS3UploadTask';
import { S3Client } from '@aws-sdk/client-s3';
type CustomProviderConfig = {
foo: boolean;
bar: number;
};
const credentials = {
accessKeyId: 'accessKeyId',
sessionToken: 'sessionToken',
secretAccessKey: 'secretAccessKey',
identityId: 'identityId',
authenticated: true,
};
const options = {
bucket: 'bucket',
region: 'region',
credentials,
level: 'level',
};
class TestCustomProvider implements StorageProvider {
getProviderName(): string {
return 'customProvider' as const;
}
getCategory() {
return 'Storage' as const;
}
configure(o: any) {
return o;
}
get(key: string, config: CustomProviderConfig) {
return Promise.resolve({ newKey: 'get' });
}
put(key: string, object: any, config: CustomProviderConfig) {
return Promise.resolve({ newKey: 'put' });
}
remove(key: string, config: CustomProviderConfig) {
return Promise.resolve({ removed: 'remove' });
}
list(key: string, config: CustomProviderConfig) {
return Promise.resolve({ list: 'list' });
}
}
class TestCustomProviderWithCopy extends TestCustomProvider
implements StorageProvider {
copy(
src: { key: string },
dest: { key: string },
config: CustomProviderConfig
) {
return Promise.resolve({ newKey: 'copy' });
}
}
describe('Storage', () => {
describe('constructor test', () => {
test('happy case', () => {
new StorageClass();
});
});
describe('getPluggable test', () => {
test('happy case', () => {
const storage = new StorageClass();
const provider = new AWSStorageProvider();
storage.addPluggable(provider);
expect(storage.getPluggable(provider.getProviderName())).toBeInstanceOf(
AWSStorageProvider
);
});
});
describe('removePluggable test', () => {
test('happy case', () => {
const storage = new StorageClass();
const provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.removePluggable(provider.getProviderName());
expect(storage.getPluggable(provider.getProviderName())).toBeNull();
});
});
describe('configure test', () => {
test('configure with aws-exports file', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
const config = storage.configure(aws_options);
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
},
});
});
test('configure with bucket and region', () => {
const storage = new StorageClass();
const aws_options = {
bucket: 'bucket',
region: 'region',
};
const config = storage.configure(aws_options);
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
},
});
});
test('Configure with Storage object', () => {
const storage = new StorageClass();
const aws_options = {
Storage: {
bucket: 'bucket',
region: 'region',
},
};
const config = storage.configure(aws_options);
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
},
});
});
test('Configure with Provider object', () => {
const storage = new StorageClass();
const aws_options = {
AWSS3: {
bucket: 'bucket',
region: 'region',
},
};
const config = storage.configure(aws_options);
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
},
});
});
test('Configure with Storage and Provider object', () => {
const storage = new StorageClass();
const aws_options = {
Storage: {
AWSS3: {
bucket: 'bucket',
region: 'region',
},
},
};
const config = storage.configure(aws_options);
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
},
});
});
test('Second configure call changing bucket name only', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
const config = storage.configure({ bucket: 'another-bucket' });
expect(config).toEqual({
AWSS3: {
bucket: 'another-bucket',
region: 'region',
},
});
});
test('Second configure call changing bucket, region and with Storage attribute', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
const config = storage.configure({
Storage: { bucket: 'another-bucket', region: 'another-region' },
});
expect(config).toEqual({
AWSS3: {
bucket: 'another-bucket',
region: 'another-region',
},
});
});
test('Second configure call changing bucket, region and with Provider attribute', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
const config = storage.configure({
AWSS3: { bucket: 'another-s3-bucket', region: 'another-s3-region' },
});
expect(config).toEqual({
AWSS3: {
bucket: 'another-s3-bucket',
region: 'another-s3-region',
},
});
});
test('backwards compatible issue, second configure call', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
const config = storage.configure({ level: 'private' });
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
level: 'private',
},
});
});
test('vault level is always private', () => {
const storage = StorageCategory;
expect.assertions(3);
storage.vault.configure = jest.fn().mockImplementation(configure => {
expect(configure).toEqual({
AWSS3: { bucket: 'bucket', level: 'private', region: 'region' },
});
});
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
storage.configure({ Storage: { level: 'protected' } });
storage.configure({ Storage: { level: 'public' } });
});
test('normal storage level is public by default', () => {
const storage = StorageCategory;
storage.configure({
region: 'region',
bucket: 'bucket',
});
expect(storage['_config']).toEqual({
AWSS3: {
bucket: 'bucket',
level: 'public',
region: 'region',
},
});
});
test('backwards compatible issue, third configure call track', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
storage.configure({ level: 'protected' });
const config = storage.configure({ track: true });
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
level: 'protected',
track: true,
},
});
});
test('backwards compatible issue, third configure to update level', () => {
const storage = new StorageClass();
const aws_options = {
aws_user_files_s3_bucket: 'bucket',
aws_user_files_s3_bucket_region: 'region',
};
storage.configure(aws_options);
storage.configure({ level: 'private' });
const config = storage.configure({ level: 'protected' });
expect(config).toEqual({
AWSS3: {
bucket: 'bucket',
region: 'region',
level: 'protected',
},
});
});
test('should add server side encryption to storage config when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'testBucket',
aws_user_files_s3_bucket_region: 'imaregion',
};
storage.configure(awsconfig);
const config = storage.configure({
serverSideEncryption: 'iamencrypted',
});
expect(config).toEqual({
AWSS3: {
bucket: 'testBucket',
region: 'imaregion',
serverSideEncryption: 'iamencrypted',
},
});
});
test('should add SSECustomerAlgorithm to storage config when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'thisIsABucket',
aws_user_files_s3_bucket_region: 'whatregionareyou',
};
storage.configure(awsconfig);
const config = storage.configure({ SSECustomerAlgorithm: '23s2sc' });
expect(config).toEqual({
AWSS3: {
bucket: 'thisIsABucket',
region: 'whatregionareyou',
SSECustomerAlgorithm: '23s2sc',
},
});
});
test('should add SSECustomerKey to storage config when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'buckbuckbucket',
aws_user_files_s3_bucket_region: 'thisisaregion',
};
storage.configure(awsconfig);
const config = storage.configure({ SSECustomerKey: 'iamakey' });
expect(config).toEqual({
AWSS3: {
bucket: 'buckbuckbucket',
region: 'thisisaregion',
SSECustomerKey: 'iamakey',
},
});
});
test('should add SSECustomerKeyMD5 to storage config when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'buckbuckbucaket',
aws_user_files_s3_bucket_region: 'ohnoregion',
};
storage.configure(awsconfig);
const config = storage.configure({ SSECustomerKeyMD5: 'somekey' });
expect(config).toEqual({
AWSS3: {
bucket: 'buckbuckbucaket',
region: 'ohnoregion',
SSECustomerKeyMD5: 'somekey',
},
});
});
test('should add SSEKMSKeyId to storage config when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'bucket2',
aws_user_files_s3_bucket_region: 'region1',
};
storage.configure(awsconfig);
const config = storage.configure({ SSEKMSKeyId: 'giveMeAnId' });
expect(config).toEqual({
AWSS3: {
bucket: 'bucket2',
region: 'region1',
SSEKMSKeyId: 'giveMeAnId',
},
});
});
test('should not add randomKeyId to storage config object when present', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'bucket2',
aws_user_files_s3_bucket_region: 'region1',
};
storage.configure(awsconfig);
const config = storage.configure({ randomKeyId: 'someRandomKey' });
expect(config).toEqual({
AWSS3: {
bucket: 'bucket2',
region: 'region1',
},
});
});
test('should add customPrefix to AWSS3 provider object if is defined', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'i_am_a_bucket',
aws_user_files_s3_bucket_region: 'IAD',
};
storage.configure(awsconfig);
const config = storage.configure({
customPrefix: {
protected: 'iamprotected',
private: 'iamprivate',
public: 'opentotheworld',
},
});
expect(config).toEqual({
AWSS3: {
bucket: 'i_am_a_bucket',
region: 'IAD',
customPrefix: {
protected: 'iamprotected',
private: 'iamprivate',
public: 'opentotheworld',
},
},
});
});
test('should not add customPrefix to AWSS3 provider object if value is undefined', () => {
const storage = new StorageClass();
const awsconfig = {
aws_user_files_s3_bucket: 'you_dont_know_this_bucket',
aws_user_files_s3_bucket_region: 'WD3',
};
storage.configure(awsconfig);
const config = storage.configure({
customPrefix: undefined,
});
expect(config).toEqual({
AWSS3: {
bucket: 'you_dont_know_this_bucket',
region: 'WD3',
},
customPrefix: {},
});
});
});
describe('get test', () => {
let storage: StorageClass;
let provider: StorageProvider;
let getSpy: jest.SpyInstance;
beforeEach(() => {
storage = new StorageClass();
provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
getSpy = jest
.spyOn(AWSStorageProvider.prototype, 'get')
.mockImplementation(() => Promise.resolve('url'));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('with default S3 provider', () => {
test('get object without download', async () => {
const url = await storage.get('key', { download: false });
expect(getSpy).toBeCalled();
expect(url).toEqual('url');
getSpy.mockClear();
});
test('get object with download', async () => {
const blob = { Body: new Blob(['body']) };
getSpy = jest
.spyOn(AWSStorageProvider.prototype, 'get')
.mockImplementation(() => {
return Promise.resolve(blob);
});
const getOutput = await storage.get('key', { download: true });
expect(getSpy).toBeCalled();
expect(getOutput).toBe(blob);
getSpy.mockClear();
});
test('get object with all available config', async () => {
await storage.get('key', {
download: false,
contentType: 'text/plain',
contentDisposition: 'contentDisposition',
contentLanguage: 'contentLanguage',
contentEncoding: 'contentEncoding',
cacheControl: 'cacheControl',
identityId: 'identityId',
expires: 100,
progressCallback: () => {},
SSECustomerAlgorithm: 'aes256',
SSECustomerKey: 'key',
SSECustomerKeyMD5: 'md5',
customPrefix: {
public: 'public',
protected: 'protected',
private: 'private',
},
level: 'private',
track: false,
});
});
});
test('get without provider', async () => {
const storage = new StorageClass();
try {
await storage.get('key');
} catch (err) {
expect(err).toEqual('No plugin found in Storage for the provider');
}
});
test('get with custom provider', async () => {
const customProvider = new TestCustomProvider();
const customProviderGetSpy = jest.spyOn(customProvider, 'get');
storage.addPluggable(customProvider);
const getRes = await storage.get<TestCustomProvider>('key', {
provider: 'customProvider',
foo: false,
bar: 10,
});
expect(customProviderGetSpy).toBeCalled();
expect(getRes.newKey).toEqual('get');
});
// backwards compatible with current custom provider user
test('get with custom provider should work with no generic type provided', async () => {
const customProvider = new TestCustomProvider();
const customProviderGetSpy = jest.spyOn(customProvider, 'get');
storage.addPluggable(customProvider);
await storage.get('key', {
provider: 'customProvider',
config1: true,
config2: false,
config3: 'config',
});
expect(customProviderGetSpy).toBeCalled();
});
});
describe('put test', () => {
let storage: StorageClass;
let provider: StorageProvider;
let putSpy: jest.SpyInstance;
beforeEach(() => {
storage = new StorageClass();
provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
putSpy = jest
.spyOn(AWSStorageProvider.prototype, 'put')
.mockImplementation(() => Promise.resolve({ key: 'new_object' }));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('with default provider', () => {
test('put object successfully', async () => {
await storage.put('key', 'object');
expect(putSpy).toBeCalled();
putSpy.mockClear();
});
test('call put object with all available config', async () => {
const putRes = await storage.put('key', 'object', {
progressCallback: _progress => {},
serverSideEncryption: 'serverSideEncryption',
SSECustomerAlgorithm: 'aes256',
SSECustomerKey: 'key',
SSECustomerKeyMD5: 'md5',
SSEKMSKeyId: 'id',
acl: 'acl',
cacheControl: 'cacheControl',
contentDisposition: 'contentDisposition',
contentEncoding: 'contentEncoding',
contentType: 'contentType',
expires: new Date(),
metadata: {
key: 'value',
},
tagging: 'tag',
});
expect(putRes).toEqual({ key: 'new_object' });
});
});
test('put without provider', async () => {
const storage = new StorageClass();
try {
await storage.put('key', 'test upload');
} catch (err) {
expect(err).toEqual('No plugin found in Storage for the provider');
}
});
test('put with resumable flag', async () => {
putSpy = jest
.spyOn(AWSStorageProvider.prototype, 'put')
.mockImplementation(() => ({
pause: jest.fn(),
resume: jest.fn(),
percent: 0,
isInProgress: false,
}));
const blob = new Blob(['blob']);
const uploadTask = storage.put('key', blob, {
resumable: true,
});
uploadTask.pause();
uploadTask.resume();
storage.cancel(uploadTask);
});
test('put with custom provider', async () => {
const customProvider = new TestCustomProvider();
const customProviderPutSpy = jest.spyOn(customProvider, 'put');
storage.addPluggable(customProvider);
const putRes = await storage.put<TestCustomProvider>('key', 'object', {
provider: 'customProvider',
foo: false,
bar: 40,
});
expect(customProviderPutSpy).toBeCalled();
expect(putRes.newKey).toEqual('put');
});
// backwards compatible with current custom provider user
test('put with custom provider should work with no generic type provided', async () => {
const customProvider = new TestCustomProvider();
const customProviderPutSpy = jest.spyOn(customProvider, 'put');
storage.addPluggable(customProvider);
await storage.put('key', 'object', {
provider: 'customProvider',
config1: true,
config2: false,
config3: 'config',
});
storage.put('key', 'obj', {
track: false,
});
expect(customProviderPutSpy).toBeCalled();
});
});
describe('remove test', () => {
let storage: StorageClass;
let provider: StorageProvider;
let removeSpy: jest.SpyInstance;
beforeEach(() => {
storage = new StorageClass();
provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
removeSpy = jest
.spyOn(AWSStorageProvider.prototype, 'remove')
.mockImplementation(() => Promise.resolve({ $metadata: {} }));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('with default provider', () => {
test('remove object successfully', async () => {
await storage.remove('key');
expect(removeSpy).toBeCalled();
removeSpy.mockClear();
});
test('call remove with all available config', async () => {
storage.remove('key', {
track: false,
level: 'public',
customPrefix: {
public: 'public',
protected: 'protected',
private: 'private',
},
});
expect(removeSpy).toBeCalled();
removeSpy.mockClear();
});
});
test('remove without provider', async () => {
const storage = new StorageClass();
try {
await storage.remove('key');
} catch (err) {
expect(err).toEqual('No plugin found in Storage for the provider');
}
});
test('remove with custom provider', async () => {
const customProvider = new TestCustomProvider();
const customProviderRemoveSpy = jest.spyOn(customProvider, 'remove');
storage.addPluggable(customProvider);
const removeRes = await storage.remove<TestCustomProvider>('key', {
provider: 'customProvider',
foo: false,
bar: 40,
});
expect(customProviderRemoveSpy).toBeCalled();
expect(removeRes.removed).toEqual('remove');
});
// backwards compatible with current custom provider user
test('remove with custom provider should work with no generic type provided', async () => {
const customProvider = new TestCustomProvider();
const customProviderRemoveSpy = jest.spyOn(customProvider, 'remove');
storage.addPluggable(customProvider);
storage.remove('key', {
provider: 'customProvider',
config1: true,
config2: false,
config3: 'config',
});
expect(customProviderRemoveSpy).toBeCalled();
});
});
describe('list test', () => {
let storage: StorageClass;
let provider: StorageProvider;
let listSpy: jest.SpyInstance;
beforeEach(() => {
storage = new StorageClass();
provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
listSpy = jest
.spyOn(AWSStorageProvider.prototype, 'list')
.mockImplementation(() => Promise.resolve([]));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('with default provider', () => {
test('list object successfully', async () => {
await storage.list('path');
expect(listSpy).toBeCalled();
listSpy.mockClear();
});
test('call list object with all available config', async () => {
storage.list('path', {
track: false,
maxKeys: 10,
level: 'public',
customPrefix: {
public: 'public',
protected: 'protected',
private: 'private',
},
});
});
});
test('list without provider', async () => {
const storage = new StorageClass();
try {
await storage.list('');
} catch (err) {
expect(err).toEqual('No plugin found in Storage for the provider');
}
});
test('list with customProvider', async () => {
const customProvider = new TestCustomProvider();
const customProviderListSpy = jest.spyOn(customProvider, 'list');
storage.addPluggable(customProvider);
const listRes = await storage.list<TestCustomProvider>('path', {
provider: 'customProvider',
foo: false,
bar: 40,
});
expect(customProviderListSpy).toBeCalled();
expect(listRes.list).toBe('list');
});
// backwards compatible with current custom provider user
test('list with customProvider should work with no generic type provided', async () => {
const customProvider = new TestCustomProvider();
const customProviderListSpy = jest.spyOn(customProvider, 'list');
storage.addPluggable(customProvider);
await storage.list('path', {
provider: 'customProvider',
config1: true,
config2: false,
config3: 'config',
});
expect(customProviderListSpy).toBeCalled();
});
});
describe('copy test', () => {
let storage: StorageClass;
let provider: StorageProvider;
let copySpy: jest.SpyInstance;
beforeEach(() => {
storage = new StorageClass();
provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
copySpy = jest
.spyOn(AWSStorageProvider.prototype, 'copy')
.mockImplementation(() => Promise.resolve({ key: 'key' }));
});
afterEach(() => {
jest.clearAllMocks();
});
describe('default provider', () => {
test('copy object successfully', async () => {
await storage.copy({ key: 'src' }, { key: 'dest' });
expect(copySpy).toBeCalled();
copySpy.mockReset();
});
test('call copy object with all available config', async () => {
storage.copy(
{ key: 'src', level: 'protected', identityId: 'identityId' },
{ key: 'dest', level: 'public' },
{
cacheControl: 'cacheControl',
contentDisposition: 'contentDisposition',
contentLanguage: 'contentLanguage',
contentType: 'contentType',
expires: new Date(),
tagging: 'tagging',
acl: 'acl',
metadata: { key: 'value' },
serverSideEncryption: 'sse',
SSECustomerAlgorithm: 'aes256',
SSECustomerKey: 'key',
SSECustomerKeyMD5: 'md5',
SSEKMSKeyId: 'id',
}
);
});
});
test('copy object without provider', async () => {
const storage = new StorageClass();
try {
await storage.copy({ key: 'src' }, { key: 'dest' });
} catch (err) {
expect(err).toEqual('No plugin found in Storage for the provider');
}
});
test('copy object with custom provider', async () => {
const customProviderWithCopy = new TestCustomProviderWithCopy();
const customProviderCopySpy = jest.spyOn(customProviderWithCopy, 'copy');
storage.addPluggable(customProviderWithCopy);
const copyRes = await storage.copy<TestCustomProviderWithCopy>(
{ key: 'src' },
{ key: 'dest' },
{
provider: 'customProvider',
foo: false,
bar: 40,
}
);
expect(customProviderCopySpy).toBeCalled();
expect(copyRes.newKey).toEqual('copy');
});
// backwards compatible with current custom provider user
test('copy object with custom provider should work with no generic type provided', async () => {
const customProviderWithCopy = new TestCustomProviderWithCopy();
const customProviderCopySpy = jest.spyOn(customProviderWithCopy, 'copy');
storage.addPluggable(customProviderWithCopy);
await storage.copy(
{ key: 'src' },
{ key: 'dest' },
{
provider: 'customProvider',
config1: true,
config2: false,
config3: 'config',
}
);
expect(customProviderCopySpy).toBeCalled();
});
});
describe('cancel test', () => {
let isCancelSpy: jest.SpyInstance;
let cancelTokenSpy: jest.SpyInstance;
let cancelMock: jest.Mock;
let tokenMock: jest.Mock;
beforeEach(() => {
cancelMock = jest.fn();
tokenMock = jest.fn();
isCancelSpy = jest.spyOn(axios, 'isCancel').mockReturnValue(true);
cancelTokenSpy = jest
.spyOn(axios.CancelToken, 'source')
.mockImplementation(() => {
return {
token: (tokenMock as unknown) as CancelToken,
cancel: cancelMock,
};
});
});
afterEach(() => {
jest.clearAllMocks();
});
test('happy case - cancel upload', async () => {
jest.spyOn(AWSStorageProvider.prototype, 'put').mockImplementation(() => {
return Promise.resolve({ key: 'new_object' });
});
const storage = new StorageClass();
const provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
const request = storage.put('test.txt', 'test upload');
storage.cancel(request, 'request cancelled');
expect(cancelTokenSpy).toBeCalledTimes(1);
expect(cancelMock).toHaveBeenCalledTimes(1);
try {
await request;
} catch (err) {
expect(err).toEqual('request cancelled');
expect(storage.isCancelError(err)).toBeTruthy();
}
});
test('happy case - cancel download', async () => {
jest.spyOn(AWSStorageProvider.prototype, 'get').mockImplementation(() => {
return Promise.resolve('some_file_content');
});
const storage = new StorageClass();
const provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
const request = storage.get('test.txt', {
download: true,
});
storage.cancel(request, 'request cancelled');
expect(cancelTokenSpy).toHaveBeenCalledTimes(1);
expect(cancelMock).toHaveBeenCalledWith('request cancelled');
try {
await request;
} catch (err) {
expect(err).toEqual('request cancelled');
expect(storage.isCancelError(err)).toBeTruthy();
}
});
test('happy case - cancel copy', async () => {
const storage = new StorageClass();
const provider = new AWSStorageProvider();
storage.addPluggable(provider);
storage.configure(options);
const request = storage.copy({ key: 'src' }, { key: 'dest' }, {});
storage.cancel(request, 'request cancelled');
expect(cancelTokenSpy).toHaveBeenCalledTimes(1);
expect(cancelMock).toHaveBeenCalledWith('request cancelled');
try {
await request;
} catch (err) {
expect(err).toEqual('request cancelled');
expect(storage.isCancelError(err)).toBeTruthy();
}
});
test('isCancelError called', () => {
const storage = new StorageClass();
storage.isCancelError({});
expect(isCancelSpy).toHaveBeenCalledTimes(1);
});
});
}); | the_stack |
import { extend, isNullOrUndefined, setValue, getValue, Ajax, addClass, removeClass } from '@syncfusion/ej2-base';
import { DataManager, Query, Group, DataUtil, QueryOptions, ReturnOption, ParamOption } from '@syncfusion/ej2-data';
import { ITreeData, RowExpandedEventArgs } from './interface';
import { TreeGrid } from './treegrid';
import { showSpinner, hideSpinner } from '@syncfusion/ej2-popups';
import { getObject, BeforeDataBoundArgs, VirtualContentRenderer, getUid, Row, Column } from '@syncfusion/ej2-grids';
import { ColumnModel as GridColumnModel, NotifyArgs, SaveEventArgs, Action, VirtualInfo } from '@syncfusion/ej2-grids';
import { isRemoteData, isOffline, isCountRequired, getExpandStatus } from '../utils';
import * as events from './constant';
/**
* Internal dataoperations for tree grid
*
* @hidden
*/
export class DataManipulation {
//Internal variables
private taskIds: Object[];
private parentItems: Object[];
private zerothLevelData: BeforeDataBoundArgs;
private storedIndex: number;
private batchChanges: Object;
private addedRecords: string = 'addedRecords';
private parent: TreeGrid;
private dataResults: ReturnOption;
private sortedData: Object[];
private hierarchyData: Object[];
private isSelfReference: boolean;
private isSortAction: boolean;
constructor(grid: TreeGrid) {
this.parent = grid;
this.parentItems = [];
this.taskIds = [];
this.hierarchyData = [];
this.storedIndex = -1;
this.sortedData = [];
this.isSortAction = false;
this.addEventListener();
this.dataResults = <ReturnOption>{};
this.isSelfReference = !isNullOrUndefined(this.parent.parentIdMapping);
}
/**
* @hidden
* @returns {void}
*/
public addEventListener(): void {
this.parent.on('updateRemoteLevel', this.updateParentRemoteData, this);
this.parent.grid.on('sorting-begin', this.beginSorting, this);
this.parent.on('updateAction', this.updateData, this);
this.parent.on(events.remoteExpand, this.collectExpandingRecs, this);
this.parent.on('dataProcessor', this.dataProcessor, this);
}
/**
* @hidden
* @returns {void}
*/
public removeEventListener(): void {
if (this.parent.isDestroyed) { return; }
this.parent.off(events.remoteExpand, this.collectExpandingRecs);
this.parent.off('updateRemoteLevel', this.updateParentRemoteData);
this.parent.off('updateAction', this.updateData);
this.parent.off('dataProcessor', this.dataProcessor);
this.parent.grid.off('sorting-begin', this.beginSorting);
}
/**
* To destroy the dataModule
*
* @returns {void}
* @hidden
*/
public destroy(): void {
this.removeEventListener();
}
/**
* @hidden
* @returns {boolean} -Returns whether remote data binding
*/
public isRemote(): boolean {
if (!(this.parent.dataSource instanceof DataManager)) {
return false;
}
return true;
// let gridData: DataManager = <DataManager>this.parent.dataSource;
// return gridData.dataSource.offline !== true && gridData.dataSource.url !== undefined;
}
/**
* Function to manipulate datasource
*
* @param {Object} data - Provide tree grid datasource to convert to flat data
* @hidden
* @returns {void}
*/
public convertToFlatData(data: Object): void {
this.parent.flatData = <Object[]>(Object.keys(data).length === 0 && !(this.parent.dataSource instanceof DataManager) ?
this.parent.dataSource : []);
this.parent.parentData = [];
if ((isRemoteData(this.parent) && !isOffline(this.parent)) && data instanceof DataManager && !(data instanceof Array)) {
const dm: DataManager = <DataManager>this.parent.dataSource;
if (this.parent.parentIdMapping) {
this.parent.query = isNullOrUndefined(this.parent.query) ?
new Query() : this.parent.query;
if (this.parent.parentIdMapping) {
const filterKey: Object[] = this.parent.query.params.filter((param: ParamOption) => param.key === 'IdMapping');
if (this.parent.initialRender && !filterKey.length) {
this.parent.query.where(this.parent.parentIdMapping, 'equal', null);
this.parent.query.addParams('IdMapping', this.parent.idMapping);
}
}
if (!this.parent.hasChildMapping) {
let qry: Query = this.parent.query.clone();
qry.queries = [];
qry = qry.select([this.parent.parentIdMapping]);
qry.isCountRequired = true;
dm.executeQuery(qry).then((e: ReturnOption) => {
this.parentItems = DataUtil.distinct(<Object[]>e.result, this.parent.parentIdMapping, false);
const req: number = getObject('dataSource.requests', this.parent).filter((e: Ajax) => {
return e.httpRequest.statusText !== 'OK'; }
).length;
if (req === 0) {
setValue('grid.contentModule.isLoaded', true, this.parent);
if (!isNullOrUndefined(this.zerothLevelData)) {
setValue('cancel', false, this.zerothLevelData);
getValue('grid.renderModule', this.parent).dataManagerSuccess(this.zerothLevelData);
this.zerothLevelData = null;
}
this.parent.grid.hideSpinner();
}
});
}
}
} else if (data instanceof Array) {
this.convertJSONData(data);
}
}
private convertJSONData(data: Object): void {
this.hierarchyData = [];
this.taskIds = [];
if (!this.parent.idMapping) {
this.hierarchyData = <Object[]> data;
} else {
const keys: string[] = Object.keys(data);
for (let i: number = 0; i < keys.length; i++) {
const tempData: Object = data[i];
this.hierarchyData.push(extend({}, tempData));
if (!isNullOrUndefined(tempData[this.parent.idMapping])) {
this.taskIds.push(tempData[this.parent.idMapping]);
}
}
}
if (this.isSelfReference) {
const selfData: ITreeData[] = [];
const mappingData: Object[] = new DataManager(this.hierarchyData).executeLocal(
new Query()
.group(this.parent.parentIdMapping)
);
for (let i: number = 0; i < mappingData.length; i++) {
const groupData: Group = mappingData[i];
const index: number = this.taskIds.indexOf(groupData.key);
if (!isNullOrUndefined(groupData.key)) {
if (index > -1) {
const childData: Object[] = (groupData.items);
this.hierarchyData[index][this.parent.childMapping] = childData;
continue;
}
}
selfData.push(...groupData.items);
}
this.hierarchyData = this.selfReferenceUpdate(selfData);
}
if (!Object.keys(this.hierarchyData).length) {
const isGantt: string = 'isGantt';
const referenceData: boolean = !(this.parent.dataSource instanceof DataManager) && this.parent[isGantt];
this.parent.flatData = referenceData ? <Object[]>(this.parent.dataSource) : [];
} else {
this.createRecords(this.hierarchyData);
}
this.storedIndex = -1;
}
// private crudActions(): void {
// if (this.parent.dataSource instanceof DataManager && (this.parent.dataSource.adaptor instanceof RemoteSaveAdaptor)) {
// let oldUpdate: Function = this.parent.dataSource.adaptor.update;
// this.parent.dataSource.adaptor.update =
// function (dm: DataManager, keyField: string, value: Object, tableName?: string, query?: Query, original?: Object): Object {
// value = getPlainData(value);
// return oldUpdate.apply(this, [dm, keyField, value, tableName, query, original]);
// }
// }
// }
private selfReferenceUpdate(selfData: ITreeData[]): ITreeData[] {
const result: ITreeData[] = [];
while (this.hierarchyData.length > 0 && selfData.length > 0) {
const index: number = selfData.indexOf(this.hierarchyData[0]);
if ( index === -1) {
this.hierarchyData.shift();
} else {
result.push(this.hierarchyData.shift());
selfData.splice(index, 1);
}
}
return result;
}
/**
* Function to update the zeroth level parent records in remote binding
*
* @param {BeforeDataBoundArgs} args - contains data before its bounds to tree grid
* @hidden
* @returns {void}
*/
private updateParentRemoteData(args?: BeforeDataBoundArgs) : void {
const records: ITreeData[] = args.result;
if (!this.parent.hasChildMapping && !this.parentItems.length &&
(!this.parent.loadChildOnDemand)) {
this.zerothLevelData = args;
setValue('cancel', true, args);
} else {
if (!this.parent.loadChildOnDemand) {
for (let rec: number = 0; rec < records.length; rec++) {
if (isCountRequired(this.parent) && records[rec].hasChildRecords && this.parent.initialRender) {
records[rec].expanded = false;
}
if (isNullOrUndefined(records[rec].index)) {
records[rec].taskData = extend({}, records[rec]);
records[rec].uniqueID = getUid(this.parent.element.id + '_data_');
setValue('uniqueIDCollection.' + records[rec].uniqueID, records[rec], this.parent);
records[rec].level = 0;
records[rec].index = Math.ceil(Math.random() * 1000);
if ((records[rec][this.parent.hasChildMapping] ||
this.parentItems.indexOf(records[rec][this.parent.idMapping]) !== -1)) {
records[rec].hasChildRecords = true;
}
records[rec].checkboxState = 'uncheck';
}
}
} else {
if (!isNullOrUndefined(records)) {
this.convertToFlatData(records);
}
}
}
args.result = this.parent.loadChildOnDemand ? this.parent.flatData : records;
this.parent.notify('updateResults', args);
}
/**
* Function to manipulate datasource
*
* @param {{record: ITreeData, rows: HTMLTableRowElement[], parentRow: HTMLTableRowElement}} rowDetails - Row details for which child rows has to be fetched
* @param {ITreeData} rowDetails.record - current expanding record
* @param {HTMLTableRowElement[]} rowDetails.rows - Expanding Row element
* @param {HTMLTableRowElement} rowDetails.parentRow - Curent expanding row element
* @param {boolean} isChild - Specified whether current record is already a child record
* @hidden
* @returns {void}
*/
private collectExpandingRecs(rowDetails: {record: ITreeData, rows: HTMLTableRowElement[], parentRow: HTMLTableRowElement},
isChild?: boolean): void {
let gridRows: HTMLTableRowElement[] = this.parent.getRows();
if (this.parent.rowTemplate) {
const rows: HTMLCollection = (this.parent.getContentTable() as HTMLTableElement).rows;
gridRows = [].slice.call(rows);
}
let childRecord: ITreeData;
if (rowDetails.rows.length > 0) {
if (!isChild) {
rowDetails.record.expanded = true;
}
for (let i: number = 0; i < rowDetails.rows.length; i++) {
rowDetails.rows[i].style.display = 'table-row';
if (this.parent.loadChildOnDemand) {
const targetEle: Element = rowDetails.rows[i].getElementsByClassName('e-treegridcollapse')[0];
childRecord = this.parent.rowTemplate ? this.parent.grid.getCurrentViewRecords()[rowDetails.rows[i].rowIndex] :
this.parent.grid.getRowObjectFromUID(rowDetails.rows[i].getAttribute('data-Uid')).data;
if (!isNullOrUndefined(targetEle) && childRecord.expanded) {
addClass([targetEle], 'e-treegridexpand');
removeClass([targetEle], 'e-treegridcollapse');
}
let childRows: HTMLTableRowElement[] = [];
childRows = gridRows.filter(
(r: HTMLTableRowElement) =>
r.querySelector(
'.e-gridrowindex' + childRecord.index + 'level' + (childRecord.level + 1)
)
);
if (childRows.length && childRecord.expanded) {
this.collectExpandingRecs({ record: childRecord, rows: childRows, parentRow: rowDetails.parentRow }, true);
}
}
const expandingTd: Element = rowDetails.rows[i].querySelector('.e-detailrowcollapse');
if (!isNullOrUndefined(expandingTd)) {
this.parent.grid.detailRowModule.expand(expandingTd);
}
}
} else {
this.fetchRemoteChildData({record: rowDetails.record, rows: rowDetails.rows, parentRow: rowDetails.parentRow});
}
}
private fetchRemoteChildData(rowDetails: { record: ITreeData, rows: HTMLTableRowElement[], parentRow: HTMLTableRowElement }): void {
const args: RowExpandedEventArgs = {row: rowDetails.parentRow, data: rowDetails.record};
const dm: DataManager = <DataManager>this.parent.dataSource;
const qry: Query = this.parent.grid.getDataModule().generateQuery();
const clonequries: QueryOptions[] = qry.queries.filter((e: QueryOptions) => e.fn !== 'onPage' && e.fn !== 'onWhere');
qry.queries = clonequries;
qry.isCountRequired = true;
qry.where(this.parent.parentIdMapping, 'equal', rowDetails.record[this.parent.idMapping]);
showSpinner(this.parent.element);
dm.executeQuery(qry).then((e: ReturnOption) => {
const datas: ITreeData[] = this.parent.grid.currentViewData.slice();
let inx: number = datas.indexOf(rowDetails.record);
if (inx === -1) {
this.parent.grid.getRowsObject().forEach((rows: Row<Column>) => {
if ((rows.data as ITreeData).uniqueID === rowDetails.record.uniqueID) {
inx = rows.index;
}
});
}
const haveChild: boolean[] = getObject('actual.nextLevel', e);
const result: ITreeData[] = <ITreeData[]>e.result;
rowDetails.record.childRecords = result;
for (let r: number = 0; r < result.length; r++) {
result[r].taskData = extend({}, result[r]);
result[r].level = rowDetails.record.level + 1;
result[r].index = Math.ceil(Math.random() * 1000);
const parentData: ITreeData = extend({}, rowDetails.record);
delete parentData.childRecords;
result[r].parentItem = parentData;
result[r].parentUniqueID = rowDetails.record.uniqueID;
result[r].uniqueID = getUid(this.parent.element.id + '_data_');
result[r].checkboxState = 'uncheck';
setValue('uniqueIDCollection.' + result[r].uniqueID, result[r], this.parent);
// delete result[r].parentItem.childRecords;
if ((result[r][this.parent.hasChildMapping] || this.parentItems.indexOf(result[r][this.parent.idMapping]) !== -1)
&& !(haveChild && !haveChild[r])) {
result[r].hasChildRecords = true; result[r].expanded = false;
}
datas.splice(inx + r + 1, 0, result[r]);
}
setValue('result', datas, e); setValue('action', 'beforecontentrender', e);
this.parent.trigger(events.actionComplete, e);
hideSpinner(this.parent.element);
if (this.parent.grid.aggregates.length > 0 && !this.parent.enableVirtualization) {
let gridQuery: Query = getObject('query', e);
const result: string = 'result';
if (isNullOrUndefined(gridQuery)) {
gridQuery = getValue('grid.renderModule.data', this.parent).aggregateQuery(new Query());
}
if (!isNullOrUndefined(gridQuery)) {
const summaryQuery: QueryOptions[] = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onAggregates');
e[result] = this.parent.summaryModule.calculateSummaryValue(summaryQuery, e[result], true);
}
}
e.count = this.parent.grid.pageSettings.totalRecordsCount;
const virtualArgs: NotifyArgs = {};
if (this.parent.enableVirtualization) {
this.remoteVirtualAction(virtualArgs);
}
const notifyArgs: { index: number, childData: ITreeData[] } = { index: inx, childData : result };
if (this.parent.enableInfiniteScrolling) {
this.parent.notify('infinite-remote-expand', notifyArgs);
} else {
getValue('grid.renderModule', this.parent).dataManagerSuccess(e, virtualArgs);
}
this.parent.trigger(events.expanded, args);
});
}
private remoteVirtualAction(virtualArgs: NotifyArgs): void {
virtualArgs.requestType = 'refresh';
setValue('isExpandCollapse', true, virtualArgs);
const contentModule: VirtualContentRenderer = getValue('grid.contentModule', this.parent);
const currentInfo: VirtualInfo = getValue('currentInfo', contentModule);
const prevInfo: VirtualInfo = getValue('prevInfo', contentModule);
if (currentInfo.loadNext && this.parent.grid.pageSettings.currentPage === currentInfo.nextInfo.page) {
this.parent.grid.pageSettings.currentPage = prevInfo.page;
}
}
private beginSorting(): void {
this.isSortAction = true;
}
private createRecords(data: Object, parentRecords?: ITreeData): ITreeData[] {
const treeGridData: ITreeData[] = [];
const keys: string[] = Object.keys(data);
for (let i: number = 0, len: number = keys.length; i < len; i++) {
const currentData: ITreeData = extend({}, data[i]);
currentData.taskData = data[i];
let level: number = 0;
this.storedIndex++;
if (!Object.prototype.hasOwnProperty.call(currentData, 'index')) {
currentData.index = this.storedIndex;
}
if (!isNullOrUndefined(currentData[this.parent.childMapping]) ||
(currentData[this.parent.hasChildMapping] && isCountRequired(this.parent))) {
currentData.hasChildRecords = true;
if (this.parent.enableCollapseAll || !isNullOrUndefined(this.parent.dataStateChange)
&& isNullOrUndefined(currentData[this.parent.childMapping])) {
currentData.expanded = false;
} else {
currentData.expanded = !isNullOrUndefined(currentData[this.parent.expandStateMapping])
? currentData[this.parent.expandStateMapping] : true;
}
}
if (!Object.prototype.hasOwnProperty.call(currentData, 'index')) {
currentData.index = currentData.hasChildRecords ? this.storedIndex : this.storedIndex;
}
if (this.isSelfReference && isNullOrUndefined(currentData[this.parent.parentIdMapping])) {
this.parent.parentData.push(currentData);
}
currentData.uniqueID = getUid(this.parent.element.id + '_data_');
setValue('uniqueIDCollection.' + currentData.uniqueID, currentData, this.parent);
if (!isNullOrUndefined(parentRecords)) {
const parentData: ITreeData = extend({}, parentRecords);
delete parentData.childRecords;
delete parentData[this.parent.childMapping];
if (this.isSelfReference) {
delete parentData.taskData[this.parent.childMapping];
}
currentData.parentItem = parentData;
currentData.parentUniqueID = parentData.uniqueID;
level = parentRecords.level + 1;
}
if (!Object.prototype.hasOwnProperty.call(currentData, 'level')) {
currentData.level = level;
}
currentData.checkboxState = 'uncheck';
if (isNullOrUndefined(currentData[this.parent.parentIdMapping]) || currentData.parentItem) {
this.parent.flatData.push(currentData);
}
if (!this.isSelfReference && currentData.level === 0) {
this.parent.parentData.push(currentData);
}
if (!isNullOrUndefined(currentData[this.parent.childMapping] && currentData[this.parent.childMapping].length )) {
const record: ITreeData[] = this.createRecords(currentData[this.parent.childMapping], currentData);
currentData.childRecords = record;
}
treeGridData.push(currentData);
}
return treeGridData;
}
/**
* Function to perform filtering/sorting action for local data
*
* @param {BeforeDataBoundArgs} args - data details to be processed before binding to grid
* @hidden
* @returns {void}
*/
public dataProcessor(args?: BeforeDataBoundArgs) : void {
const isExport: boolean = getObject('isExport', args); const expresults: Object = getObject('expresults', args);
const exportType: string = getObject('exportType', args); const isPrinting: boolean = getObject('isPrinting', args);
let dataObj: Object; const actionArgs: NotifyArgs = getObject('actionArgs', args);
let requestType: Action = getObject('requestType', args); let actionData: Object = getObject('data', args);
let action: string = getObject('action', args); const actionAddArgs: SaveEventArgs = actionArgs;
const primaryKeyColumnName: string = this.parent.getPrimaryKeyFieldNames()[0];
const dataValue: ITreeData = getObject('data', actionAddArgs);
if ((!isNullOrUndefined(actionAddArgs)) && (!isNullOrUndefined(actionAddArgs.action)) && (actionAddArgs.action === 'add')
&& (!isNullOrUndefined(actionAddArgs.data)) && isNullOrUndefined(actionAddArgs.data[primaryKeyColumnName])) {
actionAddArgs.data[primaryKeyColumnName] = args.result[actionAddArgs.index][primaryKeyColumnName];
dataValue.taskData[primaryKeyColumnName] = args.result[actionAddArgs.index][primaryKeyColumnName];
}
if ((!isNullOrUndefined(actionArgs) && Object.keys(actionArgs).length) || requestType === 'save') {
requestType = requestType ? requestType : actionArgs.requestType;
actionData = actionData ? actionData : getObject('data', actionArgs);
action = action ? action : getObject('action', actionArgs);
if (this.parent.editSettings.mode === 'Batch') {
this.batchChanges = this.parent.grid.editModule.getBatchChanges();
}
if (this.parent.isLocalData) {
this.updateAction(actionData, action, requestType);
}
}
if (isExport && !isNullOrUndefined(expresults)) {
dataObj = expresults;
} else {
dataObj = isCountRequired(this.parent) ? getValue('result', this.parent.grid.dataSource)
: this.parent.grid.dataSource;
}
let results: ITreeData[] = dataObj instanceof DataManager ? (<DataManager>dataObj).dataSource.json : <ITreeData[]>dataObj;
let count: number = isCountRequired(this.parent) ? getValue('count', this.parent.dataSource)
: results.length;
const qry: Query = new Query(); let gridQuery: Query = getObject('query', args);
let filterQuery: QueryOptions[]; let searchQuery: QueryOptions[];
if (!isNullOrUndefined(gridQuery)) {
filterQuery = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onWhere');
searchQuery = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onSearch');
}
if ((this.parent.grid.allowFiltering && this.parent.grid.filterSettings.columns.length) ||
(this.parent.grid.searchSettings.key.length > 0) || (!isNullOrUndefined(gridQuery) &&
(filterQuery.length || searchQuery.length) && this.parent.isLocalData)) {
if (isNullOrUndefined(gridQuery)) {
gridQuery = new Query(); gridQuery = getValue('grid.renderModule.data', this.parent).filterQuery(gridQuery);
gridQuery = getValue('grid.renderModule.data', this.parent).searchQuery(gridQuery);
}
const fltrQuery: QueryOptions[] = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onWhere');
const srchQuery: QueryOptions[] = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onSearch');
qry.queries = fltrQuery.concat(srchQuery); const filteredData: Object = new DataManager(results).executeLocal(qry);
this.parent.notify('updateFilterRecs', { data: filteredData });
results = <ITreeData[]>this.dataResults.result; this.dataResults.result = null;
if (this.parent.grid.aggregates.length > 0) {
const query: Query = getObject('query', args);
if (isNullOrUndefined(gridQuery)) {
gridQuery = getValue('grid.renderModule.data', this.parent).aggregateQuery(new Query());
}
if (!isNullOrUndefined(query)) {
const summaryQuery: QueryOptions[] = query.queries.filter((q: QueryOptions) => q.fn === 'onAggregates');
results = this.parent.summaryModule.calculateSummaryValue(summaryQuery, results, true);
}
}
}
if (this.parent.grid.aggregates.length && this.parent.grid.sortSettings.columns.length === 0
&& this.parent.grid.filterSettings.columns.length === 0 && !this.parent.grid.searchSettings.key.length) {
let gridQuery: Query = getObject('query', args);
if (isNullOrUndefined(gridQuery)) {
gridQuery = getValue('grid.renderModule.data', this.parent).aggregateQuery(new Query());
}
const summaryQuery: QueryOptions[] = gridQuery.queries.filter((q: QueryOptions) => q.fn === 'onAggregates');
results = this.parent.summaryModule.calculateSummaryValue(summaryQuery, this.parent.flatData, true);
}
if (this.parent.grid.sortSettings.columns.length > 0 || this.isSortAction) {
this.isSortAction = false;
const parentData: Object = this.parent.parentData;
const query: Query = getObject('query', args); const srtQry: Query = new Query();
for (let srt: number = this.parent.grid.sortSettings.columns.length - 1; srt >= 0; srt--) {
const getColumnByField: string = 'getColumnByField';
const col: GridColumnModel = this.parent.grid.renderModule.data[getColumnByField](this.parent.grid.
sortSettings.columns[srt].field);
const compFun: Function | string = col.sortComparer && isOffline(this.parent) ?
(col.sortComparer as Function).bind(col) :
this.parent.grid.sortSettings.columns[srt].direction;
srtQry.sortBy(this.parent.grid.sortSettings.columns[srt].field, compFun);
}
const modifiedData: Object = new DataManager(parentData).executeLocal(srtQry);
const sortArgs: { modifiedData: ITreeData[], filteredData: ITreeData[], srtQry: Query}
= {modifiedData: <Object[]>modifiedData, filteredData: results, srtQry: srtQry};
this.parent.notify('createSort', sortArgs); results = sortArgs.modifiedData;
this.dataResults.result = null; this.sortedData = results; this.parent.notify('updateModel', {});
if (this.parent.grid.aggregates.length > 0 && !isNullOrUndefined(query)) {
const isSort: boolean = false;
const query: Query = getObject('query', args);
const summaryQuery: QueryOptions[] = query.queries.filter((q: QueryOptions) => q.fn === 'onAggregates');
results = this.parent.summaryModule.calculateSummaryValue(summaryQuery, this.sortedData, isSort);
}
}
count = isCountRequired(this.parent) ? getValue('count', this.parent.dataSource)
: results.length;
const temp: BeforeDataBoundArgs = this.paging(results, count, isExport, isPrinting, exportType, args);
results = temp.result; count = temp.count;
args.result = results; args.count = count;
this.parent.notify('updateResults', args);
}
private paging(results: ITreeData[], count: number, isExport: boolean,
isPrinting: boolean, exportType: string, args: Object): BeforeDataBoundArgs {
if (this.parent.allowPaging && (!isExport || exportType === 'CurrentPage')
&& (!isPrinting || this.parent.printMode === 'CurrentPage')) {
this.parent.notify(events.pagingActions, {result: results, count: count});
results = <ITreeData[]>this.dataResults.result;
count = isCountRequired(this.parent) ? getValue('count', this.parent.dataSource)
: this.dataResults.count;
} else if ((this.parent.enableVirtualization || this.parent.enableInfiniteScrolling) && (!isExport || exportType === 'CurrentPage')
&& getValue('requestType', args) !== 'save') {
const actArgs: Object = this.parent.enableInfiniteScrolling ? args : getValue('actionArgs', args);
this.parent.notify(events.pagingActions, {result: results, count: count, actionArgs: actArgs});
results = <ITreeData[]>this.dataResults.result;
count = this.dataResults.count;
}
const isPdfExport: string = 'isPdfExport'; const isCollapsedStatePersist: string = 'isCollapsedStatePersist';
if ((isPrinting === true || (args[isPdfExport] && (isNullOrUndefined(args[isCollapsedStatePersist])
|| args[isCollapsedStatePersist]))) && this.parent.printMode === 'AllPages') {
const actualResults: ITreeData[] = [];
for (let i: number = 0; i < results.length; i++) {
const expandStatus: boolean = getExpandStatus(this.parent, results[i], this.parent.parentData);
if (expandStatus) {
actualResults.push(results[i]);
}
}
results = actualResults;
count = results.length;
}
const value: BeforeDataBoundArgs = { result: results, count: count };
return value;
}
private updateData(dataResult: {result: ITreeData, count: number}): void {
this.dataResults = <ReturnOption>dataResult;
}
private updateAction(actionData: ITreeData, action: string, requestType: string): void {
if ((requestType === 'delete' || requestType === 'save')) {
this.parent.notify(events.crudAction, { value: actionData, action: action || requestType });
}
if (requestType === 'batchsave' && this.parent.editSettings.mode === 'Batch') {
this.parent.notify(events.batchSave, {});
}
}
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
export const metricOnly = {
hits: { total: 1000, hits: [], max_score: 0 },
aggregations: {
agg_1: { value: 412032 },
},
};
export const threeTermBuckets = {
hits: { total: 1000, hits: [], max_score: 0 },
aggregations: {
agg_2: {
buckets: [
{
key: 'png',
doc_count: 50,
agg_1: { value: 412032 },
agg_3: {
buckets: [
{
key: 'IT',
doc_count: 10,
agg_1: { value: 9299 },
agg_4: {
buckets: [
{ key: 'win', doc_count: 4, agg_1: { value: 0 } },
{ key: 'mac', doc_count: 6, agg_1: { value: 9299 } },
],
},
},
{
key: 'US',
doc_count: 20,
agg_1: { value: 8293 },
agg_4: {
buckets: [
{ key: 'linux', doc_count: 12, agg_1: { value: 3992 } },
{ key: 'mac', doc_count: 8, agg_1: { value: 3029 } },
],
},
},
],
},
},
{
key: 'css',
doc_count: 20,
agg_1: { value: 412032 },
agg_3: {
buckets: [
{
key: 'MX',
doc_count: 7,
agg_1: { value: 9299 },
agg_4: {
buckets: [
{ key: 'win', doc_count: 3, agg_1: { value: 4992 } },
{ key: 'mac', doc_count: 4, agg_1: { value: 5892 } },
],
},
},
{
key: 'US',
doc_count: 13,
agg_1: { value: 8293 },
agg_4: {
buckets: [
{ key: 'linux', doc_count: 12, agg_1: { value: 3992 } },
{ key: 'mac', doc_count: 1, agg_1: { value: 3029 } },
],
},
},
],
},
},
{
key: 'html',
doc_count: 90,
agg_1: { value: 412032 },
agg_3: {
buckets: [
{
key: 'CN',
doc_count: 85,
agg_1: { value: 9299 },
agg_4: {
buckets: [
{ key: 'win', doc_count: 46, agg_1: { value: 4992 } },
{ key: 'mac', doc_count: 39, agg_1: { value: 5892 } },
],
},
},
{
key: 'FR',
doc_count: 15,
agg_1: { value: 8293 },
agg_4: {
buckets: [
{ key: 'win', doc_count: 3, agg_1: { value: 3992 } },
{ key: 'mac', doc_count: 12, agg_1: { value: 3029 } },
],
},
},
],
},
},
],
},
},
};
export const oneTermOneHistogramBucketWithTwoMetricsOneTopHitOneDerivative = {
hits: { total: 1000, hits: [], max_score: 0 },
aggregations: {
agg_3: {
buckets: [
{
key: 'png',
doc_count: 50,
agg_4: {
buckets: [
{
key_as_string: '2014-09-28T00:00:00.000Z',
key: 1411862400000,
doc_count: 1,
agg_1: { value: 9283 },
agg_2: { value: 1411862400000 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 23,
},
},
],
},
},
},
{
key_as_string: '2014-09-29T00:00:00.000Z',
key: 1411948800000,
doc_count: 2,
agg_1: { value: 28349 },
agg_2: { value: 1411948800000 },
agg_5: { value: 203 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 39,
},
},
],
},
},
},
{
key_as_string: '2014-09-30T00:00:00.000Z',
key: 1412035200000,
doc_count: 3,
agg_1: { value: 84330 },
agg_2: { value: 1412035200000 },
agg_5: { value: 200 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 329,
},
},
],
},
},
},
{
key_as_string: '2014-10-01T00:00:00.000Z',
key: 1412121600000,
doc_count: 4,
agg_1: { value: 34992 },
agg_2: { value: 1412121600000 },
agg_5: { value: 103 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 22,
},
},
],
},
},
},
{
key_as_string: '2014-10-02T00:00:00.000Z',
key: 1412208000000,
doc_count: 5,
agg_1: { value: 145432 },
agg_2: { value: 1412208000000 },
agg_5: { value: 153 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 93,
},
},
],
},
},
},
{
key_as_string: '2014-10-03T00:00:00.000Z',
key: 1412294400000,
doc_count: 35,
agg_1: { value: 220943 },
agg_2: { value: 1412294400000 },
agg_5: { value: 239 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 72,
},
},
],
},
},
},
],
},
},
{
key: 'css',
doc_count: 20,
agg_4: {
buckets: [
{
key_as_string: '2014-09-28T00:00:00.000Z',
key: 1411862400000,
doc_count: 1,
agg_1: { value: 9283 },
agg_2: { value: 1411862400000 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 75,
},
},
],
},
},
},
{
key_as_string: '2014-09-29T00:00:00.000Z',
key: 1411948800000,
doc_count: 2,
agg_1: { value: 28349 },
agg_2: { value: 1411948800000 },
agg_5: { value: 10 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 11,
},
},
],
},
},
},
{
key_as_string: '2014-09-30T00:00:00.000Z',
key: 1412035200000,
doc_count: 3,
agg_1: { value: 84330 },
agg_2: { value: 1412035200000 },
agg_5: { value: 24 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 238,
},
},
],
},
},
},
{
key_as_string: '2014-10-01T00:00:00.000Z',
key: 1412121600000,
doc_count: 4,
agg_1: { value: 34992 },
agg_2: { value: 1412121600000 },
agg_5: { value: 49 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 343,
},
},
],
},
},
},
{
key_as_string: '2014-10-02T00:00:00.000Z',
key: 1412208000000,
doc_count: 5,
agg_1: { value: 145432 },
agg_2: { value: 1412208000000 },
agg_5: { value: 100 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 837,
},
},
],
},
},
},
{
key_as_string: '2014-10-03T00:00:00.000Z',
key: 1412294400000,
doc_count: 5,
agg_1: { value: 220943 },
agg_2: { value: 1412294400000 },
agg_5: { value: 23 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 302,
},
},
],
},
},
},
],
},
},
{
key: 'html',
doc_count: 90,
agg_4: {
buckets: [
{
key_as_string: '2014-09-28T00:00:00.000Z',
key: 1411862400000,
doc_count: 10,
agg_1: { value: 9283 },
agg_2: { value: 1411862400000 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 30,
},
},
],
},
},
},
{
key_as_string: '2014-09-29T00:00:00.000Z',
key: 1411948800000,
doc_count: 20,
agg_1: { value: 28349 },
agg_2: { value: 1411948800000 },
agg_5: { value: 1 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 43,
},
},
],
},
},
},
{
key_as_string: '2014-09-30T00:00:00.000Z',
key: 1412035200000,
doc_count: 30,
agg_1: { value: 84330 },
agg_2: { value: 1412035200000 },
agg_5: { value: 5 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 88,
},
},
],
},
},
},
{
key_as_string: '2014-10-01T00:00:00.000Z',
key: 1412121600000,
doc_count: 11,
agg_1: { value: 34992 },
agg_2: { value: 1412121600000 },
agg_5: { value: 10 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 91,
},
},
],
},
},
},
{
key_as_string: '2014-10-02T00:00:00.000Z',
key: 1412208000000,
doc_count: 12,
agg_1: { value: 145432 },
agg_2: { value: 1412208000000 },
agg_5: { value: 43 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 534,
},
},
],
},
},
},
{
key_as_string: '2014-10-03T00:00:00.000Z',
key: 1412294400000,
doc_count: 7,
agg_1: { value: 220943 },
agg_2: { value: 1412294400000 },
agg_5: { value: 1 },
agg_6: {
hits: {
total: 2,
hits: [
{
fields: {
bytes: 553,
},
},
],
},
},
},
],
},
},
],
},
},
};
export const oneRangeBucket = {
took: 35,
timed_out: false,
_shards: {
total: 1,
successful: 1,
failed: 0,
},
hits: {
total: 6039,
max_score: 0,
hits: [],
},
aggregations: {
agg_2: {
buckets: {
'0.0-1000.0': {
from: 0,
from_as_string: '0.0',
to: 1000,
to_as_string: '1000.0',
doc_count: 606,
},
'1000.0-2000.0': {
from: 1000,
from_as_string: '1000.0',
to: 2000,
to_as_string: '2000.0',
doc_count: 298,
},
},
},
},
};
export const oneFilterBucket = {
took: 11,
timed_out: false,
_shards: {
total: 1,
successful: 1,
failed: 0,
},
hits: {
total: 6005,
max_score: 0,
hits: [],
},
aggregations: {
agg_2: {
buckets: {
'type:apache': {
doc_count: 4844,
},
'type:nginx': {
doc_count: 1161,
},
},
},
},
};
export const oneHistogramBucket = {
took: 37,
timed_out: false,
_shards: {
total: 6,
successful: 6,
failed: 0,
},
hits: {
total: 49208,
max_score: 0,
hits: [],
},
aggregations: {
agg_2: {
buckets: [
{
key_as_string: '2014-09-28T00:00:00.000Z',
key: 1411862400000,
doc_count: 8247,
},
{
key_as_string: '2014-09-29T00:00:00.000Z',
key: 1411948800000,
doc_count: 8184,
},
{
key_as_string: '2014-09-30T00:00:00.000Z',
key: 1412035200000,
doc_count: 8269,
},
{
key_as_string: '2014-10-01T00:00:00.000Z',
key: 1412121600000,
doc_count: 8141,
},
{
key_as_string: '2014-10-02T00:00:00.000Z',
key: 1412208000000,
doc_count: 8148,
},
{
key_as_string: '2014-10-03T00:00:00.000Z',
key: 1412294400000,
doc_count: 8219,
},
],
},
},
}; | the_stack |
import { Promise } from "bluebird";
import Debug from "debug";
import { EventEmitter } from "events";
import { v4 as uuidv4} from "uuid";
import { murmur } from "murmurhash";
import { murmur2Partitioner } from "murmur2-partitioner";
import { Kafka, KafkaConfig, SASLMechanism, Admin, Producer, RecordMetadata, CompressionTypes } from "kafkajs";
import { Metadata, ProducerAnalytics, ProducerHealth, Check, ProducerRunResult, defaultAnalyticsInterval } from "../shared";
import { MessageReturn, JSKafkaProducerConfig, ProducerStats, AnalyticsConfig, KafkaLogger } from "../interfaces";
import fs from "fs";
const MESSAGE_TYPES = {
PUBLISH: "-published",
UNPUBLISH: "-unpublished",
UPDATE: "-updated"
};
const MAX_PART_AGE_MS = 1e3 * 60 * 5; //5 minutes
const MAX_PART_STORE_SIZE = 1e4;
const DEFAULT_MURMURHASH_VERSION = "3";
const DEFAULT_LOGGER = {
debug: Debug("sinek:jsproducer:debug"),
info: Debug("sinek:jsproducer:info"),
warn: Debug("sinek:jsproducer:warn"),
error: Debug("sinek:jsproducer:error")
};
/**
* native producer wrapper for node-librdkafka
* @extends EventEmitter
*/
export class JSProducer extends EventEmitter {
kafkaClient: Kafka;
config: JSKafkaProducerConfig;
paused = false;
producer: Producer | undefined;
private _health: ProducerHealth;
private _adminClient: Admin;
private _producerPollIntv = 0;
private _partitionCounts = {};
private _inClosing = false;
private _totalSentMessages = 0;
private _lastProcessed = 0;
private _analyticsOptions: AnalyticsConfig | null = null;
private _analyticsIntv: NodeJS.Timeout | null = null;
_analytics: ProducerAnalytics | undefined;
private _murmurHashVersion: string = DEFAULT_MURMURHASH_VERSION;
private _murmur;
private _errors = 0;
defaultPartitionCount = 1;
/**
* creates a new producer instance
* @param {object} config - configuration object
* @param {*} _ - ignore this param (api compatability)
* @param {number} defaultPartitionCount - amount of default partitions for the topics to produce to
*/
constructor(config: JSKafkaProducerConfig, defaultPartitionCount = 1) {
super();
if (!config) {
throw new Error("You are missing a config object.");
}
if (!config.logger || typeof config.logger !== "object") {
config.logger = DEFAULT_LOGGER;
}
if (!config.options) {
config.options = {};
}
const {
"metadata.broker.list": brokerList,
"client.id": clientId,
"security.protocol": securityProtocol,
"ssl.ca.location": sslCALocation,
"ssl.certificate.location": sslCertLocation,
"ssl.key.location": sslKeyLocation,
"ssl.key.password": sslKeyPassword,
"sasl.mechanisms": mechanism,
"sasl.username": username,
"sasl.password": password,
} = config.noptions;
const brokers = brokerList.split(",");
if (!brokers || !clientId) {
throw new Error("You are missing a broker or group configs");
}
const conf = {
brokers,
clientId,
} as KafkaConfig
if (securityProtocol) {
if (securityProtocol.includes('sasl')) {
conf.sasl = {
mechanism: mechanism as SASLMechanism,
username: username as string,
password: password as string,
}
}
if (securityProtocol.includes('ssl')) {
conf.ssl = {
ca: [fs.readFileSync(sslCALocation as string, "utf-8")],
cert: fs.readFileSync(sslCertLocation as string, "utf-8"),
key: fs.readFileSync(sslKeyLocation as string, "utf-8"),
passphrase: sslKeyPassword,
}
}
}
this.kafkaClient = new Kafka(conf);
this.config = config;
this._health = new ProducerHealth(this, this.config.health);
this._adminClient = this.kafkaClient.admin();
this._murmurHashVersion = this.config.options!.murmurHashVersion || DEFAULT_MURMURHASH_VERSION;
this.config.logger!.info(`using murmur ${this._murmurHashVersion} partitioner.`);
this.defaultPartitionCount = defaultPartitionCount;
switch (this._murmurHashVersion) {
case "2":
this._murmur = (key, partitionCount) => murmur2Partitioner.partition(key, partitionCount);
break;
case "3":
this._murmur = (key, partitionCount) => murmur.v3(key) % partitionCount;
break;
default:
throw new Error(`${this._murmurHashVersion} is not a supported murmur hash version. Choose '2' or '3'.`);
}
this.on("error", () => this._errors++);
}
/**
* @throws
* starts analytics tasks
* @param {object} options - analytic options
*/
enableAnalytics(options: { analyticsInterval: number } = {analyticsInterval: defaultAnalyticsInterval}): void {
if (this._analyticsIntv) {
throw new Error("analytics intervals are already running.");
}
let { analyticsInterval } = options;
this._analyticsOptions = options;
analyticsInterval = analyticsInterval || defaultAnalyticsInterval; // 150 sec
this._analyticsIntv = setInterval(this._runAnalytics.bind(this), analyticsInterval);
}
/**
* halts all analytics tasks
*/
haltAnalytics(): void {
if (this._analyticsIntv) {
clearInterval(this._analyticsIntv);
}
}
/**
* connects to the broker
* @returns {Promise.<*>}
*/
connect(): Promise<void> {
return new Promise((resolve, reject) => {
const { kafkaHost, logger } = this.config;
let { noptions, tconf } = this.config;
let conStr: string | null = null;
if (typeof kafkaHost === "string") {
conStr = kafkaHost;
}
if (conStr === null && !noptions) {
return reject(new Error("KafkaHost must be defined."));
}
const config = {
"metadata.broker.list": conStr,
"dr_cb": true
};
noptions = Object.assign({}, config, noptions);
logger!.debug(JSON.stringify(noptions));
tconf = tconf ? tconf : {
"request.required.acks": 1
};
logger!.debug(JSON.stringify(tconf));
this.producer = this.kafkaClient.producer();
const { CONNECT, DISCONNECT, REQUEST_TIMEOUT } = this.producer.events;
this.producer.on(REQUEST_TIMEOUT, details => {
this.emit("error", new Error(`Request Timed out. Info ${JSON.stringify(details)}`));
});
/* ### EOF STUFF ### */
this.producer.on(DISCONNECT, () => {
if (this._inClosing) {
this._reset();
}
logger!.warn("Disconnected.");
//auto-reconnect??? -> handled by producer.poll()
});
this.producer.on(CONNECT, () => {
logger!.info("KafkaJS producer is ready.");
this.emit("ready");
});
logger!.debug("Connecting..");
try {
Promise.all([
this.producer.connect(),
this._adminClient.connect(),
]).then(resolve);
} catch (error) {
this.emit("error", error);
return reject(error);
}
});
}
/**
* returns a partition for a key
* @private
* @param {string} - message key
* @param {number} - partition count of topic, if 0 defaultPartitionCount is used
* @returns {string} - deterministic partition value for key
*/
_getPartitionForKey(key: string, partitionCount = 1): number {
if (typeof key !== "string") {
throw new Error("key must be a string.");
}
if (typeof partitionCount !== "number") {
throw new Error("partitionCount must be number.");
}
return this._murmur(key, partitionCount);
}
/**
* @async
* produces a kafka message to a certain topic
* @param {string} topicName - name of the topic to produce to
* @param {object|string|null} message - value object for the message
* @param {number} _partition - optional partition to produce to
* @param {string} _key - optional message key
* @param {string} _partitionKey - optional key to evaluate partition for this message
* @returns {Promise.<object>}
*/
async send(
topicName: string,
message: Record<string, unknown> | string | null | Buffer,
_partition: number | null = null,
_key: string | null = null,
_partitionKey: string | null = null
): Promise<MessageReturn> {
/*
these are not supported in the HighLevelProducer of node-rdkafka
_opaqueKey = null,
_headers = null,
*/
if (!this.producer) {
throw new Error("You must call and await .connect() before trying to produce messages.");
}
if (this.paused) {
throw new Error("producer is paused.");
}
if (typeof message === "undefined" || !(typeof message === "string" || Buffer.isBuffer(message) || message === null)) {
throw new Error("message must be a string, an instance of Buffer or null.");
}
const key = _key ? _key : uuidv4();
let convertedMessage: Buffer;
if (message !== null) {
convertedMessage = Buffer.isBuffer(message) ? message : Buffer.from(message);
}
let maxPartitions = 0;
//find correct max partition count
if (typeof _partition !== "number") { //manual check to improve performance
maxPartitions = await this.getPartitionCountOfTopic(topicName);
if (maxPartitions === -1) {
throw new Error("defaultPartition set to 'auto', but was not able to resolve partition count for topic" +
topicName + ", please make sure the topic exists before starting the producer in auto mode.");
}
} else {
maxPartitions = this.defaultPartitionCount;
}
let partition = 0;
//find correct partition for this key
if (maxPartitions >= 2 && typeof _partition !== "number") { //manual check to improve performance
partition = this._getPartitionForKey(_partitionKey ? _partitionKey : key, maxPartitions);
}
//if _partition (manual) is set, it always overwrites a selected partition
partition = typeof _partition === "number" ? _partition : partition;
this.config.logger!.debug(JSON.stringify({
topicName,
partition,
key
}));
const producedAt = Date.now();
this._lastProcessed = producedAt;
this._totalSentMessages++;
const timestamp = producedAt.toString();
const acks = this.config && this.config.tconf && this.config.tconf["request.required.acks"] || 1;
const compression = (this.config.noptions)
? this.config.noptions["compression.codec"]
: CompressionTypes.None;
return new Promise((resolve, reject) => {
this.producer!.send({
topic: topicName,
acks,
compression,
messages: [{
key,
value: convertedMessage,
partition,
timestamp
}],
})
.then((metadata: RecordMetadata[] ) => {
resolve({
key,
partition,
offset: metadata[0].offset,
});
})
.catch((error) => {
reject(error);
});
});
}
/**
* @async
* produces a formatted message to a topic
* @param {string} topic - topic to produce to
* @param {string} identifier - identifier of message (is the key)
* @param {object} payload - object (part of message value)
* @param {number} partition - optional partition to produce to
* @param {number} version - optional version of the message value
* @param {string} partitionKey - optional key to evaluate partition for this message
* @returns {Promise.<object>}
*/
async buffer(
topic: string,
identifier: string,
payload: Record<string, unknown>,
partition: number | null = null,
version: number | null = null,
partitionKey: string | null = null
): Promise<MessageReturn> {
if (typeof identifier === "undefined") {
identifier = uuidv4();
}
if (typeof identifier !== "string") {
identifier = identifier + "";
}
if (typeof payload !== "object") {
throw new Error("expecting payload to be of type object.");
}
if (typeof payload.id === "undefined") {
payload.id = identifier;
}
if (version && typeof payload.version === "undefined") {
payload.version = version;
}
return await this.send(topic, JSON.stringify(payload), partition, identifier, partitionKey);
}
/**
* @async
* @private
* produces a specially formatted message to a topic
* @param {string} topic - topic to produce to
* @param {string} identifier - identifier of message (is the key)
* @param {object} _payload - object message value payload
* @param {number} version - optional version (default is 1)
* @param {*} _ -ignoreable, here for api compatibility
* @param {string} partitionKey - optional key to deterministcally detect partition
* @param {number} partition - optional partition (overwrites partitionKey)
* @param {string} messageType - optional messageType (for the formatted message value)
* @returns {Promise.<object>}
*/
async _sendBufferFormat(
topic: string,
identifier: string,
_payload: Record<string, unknown>,
version = 1,
_: null | number,
partitionKey: string | null = null,
partition: number | null = null,
messageType = ""
): Promise<MessageReturn> {
if (typeof identifier === "undefined") {
identifier = uuidv4();
}
if (typeof identifier !== "string") {
identifier = identifier + "";
}
if (typeof _payload !== "object") {
throw new Error("expecting payload to be of type object.");
}
if (typeof _payload.id === "undefined") {
_payload.id = identifier;
}
if (version && typeof _payload.version === "undefined") {
_payload.version = version;
}
const payload = {
payload: _payload,
key: identifier,
id: uuidv4(),
time: (new Date()).toISOString(),
type: topic + messageType
};
return await this.send(topic, JSON.stringify(payload), partition, identifier, partitionKey);
}
/**
* an alias for bufferFormatPublish()
* @alias bufferFormatPublish
*/
bufferFormat(
topic: string,
identifier: string,
payload: Record<string, unknown>,
version = 1,
compressionType = 0,
partitionKey: string | null = null
): Promise<MessageReturn> {
return this.bufferFormatPublish(topic, identifier, payload, version, compressionType, partitionKey);
}
/**
* produces a specially formatted message to a topic, with type "publish"
* @param {string} topic - topic to produce to
* @param {string} identifier - identifier of message (is the key)
* @param {object} _payload - object message value payload
* @param {number} version - optional version (default is 1)
* @param {*} _ -ignoreable, here for api compatibility
* @param {string} partitionKey - optional key to deterministcally detect partition
* @param {number} partition - optional partition (overwrites partitionKey)
* @returns {Promise.<object>}
*/
bufferFormatPublish(
topic: string,
identifier: string,
_payload: Record<string, unknown>,
version = 1,
_: null | number,
partitionKey: string | null = null,
partition: number | null = null
): Promise<MessageReturn> {
return this._sendBufferFormat(topic, identifier, _payload, version, _, partitionKey, partition, MESSAGE_TYPES.PUBLISH);
}
/**
* produces a specially formatted message to a topic, with type "update"
* @param {string} topic - topic to produce to
* @param {string} identifier - identifier of message (is the key)
* @param {object} _payload - object message value payload
* @param {number} version - optional version (default is 1)
* @param {*} _ -ignoreable, here for api compatibility
* @param {string} partitionKey - optional key to deterministcally detect partition
* @param {number} partition - optional partition (overwrites partitionKey)
* @returns {Promise.<object>}
*/
bufferFormatUpdate(
topic: string,
identifier: string,
_payload: Record<string, unknown>,
version = 1,
_: null | number,
partitionKey: string | null = null,
partition: number | null = null
): Promise<MessageReturn> {
return this._sendBufferFormat(topic, identifier, _payload, version, _, partitionKey, partition, MESSAGE_TYPES.UPDATE);
}
/**
* produces a specially formatted message to a topic, with type "unpublish"
* @param {string} topic - topic to produce to
* @param {string} identifier - identifier of message (is the key)
* @param {object} _payload - object message value payload
* @param {number} version - optional version (default is 1)
* @param {*} _ -ignoreable, here for api compatibility
* @param {string} partitionKey - optional key to deterministcally detect partition
* @param {number} partition - optional partition (overwrites partitionKey)
* @returns {Promise.<object>}
*/
bufferFormatUnpublish(
topic: string,
identifier: string,
_payload: Record<string, unknown>,
version = 1,
_: null | number,
partitionKey: string | null = null,
partition: number | null = null
): Promise<MessageReturn> {
return this._sendBufferFormat(topic, identifier, _payload, version, _, partitionKey, partition, MESSAGE_TYPES.UNPUBLISH);
}
/**
* produces a tombstone (null payload with -1 size) message
* on a key compacted topic/partition this will delete all occurances of the key
* @param {string} topic - name of the topic
* @param {string} key - key
* @param {number|null} _partition - optional partition
*/
tombstone(
topic: string,
key: string,
_partition: number | null = null
): Promise<MessageReturn> {
if (!key) {
return Promise.reject(new Error("Tombstone messages only work on a key compacted topic, please provide a key."));
}
return this.send(topic, null, _partition, key, null);
}
/**
* pauses production (sends will not be queued)
*/
pause(): void {
this.paused = true;
}
/**
* resumes production
*/
resume(): void {
this.paused = false;
}
/**
* returns producer statistics
* * @todo - update type for producer stats.
* @returns {object}
*/
getStats(): ProducerStats {
return {
totalPublished: this._totalSentMessages,
last: this._lastProcessed,
isPaused: this.paused,
totalErrors: this._errors
};
}
/**
* @deprecated
*/
refreshMetadata(): void {
throw new Error("refreshMetadata not implemented for nproducer.");
}
/**
* resolve the metadata information for a give topic
* will create topic if it doesnt exist
* @param {string} topic - name of the topic to query metadata for
* @param {number} timeout - optional, default is 2500
* @returns {Promise.<Metadata>}
*/
getTopicMetadata(topic: string): Promise<Metadata> {
return new Promise((resolve, reject) => {
if (!this.producer) {
return reject(new Error("You must call and await .connect() before trying to get metadata."));
}
const topics = (topic === "")
? []
: [topic];
this._adminClient.fetchTopicMetadata({
topics,
}).then((raw) => {
resolve(new Metadata(raw));
}).catch((e) => reject(e));
});
}
/**
* @alias getTopicMetadata
* @returns {Promise.<Metadata>}
*/
getMetadata(): Promise<Metadata> {
return this.getTopicMetadata("");
}
/**
* returns a list of available kafka topics on the connected brokers
*/
async getTopicList(): Promise<string[]> {
const metadata: Metadata = await this.getMetadata();
return metadata.asTopicList();
}
/**
* @async
* gets the partition count of the topic from the brokers metadata
* keeps a local cache to speed up future requests
* resolves to -1 if an error occures
* @param {string} topic - name of topic
* @returns {Promise.<number>}
*/
async getPartitionCountOfTopic(topic: string): Promise<number> {
if (!this.producer) {
throw new Error("You must call and await .connect() before trying to get metadata.");
}
//prevent long running leaks..
if (Object.keys(this._partitionCounts).length > MAX_PART_STORE_SIZE) {
this._partitionCounts = {};
}
const now = Date.now();
if (!this._partitionCounts[topic] || this._partitionCounts[topic].requested + MAX_PART_AGE_MS < now) {
let count = -1;
try {
const metadata = await this.getMetadata(); //prevent creation of topic, if it does not exist
count = metadata.getPartitionCountOfTopic(topic);
} catch (error) {
this.emit("error", new Error(`Failed to get metadata for topic ${topic}, because: ${error}.`));
return -1;
}
this._partitionCounts[topic] = {
requested: now,
count
};
return count;
}
return this._partitionCounts[topic].count;
}
/**
* gets the local partition count cache
* @returns {object}
*/
getStoredPartitionCounts(): Record<string, unknown> {
return this._partitionCounts;
}
/**
* @private
* resets internal values
*/
private _reset() {
this._lastProcessed = 0;
this._totalSentMessages = 0;
this.paused = false;
this._inClosing = false;
this._partitionCounts = {};
this._analytics = undefined;
this._errors = 0;
}
/**
* closes connection if open
* stops poll interval if open
*/
async close(): Promise<void> {
this.haltAnalytics();
if (this.producer) {
this._inClosing = true;
clearInterval(this._producerPollIntv);
try {
await Promise.all([
this.producer.disconnect(),
this._adminClient.disconnect(),
]);
} catch(error) {
// Do nothing, silently closing
}
//this.producer = null;
}
}
/**
* called in interval
* @private
*/
private _runAnalytics(): void {
if (!this._analytics) {
this._analytics = new ProducerAnalytics(this, this._analyticsOptions, this.config.logger as KafkaLogger);
}
this._analytics.run()
.then(res => this.emit("analytics", res))
.catch(error => this.emit("error", error));
}
/**
* returns the last computed analytics results
* @throws
* @returns {object}
*/
getAnalytics(): ProducerRunResult|null {
if (!this._analytics) {
this.emit("error", new Error("You have not enabled analytics on this consumer instance."));
return null;
}
return this._analytics.getLastResult();
}
/**
* runs a health check and returns object with status and message
* @returns {Promise.<Check>}
*/
checkHealth(): Promise<Check> {
return this._health.check();
}
} | the_stack |
import '@polymer/polymer/polymer-legacy';
import '@polymer/paper-button/paper-button';
import '@polymer/paper-checkbox/paper-checkbox';
import '@polymer/paper-dropdown-menu/paper-dropdown-menu';
import '@polymer/paper-input/paper-input';
import './cloud-install-styles';
import './outline-server-settings-styles';
import './outline-iconset';
import './outline-validated-input';
import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn';
import {html} from '@polymer/polymer/lib/utils/html-tag';
import {formatBytesParts} from '../data_formatting';
import {getCloudName, getCloudIcon} from './cloud-assets';
import {getShortName} from '../location_formatting';
export interface OutlineServerSettings extends Element {
setServerName(name: string): void;
}
Polymer({
_template: html`
<style include="cloud-install-styles"></style>
<style include="outline-server-settings-styles"></style>
<style>
.content {
flex-grow: 1;
}
.setting {
padding: 24px;
align-items: flex-start;
}
.setting:not(:first-child) {
margin-top: 8px;
}
.setting-icon,
img.setting-icon {
margin-right: 24px;
color: #fff;
opacity: 0.87;
filter: grayscale(100%);
}
.setting > div {
width: 100%;
}
.setting h3 {
margin: 0 0 16px 0;
padding: 0;
color: #fff;
font-size: 16px;
width: 100%;
}
.setting p {
margin-bottom: 12px;
width: 60%;
color: var(--medium-gray);
}
#experiments p {
width: 80%;
}
#experiments .sub-section p {
width: 100%;
}
.sub-section {
background: var(--border-color);
padding: 16px;
margin: 24px 0;
display: flex;
align-items: center;
border-radius: 2px;
}
.sub-section iron-icon {
margin-right: 16px;
}
.selection-container {
display: flex;
justify-content: space-between;
align-items: baseline;
}
.selection-container > .content {
flex: 4;
}
.selection-container > paper-dropdown-menu {
flex: 1;
}
.data-limits-input {
display: flex;
align-items: center;
}
.data-limits-input paper-input:not([readonly]) {
width: auto;
--paper-input-container: {
width: 120px;
}
}
.data-limits-disclaimer {
margin: 0 0 8px 0;
}
.data-limits-disclaimer p {
width: 100%;
}
.detail {
margin-top: 0px;
font-size: 12px;
}
paper-input:not([readonly]) {
width: 60%;
}
paper-dropdown-menu {
border: 1px solid var(--medium-gray);
border-radius: 4px;
max-width: 150px;
--paper-input-container: {
padding: 0 4px;
text-align: center;
}
--paper-input-container-input: {
color: var(--medium-gray);
font-size: 14px;
}
--paper-dropdown-menu-ripple: {
display: none;
}
--paper-input-container-underline: {
display: none;
}
--paper-input-container-underline-focus: {
display: none;
}
}
.data-limits-input paper-dropdown-menu {
border: none;
--paper-input-container: {
width: 72px;
}
}
paper-listbox paper-item {
font-size: 14px;
}
paper-listbox paper-item:hover {
cursor: pointer;
background-color: #eee;
}
#data-limits-container .selection-container p {
margin: 0 0 24px 0;
width: 80%;
}
#data-limits-container .selection-container span {
display: block;
margin-top: 6px;
}
paper-checkbox {
/* We want the ink to be the color we're going to, not coming from */
--paper-checkbox-checked-color: var(--primary-green);
--paper-checkbox-checked-ink-color: var(--dark-gray);
--paper-checkbox-unchecked-color: var(--light-gray);
--paper-checkbox-unchecked-ink-color: var(--primary-green);
}
.selection-container paper-checkbox {
margin-right: 4px;
}
</style>
<div class="container">
<div class="content">
<!-- Managed Server information -->
<div class="setting card-section" hidden\$="[[!cloudId]]">
<img class="setting-icon" src="[[_getCloudIcon(cloudId)]]">
<div>
<h3>[[_getCloudName(cloudId)]]</h3>
<paper-input readonly="" value="[[_getShortName(cloudLocation, localize)]]" label="[[localize('settings-server-location')]]" hidden\$="[[!cloudLocation]]" always-float-label="" maxlength="100"></paper-input>
<paper-input readonly="" value="[[serverMonthlyCost]]" label="[[localize('settings-server-cost')]]" hidden\$="[[!serverMonthlyCost]]" always-float-label="" maxlength="100"></paper-input>
<paper-input readonly="" value="[[serverMonthlyTransferLimit]]" label="[[localize('settings-transfer-limit')]]" hidden\$="[[!serverMonthlyTransferLimit]]" always-float-label="" maxlength="100"></paper-input>
</div>
</div>
<div class="setting card-section">
<iron-icon class="setting-icon" icon="outline-iconset:outline"></iron-icon>
<div>
<h3>[[localize('settings-server-info')]]</h3>
<!-- TODO: consider making this an outline-validated-input -->
<paper-input id="serverNameInput" class="server-name" value="{{serverName}}" label="[[localize('settings-server-name')]]" always-float-label="" maxlength="100" on-keydown="_handleNameInputKeyDown" on-blur="_handleNameInputBlur"></paper-input>
<p class="detail">[[localize('settings-server-rename')]]</p>
<outline-validated-input editable="[[isAccessKeyPortEditable]]" visible="[[serverPortForNewAccessKeys]]" label="[[localize('settings-access-key-port')]]" allowed-pattern="[0-9]{1,5}" max-length="5" value="[[serverPortForNewAccessKeys]]" client-side-validator="[[_validatePort]]" event="ChangePortForNewAccessKeysRequested" localize="[[localize]]"></outline-validated-input>
<outline-validated-input editable="[[isHostnameEditable]]" visible="[[serverHostname]]" label="[[localize('settings-server-hostname')]]" max-length="253" value="[[serverHostname]]" event="ChangeHostnameForAccessKeysRequested" localize="[[localize]]"></outline-validated-input>
<paper-input readonly="" value="[[serverManagementApiUrl]]" label="[[localize('settings-server-api-url')]]" hidden\$="[[!serverManagementApiUrl]]" always-float-label="" maxlength="100"></paper-input>
<paper-input readonly="" value="[[_formatDate(language, serverCreationDate)]]" label="[[localize('settings-server-creation')]]" hidden\$="[[!_formatDate(language, serverCreationDate)]]" always-float-label="" maxlength="100"></paper-input>
<paper-input readonly="" value="[[metricsId]]" label="[[localize('settings-server-id')]]" hidden\$="[[!metricsId]]" always-float-label="" maxlength="100"></paper-input>
<paper-input readonly="" value="[[serverVersion]]" label="[[localize('settings-server-version')]]" hidden\$="[[!serverVersion]]" always-float-label="" maxlength="100"></paper-input>
</div>
</div>
<!-- Data limits -->
<div class="setting card-section" hidden\$="[[!supportsDefaultDataLimit]]">
<iron-icon class="setting-icon" icon="icons:perm-data-setting"></iron-icon>
<div id="data-limits-container">
<div class="selection-container">
<div class="content">
<h3>[[localize('data-limits')]]</h3>
<p>[[localize('data-limits-description')]]</p>
</div>
<!-- NOTE: The dropdown is not automatically sized to the button's width:
https://github.com/PolymerElements/paper-dropdown-menu/issues/229 -->
<paper-dropdown-menu no-label-float="" horizontal-align="left">
<paper-listbox slot="dropdown-content" selected="{{_computeDataLimitsEnabledName(isDefaultDataLimitEnabled)}}" attr-for-selected="name" on-selected-changed="_defaultDataLimitEnabledChanged">
<paper-item name="enabled">[[localize('enabled')]]</paper-item>
<paper-item name="disabled">[[localize('disabled')]]</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
<div class="sub-section data-limits-disclaimer" hidden\$="[[!showFeatureMetricsDisclaimer]]">
<iron-icon icon="icons:error-outline"></iron-icon>
<p inner-h-t-m-l="[[localize('data-limits-disclaimer', 'openLink', '<a href=https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection>', 'closeLink', '</a>')]]"></p>
</div>
<div class="data-limits-input" hidden\$="[[!isDefaultDataLimitEnabled]]">
<paper-input id="defaultDataLimitInput" value="[[defaultDataLimit.value]]" label="[[localize('data-limit-per-key')]]" always-float-label="" allowed-pattern="[0-9]+" required="" auto-validate="" maxlength="9" on-keydown="_handleDefaultDataLimitInputKeyDown" on-blur="_requestSetDefaultDataLimit"></paper-input>
<paper-dropdown-menu no-label-float="">
<paper-listbox id="defaultDataLimitUnits" slot="dropdown-content" selected="[[defaultDataLimit.unit]]" attr-for-selected="name" on-selected-changed="_requestSetDefaultDataLimit">
<paper-item name="MB">[[_getInternationalizedUnit(1000000, language)]]</paper-item>
<paper-item name="GB">[[_getInternationalizedUnit(1000000000, language)]]</paper-item>
</paper-listbox>
</paper-dropdown-menu>
</div>
</div>
</div>
<!-- Experiments -->
<div id="experiments" class="setting card-section" hidden\$="[[!shouldShowExperiments]]">
<iron-icon class="setting-icon" icon="icons:build"></iron-icon>
<div>
<h3>[[localize('experiments')]]</h3>
<p>[[localize('experiments-description')]]</p>
<div class="sub-section">
<iron-icon icon="icons:error-outline"></iron-icon>
<p inner-h-t-m-l="[[localize('experiments-disclaimer', 'openLink', '<a href=https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection>', 'closeLink', '</a>')]]"></p>
</div>
</div>
</div>
<!-- Metrics controls -->
<div class="setting card-section">
<iron-icon class="setting-icon" icon="editor:insert-chart"></iron-icon>
<div>
<div class="selection-container">
<paper-checkbox checked="{{metricsEnabled}}" on-change="_metricsEnabledChanged"></paper-checkbox>
<h3>[[localize('settings-metrics-header')]]</h3>
</div>
<p inner-h-t-m-l="[[localize('metrics-description', 'openLink', '<a href=https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection>', 'closeLink', '</a>')]]"></p>
</div>
</div>
</div>
</div>
`,
is: 'outline-server-settings',
properties: {
serverName: String,
metricsEnabled: Boolean,
// Initialize to null so we can use the hidden attribute, which does not work well with
// undefined values.
metricsId: {type: String, value: null},
serverHostname: {type: String, value: null},
serverManagementApiUrl: {type: String, value: null},
serverPortForNewAccessKeys: {type: Number, value: null},
serverVersion: {type: String, value: null},
isAccessKeyPortEditable: {type: Boolean, value: false},
isDefaultDataLimitEnabled: {type: Boolean, notify: true},
defaultDataLimit: {type: Object, value: null}, // type: app.DisplayDataAmount
supportsDefaultDataLimit:
{type: Boolean, value: false}, // Whether the server supports default data limits.
showFeatureMetricsDisclaimer: {type: Boolean, value: false},
isHostnameEditable: {type: Boolean, value: true},
serverCreationDate: {type: Date, value: '1970-01-01T00:00:00.000Z'},
cloudLocation: {type: Object, value: null},
cloudId: {type: String, value: null},
serverMonthlyCost: {type: String, value: null},
serverMonthlyTransferLimit: {type: String, value: null},
language: {type: String, value: 'en'},
localize: {type: Function},
shouldShowExperiments: {type: Boolean, value: false},
},
setServerName(name: string) {
this.initialName = name;
this.name = name;
},
_handleNameInputKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.serverName = this.initialName;
this.$.serverNameInput.blur();
} else if (event.key === 'Enter') {
this.$.serverNameInput.blur();
}
},
_handleNameInputBlur(event: FocusEvent) {
const newName = this.serverName;
if (!newName) {
this.serverName = this.initialName;
return;
}
// Fire signal if name has changed.
if (newName !== this.initialName) {
this.fire('ServerRenameRequested', {newName});
}
},
_metricsEnabledChanged() {
const metricsSignal =
this.metricsEnabled ? 'EnableMetricsRequested' : 'DisableMetricsRequested';
this.fire(metricsSignal);
},
_defaultDataLimitEnabledChanged(e: CustomEvent) {
const wasDataLimitEnabled = this.isDefaultDataLimitEnabled;
const isDataLimitEnabled = e.detail.value === 'enabled';
if (isDataLimitEnabled === undefined || wasDataLimitEnabled === undefined) {
return;
} else if (isDataLimitEnabled === wasDataLimitEnabled) {
return;
}
this.isDefaultDataLimitEnabled = isDataLimitEnabled;
if (isDataLimitEnabled) {
this._requestSetDefaultDataLimit();
} else {
this.fire('RemoveDefaultDataLimitRequested');
}
},
_handleDefaultDataLimitInputKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
this.$.defaultDataLimitInput.value = this.defaultDataLimit.value;
this.$.defaultDataLimitInput.blur();
} else if (event.key === 'Enter') {
this.$.defaultDataLimitInput.blur();
}
},
_requestSetDefaultDataLimit() {
if (this.$.defaultDataLimitInput.invalid) {
return;
}
const value = Number(this.$.defaultDataLimitInput.value);
const unit = this.$.defaultDataLimitUnits.selected;
this.fire('SetDefaultDataLimitRequested', {limit: {value, unit}});
},
_computeDataLimitsEnabledName(isDefaultDataLimitEnabled: boolean) {
return isDefaultDataLimitEnabled ? 'enabled' : 'disabled';
},
_validatePort(value: string) {
const port = Number(value);
const valid = !Number.isNaN(port) && port >= 1 && port <= 65535 && Number.isInteger(port);
return valid ? '' : this.localize('error-keys-port-bad-input');
},
_getShortName: getShortName,
_getCloudIcon: getCloudIcon,
_getCloudName: getCloudName,
_getInternationalizedUnit(bytesAmount: number, language: string) {
return formatBytesParts(bytesAmount, language).unit;
},
_formatDate(language: string, date: Date) {
return date.toLocaleString(language, {year: 'numeric', month: 'long', day: 'numeric'});
}
}); | the_stack |
import { Meteor } from 'meteor/meteor'
import { check } from '../../../lib/check'
import { PeripheralDevice, PeripheralDeviceId, PeripheralDevices } from '../../../lib/collections/PeripheralDevices'
import { DBRundown, Rundowns } from '../../../lib/collections/Rundowns'
import { getCurrentTime, literal, waitForPromise } from '../../../lib/lib'
import { IngestRundown, IngestSegment, IngestPart, IngestPlaylist } from '@sofie-automation/blueprints-integration'
import { logger } from '../../../lib/logging'
import { Studio, StudioId } from '../../../lib/collections/Studios'
import { Segment, SegmentId, Segments } from '../../../lib/collections/Segments'
import {
RundownIngestDataCache,
LocalIngestRundown,
makeNewIngestSegment,
makeNewIngestPart,
makeNewIngestRundown,
} from './ingestCache'
import {
getSegmentId,
getStudioFromDevice,
canRundownBeUpdated,
canSegmentBeUpdated,
checkAccessAndGetPeripheralDevice,
getRundown,
} from './lib'
import { MethodContext } from '../../../lib/api/methods'
import { CommitIngestData, runIngestOperationWithCache, UpdateIngestRundownAction } from './lockFunction'
import { CacheForIngest } from './cache'
import { updateRundownFromIngestData, updateSegmentFromIngestData } from './generation'
import { removeRundownsFromDb } from '../rundownPlaylist'
import { RundownPlaylists } from '../../../lib/collections/RundownPlaylists'
export namespace RundownInput {
export function dataPlaylistGet(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
playlistExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataPlaylistGet', playlistExternalId)
check(playlistExternalId, String)
return getIngestPlaylist(peripheralDevice, playlistExternalId)
}
// Get info on the current rundowns from this device:
export function dataRundownList(context: MethodContext, deviceId: PeripheralDeviceId, deviceToken: string) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataRundownList')
return listIngestRundowns(peripheralDevice)
}
export function dataRundownGet(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataRundownGet', rundownExternalId)
check(rundownExternalId, String)
return getIngestRundown(peripheralDevice, rundownExternalId)
}
// Delete, Create & Update Rundown (and it's contents):
export function dataRundownDelete(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataRundownDelete', rundownExternalId)
check(rundownExternalId, String)
handleRemovedRundown(peripheralDevice, rundownExternalId)
}
export function dataRundownCreate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
ingestRundown: IngestRundown
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataRundownCreate', ingestRundown)
check(ingestRundown, Object)
handleUpdatedRundown(undefined, peripheralDevice, ingestRundown, true)
}
export function dataRundownUpdate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
ingestRundown: IngestRundown
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataRundownUpdate', ingestRundown)
check(ingestRundown, Object)
handleUpdatedRundown(undefined, peripheralDevice, ingestRundown, false)
}
export function dataSegmentGet(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
segmentExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataSegmentGet', rundownExternalId, segmentExternalId)
check(rundownExternalId, String)
check(segmentExternalId, String)
return getIngestSegment(peripheralDevice, rundownExternalId, segmentExternalId)
}
// Delete, Create & Update Segment (and it's contents):
export function dataSegmentDelete(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
segmentExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataSegmentDelete', rundownExternalId, segmentExternalId)
check(rundownExternalId, String)
check(segmentExternalId, String)
handleRemovedSegment(peripheralDevice, rundownExternalId, segmentExternalId)
}
export function dataSegmentCreate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
ingestSegment: IngestSegment
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataSegmentCreate', rundownExternalId, ingestSegment)
check(rundownExternalId, String)
check(ingestSegment, Object)
handleUpdatedSegment(peripheralDevice, rundownExternalId, ingestSegment, true)
}
export function dataSegmentUpdate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
ingestSegment: IngestSegment
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataSegmentUpdate', rundownExternalId, ingestSegment)
check(rundownExternalId, String)
check(ingestSegment, Object)
handleUpdatedSegment(peripheralDevice, rundownExternalId, ingestSegment, false)
}
export function dataSegmentRanksUpdate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
newRanks: { [segmentExternalId: string]: number }
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataSegmentRanksUpdate', rundownExternalId, Object.keys(newRanks))
check(rundownExternalId, String)
check(newRanks, Object)
handleUpdatedSegmentRanks(peripheralDevice, rundownExternalId, newRanks)
}
// Delete, Create & Update Part:
export function dataPartDelete(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
segmentExternalId: string,
partExternalId: string
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataPartDelete', rundownExternalId, segmentExternalId, partExternalId)
check(rundownExternalId, String)
check(segmentExternalId, String)
check(partExternalId, String)
handleRemovedPart(peripheralDevice, rundownExternalId, segmentExternalId, partExternalId)
}
export function dataPartCreate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
segmentExternalId: string,
ingestPart: IngestPart
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataPartCreate', rundownExternalId, segmentExternalId, ingestPart)
check(rundownExternalId, String)
check(segmentExternalId, String)
check(ingestPart, Object)
handleUpdatedPart(peripheralDevice, rundownExternalId, segmentExternalId, ingestPart)
}
export function dataPartUpdate(
context: MethodContext,
deviceId: PeripheralDeviceId,
deviceToken: string,
rundownExternalId: string,
segmentExternalId: string,
ingestPart: IngestPart
) {
const peripheralDevice = checkAccessAndGetPeripheralDevice(deviceId, deviceToken, context)
logger.info('dataPartUpdate', rundownExternalId, segmentExternalId, ingestPart)
check(rundownExternalId, String)
check(segmentExternalId, String)
check(ingestPart, Object)
handleUpdatedPart(peripheralDevice, rundownExternalId, segmentExternalId, ingestPart)
}
}
function getIngestPlaylist(peripheralDevice: PeripheralDevice, playlistExternalId: string): IngestPlaylist {
const rundowns = Rundowns.find({
peripheralDeviceId: peripheralDevice._id,
playlistExternalId,
}).fetch()
const ingestPlaylist: IngestPlaylist = literal<IngestPlaylist>({
externalId: playlistExternalId,
rundowns: [],
})
for (const rundown of rundowns) {
const ingestCache = waitForPromise(RundownIngestDataCache.create(rundown._id))
const ingestData = ingestCache.fetchRundown()
if (ingestData) {
ingestPlaylist.rundowns.push(ingestData)
}
}
return ingestPlaylist
}
function getIngestRundown(peripheralDevice: PeripheralDevice, rundownExternalId: string): IngestRundown {
const rundown = Rundowns.findOne({
peripheralDeviceId: peripheralDevice._id,
externalId: rundownExternalId,
})
if (!rundown) {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
const ingestCache = waitForPromise(RundownIngestDataCache.create(rundown._id))
const ingestData = ingestCache.fetchRundown()
if (!ingestData)
throw new Meteor.Error(404, `Rundown "${rundown._id}", (${rundownExternalId}) has no cached ingest data`)
return ingestData
}
function getIngestSegment(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
segmentExternalId: string
): IngestSegment {
const rundown = Rundowns.findOne({
peripheralDeviceId: peripheralDevice._id,
externalId: rundownExternalId,
})
if (!rundown) {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
const segment = Segments.findOne({
externalId: segmentExternalId,
rundownId: rundown._id,
})
if (!segment) {
throw new Meteor.Error(404, `Segment ${segmentExternalId} not found in rundown ${rundownExternalId}`)
}
const ingestCache = waitForPromise(RundownIngestDataCache.create(rundown._id))
const ingestData = ingestCache.fetchSegment(segment._id)
if (!ingestData)
throw new Meteor.Error(
404,
`Rundown "${rundown._id}", (${rundownExternalId}) has no cached segment "${segment._id}" ingest data`
)
return ingestData
}
function listIngestRundowns(peripheralDevice: PeripheralDevice): string[] {
const rundowns = Rundowns.find({
peripheralDeviceId: peripheralDevice._id,
}).fetch()
return rundowns.map((r) => r.externalId)
}
export function handleRemovedRundown(peripheralDevice: PeripheralDevice, rundownExternalId: string) {
const studio = getStudioFromDevice(peripheralDevice)
return handleRemovedRundownFromStudio(studio._id, rundownExternalId)
}
function handleRemovedRundownFromStudio(studioId: StudioId, rundownExternalId: string, forceDelete?: boolean) {
return runIngestOperationWithCache(
'handleRemovedRundown',
studioId,
rundownExternalId,
() => {
// Remove it
return UpdateIngestRundownAction.DELETE
},
async (cache) => {
const rundown = getRundown(cache)
return {
changedSegmentIds: [],
removedSegmentIds: [],
renamedSegments: new Map(),
removeRundown: forceDelete || canRundownBeUpdated(rundown, false),
showStyle: undefined,
blueprint: undefined,
}
}
)
}
export function handleRemovedRundownByRundown(rundown: DBRundown, forceDelete?: boolean) {
if (rundown.restoredFromSnapshotId) {
// It's from a snapshot, so should be removed directly, as that means it cannot run ingest operations
// Note: this bypasses activation checks, but that probably doesnt matter
waitForPromise(removeRundownsFromDb([rundown._id]))
// check if the playlist is now empty
const rundownCount = Rundowns.find({ playlistId: rundown.playlistId }).count()
if (rundownCount === 0) {
// A lazy approach, but good enough for snapshots
RundownPlaylists.remove(rundown.playlistId)
}
} else {
handleRemovedRundownFromStudio(rundown.studioId, rundown.externalId, forceDelete)
}
}
/** Handle an updated (or inserted) Rundown */
export function handleUpdatedRundown(
studio0: Studio | undefined,
peripheralDevice: PeripheralDevice | undefined,
newIngestRundown: IngestRundown,
isCreateAction: boolean
) {
const studioId = peripheralDevice?.studioId ?? studio0?._id
if ((!peripheralDevice && !studio0) || !studioId) {
throw new Meteor.Error(500, `A PeripheralDevice or Studio is required to update a rundown`)
}
if (peripheralDevice && studio0 && peripheralDevice.studioId !== studio0._id) {
throw new Meteor.Error(
500,
`PeripheralDevice "${peripheralDevice._id}" does not belong to studio "${studio0._id}"`
)
}
const rundownExternalId = newIngestRundown.externalId
return runIngestOperationWithCache(
'handleUpdatedRundown',
studioId,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown || isCreateAction) {
// We want to regenerate unmodified
return makeNewIngestRundown(newIngestRundown)
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache, ingestRundown) => {
if (!ingestRundown) throw new Meteor.Error(`regenerateRundown lost the IngestRundown...`)
return handleUpdatedRundownInner(cache, ingestRundown, isCreateAction, peripheralDevice)
}
)
}
export async function handleUpdatedRundownInner(
cache: CacheForIngest,
ingestRundown: LocalIngestRundown,
isCreateAction: boolean,
peripheralDevice?: PeripheralDevice // TODO - to cache?
): Promise<CommitIngestData | null> {
if (!canRundownBeUpdated(cache.Rundown.doc, isCreateAction)) return null
logger.info(`${cache.Rundown.doc ? 'Updating' : 'Adding'} rundown ${cache.RundownId}`)
return updateRundownFromIngestData(cache, ingestRundown, peripheralDevice)
}
export function regenerateRundown(
studio: Studio,
rundownExternalId: string,
peripheralDevice0: PeripheralDevice | undefined
) {
return runIngestOperationWithCache(
'regenerateRundown',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
// We want to regenerate unmodified
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache, ingestRundown) => {
// If the rundown is orphaned, then we can't regenerate as there wont be any data to use!
if (!ingestRundown || !canRundownBeUpdated(cache.Rundown.doc, false)) return null
// Try and find the stored peripheralDevice
const peripheralDevice =
peripheralDevice0 ??
(cache.Rundown.doc?.peripheralDeviceId
? PeripheralDevices.findOne({
_id: cache.Rundown.doc.peripheralDeviceId,
studioId: cache.Studio.doc._id,
})
: undefined)
return updateRundownFromIngestData(cache, ingestRundown, peripheralDevice)
}
)
}
export function handleRemovedSegment(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
segmentExternalId: string
) {
const studio = getStudioFromDevice(peripheralDevice)
return runIngestOperationWithCache(
'handleRemovedSegment',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
const oldSegmentsLength = ingestRundown.segments.length
ingestRundown.segments = ingestRundown.segments.filter((s) => s.externalId !== segmentExternalId)
ingestRundown.modified = getCurrentTime()
if (ingestRundown.segments.length === oldSegmentsLength) {
throw new Meteor.Error(
404,
`Rundown "${rundownExternalId}" does not have a Segment "${segmentExternalId}" to remove`
)
}
// We modify in-place
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache) => {
const rundown = getRundown(cache)
const segmentId = getSegmentId(rundown._id, segmentExternalId)
const segment = cache.Segments.findOne(segmentId)
if (!canSegmentBeUpdated(rundown, segment, false)) {
// segment has already been deleted
return null
} else {
return {
changedSegmentIds: [],
removedSegmentIds: [segmentId],
renamedSegments: new Map(),
removeRundown: false,
showStyle: undefined,
blueprint: undefined,
}
}
}
)
}
export function handleUpdatedSegment(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
newIngestSegment: IngestSegment,
isCreateAction: boolean
) {
const studio = getStudioFromDevice(peripheralDevice)
const segmentExternalId = newIngestSegment.externalId
return runIngestOperationWithCache(
'handleUpdatedSegment',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
ingestRundown.segments = ingestRundown.segments.filter((s) => s.externalId !== segmentExternalId)
ingestRundown.segments.push(makeNewIngestSegment(newIngestSegment))
ingestRundown.modified = getCurrentTime()
// We modify in-place
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache, ingestRundown) => {
const ingestSegment = ingestRundown?.segments?.find((s) => s.externalId === segmentExternalId)
if (!ingestSegment) throw new Meteor.Error(500, `IngestSegment "${segmentExternalId}" is missing!`)
return updateSegmentFromIngestData(cache, ingestSegment, isCreateAction)
}
)
}
export function handleUpdatedSegmentRanks(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
newRanks: { [segmentExternalId: string]: number }
) {
const studio = getStudioFromDevice(peripheralDevice)
return runIngestOperationWithCache(
'handleUpdatedSegmentRanks',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
// Update ranks on ingest data
for (const segment of ingestRundown.segments) {
segment.rank = newRanks[segment.externalId] ?? segment.rank
}
// We modify in-place
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache) => {
const changedSegmentIds: SegmentId[] = []
for (const [externalId, rank] of Object.entries(newRanks)) {
const segmentId = getSegmentId(cache.RundownId, externalId)
const changed = cache.Segments.update(segmentId, {
$set: {
_rank: rank,
},
})
if (changed.length === 0) {
logger.warn(`Failed to update rank of segment "${externalId}" (${rundownExternalId})`)
} else {
changedSegmentIds.push(segmentId)
}
}
return {
changedSegmentIds,
removedSegmentIds: [],
renamedSegments: new Map(),
removeRundown: false,
showStyle: undefined,
blueprint: undefined,
}
}
)
}
export function handleRemovedPart(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
segmentExternalId: string,
partExternalId: string
) {
const studio = getStudioFromDevice(peripheralDevice)
return runIngestOperationWithCache(
'handleRemovedPart',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
const ingestSegment = ingestRundown.segments.find((s) => s.externalId === segmentExternalId)
if (!ingestSegment) {
throw new Meteor.Error(
404,
`Rundown "${rundownExternalId}" does not have a Segment "${segmentExternalId}" to update`
)
}
ingestSegment.parts = ingestSegment.parts.filter((p) => p.externalId !== partExternalId)
ingestSegment.modified = getCurrentTime()
// We modify in-place
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache, ingestRundown) => {
const ingestSegment = ingestRundown?.segments?.find((s) => s.externalId === segmentExternalId)
if (!ingestSegment) throw new Meteor.Error(500, `IngestSegment "${segmentExternalId}" is missing!`)
return updateSegmentFromIngestData(cache, ingestSegment, false)
}
)
}
export function handleUpdatedPart(
peripheralDevice: PeripheralDevice,
rundownExternalId: string,
segmentExternalId: string,
ingestPart: IngestPart
) {
const studio = getStudioFromDevice(peripheralDevice)
return runIngestOperationWithCache(
'handleUpdatedPart',
studio._id,
rundownExternalId,
(ingestRundown) => {
if (ingestRundown) {
const ingestSegment = ingestRundown.segments.find((s) => s.externalId === segmentExternalId)
if (!ingestSegment) {
throw new Meteor.Error(
404,
`Rundown "${rundownExternalId}" does not have a Segment "${segmentExternalId}" to update`
)
}
ingestSegment.parts = ingestSegment.parts.filter((p) => p.externalId !== ingestPart.externalId)
ingestSegment.parts.push(makeNewIngestPart(ingestPart))
ingestSegment.modified = getCurrentTime()
// We modify in-place
return ingestRundown
} else {
throw new Meteor.Error(404, `Rundown "${rundownExternalId}" not found`)
}
},
async (cache, ingestRundown) => {
const ingestSegment = ingestRundown?.segments?.find((s) => s.externalId === segmentExternalId)
if (!ingestSegment) throw new Meteor.Error(500, `IngestSegment "${segmentExternalId}" is missing!`)
return updateSegmentFromIngestData(cache, ingestSegment, false)
}
)
} | the_stack |
import { strict as assert } from "assert";
import { IChannelFactory } from "@fluidframework/datastore-definitions";
import {
MockFluidDataStoreRuntime,
MockContainerRuntimeFactory,
MockContainerRuntimeFactoryForReconnection,
MockContainerRuntimeForReconnection,
MockSharedObjectServices,
MockStorage,
} from "@fluidframework/test-runtime-utils";
import { ISharedCounter, SharedCounter } from "..";
describe("SharedCounter", () => {
let testCounter: ISharedCounter;
let dataStoreRuntime: MockFluidDataStoreRuntime;
let factory: IChannelFactory;
beforeEach(async () => {
dataStoreRuntime = new MockFluidDataStoreRuntime();
factory = SharedCounter.getFactory();
testCounter = factory.create(dataStoreRuntime, "counter") as ISharedCounter;
});
describe("SharedCounter in local state", () => {
describe("constructor", () => {
it("Can create a counter with default value", () => {
assert.ok(testCounter, "Count not create the SharedCounter");
assert.equal(testCounter.value, 0, "The defaul value is incorrect");
});
});
describe("increment", () => {
it("Can increment a counter with positive and negative values", () => {
testCounter.increment(20);
assert.equal(testCounter.value, 20, "Could not increment with positive value");
testCounter.increment(-30);
assert.equal(testCounter.value, -10, "Could not increment with negative value");
});
it("Fires a listener callback after increment", () => {
let fired1 = false;
let fired2 = false;
testCounter.on("incremented", (incrementAmount: number, newValue: number) => {
if (!fired1) {
fired1 = true;
assert.equal(incrementAmount, 10, "The increment amount in the first event is incorrect");
assert.equal(newValue, 10, "The new value in the first event is incorrect");
} else if (!fired2) {
fired2 = true;
assert.equal(incrementAmount, -3, "The increment amount in the second event is incorrect");
assert.equal(newValue, 7, "The new value in the second event is incorrect");
} else {
assert.fail("incremented event fired too many times");
}
});
testCounter.increment(10);
testCounter.increment(-3);
assert.ok(fired1, "The event for first increment was not fired");
assert.ok(fired2, "The event for second increment was not fired");
});
});
describe("snapshot / load", () => {
it("can load a SharedCounter from snapshot", async () => {
testCounter.increment(20);
testCounter.increment(-10);
// Load a new SharedCounter from the snapshot of the first one.
const services = MockSharedObjectServices.createFromSummary(testCounter.summarize().summary);
const testCounter2 = factory.create(dataStoreRuntime, "counter2") as SharedCounter;
await testCounter2.load(services);
// Verify that the new SharedCounter has the correct value.
assert.equal(testCounter.value, 10, "The loaded SharedCounter does not have the correct value");
});
});
});
describe("SharedCounter in connected state with a remote SharedCounter", () => {
let testCounter2: ISharedCounter;
let containerRuntimeFactory: MockContainerRuntimeFactory;
beforeEach(() => {
containerRuntimeFactory = new MockContainerRuntimeFactory();
// Connect the first SharedCounter.
dataStoreRuntime.local = false;
const containerRuntime1 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime);
const services1 = {
deltaConnection: containerRuntime1.createDeltaConnection(),
objectStorage: new MockStorage(),
};
testCounter.connect(services1);
// Create and connect a second SharedCounter.
const dataStoreRuntime2 = new MockFluidDataStoreRuntime();
const containerRuntime2 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime2);
const services2 = {
deltaConnection: containerRuntime2.createDeltaConnection(),
objectStorage: new MockStorage(),
};
testCounter2 = factory.create(dataStoreRuntime, "counter2") as SharedCounter;
testCounter2.connect(services2);
});
describe("increment", () => {
it("Can increment a counter with positive and negative values", () => {
testCounter.increment(20);
containerRuntimeFactory.processAllMessages();
assert.equal(testCounter.value, 20, "Could not increment with positive value");
assert.equal(testCounter2.value, 20, "Could not increment with positive value");
testCounter.increment(-30);
containerRuntimeFactory.processAllMessages();
assert.equal(testCounter.value, -10, "Could not increment with negative value");
assert.equal(testCounter2.value, -10, "Could not increment with negative value");
});
it("Fires a listener callback after increment", () => {
let fired1 = false;
let fired2 = false;
testCounter2.on("incremented", (incrementAmount: number, newValue: number) => {
if (!fired1) {
fired1 = true;
assert.equal(incrementAmount, 10, "The increment amount in the first event is incorrect");
assert.equal(newValue, 10, "The new value in the first event is incorrect");
} else if (!fired2) {
fired2 = true;
assert.equal(incrementAmount, -3, "The increment amount in the second event is incorrect");
assert.equal(newValue, 7, "The new value in the second event is incorrect");
} else {
assert.fail("incremented event fired too many times");
}
});
testCounter.increment(10);
testCounter.increment(-3);
containerRuntimeFactory.processAllMessages();
assert.ok(fired1, "The event for first increment was not fired");
assert.ok(fired2, "The event for second increment was not fired");
});
});
});
describe("SharedCounter reconnection flow", () => {
let containerRuntimeFactory: MockContainerRuntimeFactoryForReconnection;
let containerRuntime1: MockContainerRuntimeForReconnection;
let containerRuntime2: MockContainerRuntimeForReconnection;
let testCounter2: ISharedCounter;
beforeEach(() => {
containerRuntimeFactory = new MockContainerRuntimeFactoryForReconnection();
// Connect the first SharedCounter.
dataStoreRuntime.local = false;
containerRuntime1 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime);
const services1 = {
deltaConnection: containerRuntime1.createDeltaConnection(),
objectStorage: new MockStorage(),
};
testCounter.connect(services1);
// Create and connect a second SharedCounter.
const dataStoreRuntime2 = new MockFluidDataStoreRuntime();
containerRuntime2 = containerRuntimeFactory.createContainerRuntime(dataStoreRuntime2);
const services2 = {
deltaConnection: containerRuntime2.createDeltaConnection(),
objectStorage: new MockStorage(),
};
testCounter2 = factory.create(dataStoreRuntime, "counter2") as SharedCounter;
testCounter2.connect(services2);
});
it("can resend unacked ops on reconnection", async () => {
// Increment the first SharedCounter.
testCounter.increment(20);
// Disconnect and reconnect the first client.
containerRuntime1.connected = false;
containerRuntime1.connected = true;
// Process the messages.
containerRuntimeFactory.processAllMessages();
// Verify that the value is incremented in both the clients.
assert.equal(testCounter.value, 20, "Value not incremented in first client");
assert.equal(testCounter2.value, 20, "Value not incremented in second client");
// Increment the second SharedCounter.
testCounter.increment(-40);
// Disconnect and reconnect the second client.
containerRuntime2.connected = false;
containerRuntime2.connected = true;
// Process the messages.
containerRuntimeFactory.processAllMessages();
// Verify that the value is incremented in both the clients.
assert.equal(testCounter.value, -20, "Value not incremented in first client");
assert.equal(testCounter2.value, -20, "Value not incremented in second client");
});
it("can store ops in disconnected state and resend them on reconnection", async () => {
// Disconnect the first client.
containerRuntime1.connected = false;
// Increment the first SharedCounter.
testCounter.increment(20);
// Reconnect the first client.
containerRuntime1.connected = true;
// Process the messages.
containerRuntimeFactory.processAllMessages();
// Verify that the value is incremented in both the clients.
assert.equal(testCounter.value, 20, "Value not incremented in first client");
assert.equal(testCounter2.value, 20, "Value not incremented in second client");
// Disconnect the second client.
containerRuntime2.connected = false;
// Increment the second SharedCounter.
testCounter.increment(-40);
// Reconnect the second client.
containerRuntime2.connected = true;
// Process the messages.
containerRuntimeFactory.processAllMessages();
// Verify that the value is incremented in both the clients.
assert.equal(testCounter.value, -20, "Value not incremented in first client");
assert.equal(testCounter2.value, -20, "Value not incremented in second client");
});
});
}); | the_stack |
import {
GaxiosError,
GaxiosOptions,
GaxiosPromise,
GaxiosResponse,
} from 'gaxios';
import * as stream from 'stream';
import {BodyResponseCallback} from '../transporters';
import {Credentials} from './credentials';
import {AuthClient} from './authclient';
import {GetAccessTokenResponse, Headers, RefreshOptions} from './oauth2client';
import * as sts from './stscredentials';
/**
* The required token exchange grant_type: rfc8693#section-2.1
*/
const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange';
/**
* The requested token exchange requested_token_type: rfc8693#section-2.1
*/
const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
/**
* The requested token exchange subject_token_type: rfc8693#section-2.1
*/
const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
/** The STS access token exchange end point. */
const STS_ACCESS_TOKEN_URL = 'https://sts.googleapis.com/v1/token';
/**
* The maximum number of access boundary rules a Credential Access Boundary
* can contain.
*/
export const MAX_ACCESS_BOUNDARY_RULES_COUNT = 10;
/**
* Offset to take into account network delays and server clock skews.
*/
export const EXPIRATION_TIME_OFFSET = 5 * 60 * 1000;
/**
* Internal interface for tracking the access token expiration time.
*/
interface CredentialsWithResponse extends Credentials {
res?: GaxiosResponse | null;
}
/**
* Internal interface for tracking and returning the Downscoped access token
* expiration time in epoch time (seconds).
*/
interface DownscopedAccessTokenResponse extends GetAccessTokenResponse {
expirationTime?: number | null;
}
/**
* Defines an upper bound of permissions available for a GCP credential.
*/
export interface CredentialAccessBoundary {
accessBoundary: {
accessBoundaryRules: AccessBoundaryRule[];
};
}
/** Defines an upper bound of permissions on a particular resource. */
interface AccessBoundaryRule {
availablePermissions: string[];
availableResource: string;
availabilityCondition?: AvailabilityCondition;
}
/**
* An optional condition that can be used as part of a
* CredentialAccessBoundary to further restrict permissions.
*/
interface AvailabilityCondition {
expression: string;
title?: string;
description?: string;
}
/**
* Defines a set of Google credentials that are downscoped from an existing set
* of Google OAuth2 credentials. This is useful to restrict the Identity and
* Access Management (IAM) permissions that a short-lived credential can use.
* The common pattern of usage is to have a token broker with elevated access
* generate these downscoped credentials from higher access source credentials
* and pass the downscoped short-lived access tokens to a token consumer via
* some secure authenticated channel for limited access to Google Cloud Storage
* resources.
*/
export class DownscopedClient extends AuthClient {
private cachedDownscopedAccessToken: CredentialsWithResponse | null;
private readonly stsCredential: sts.StsCredentials;
public readonly eagerRefreshThresholdMillis: number;
public readonly forceRefreshOnFailure: boolean;
/**
* Instantiates a downscoped client object using the provided source
* AuthClient and credential access boundary rules.
* To downscope permissions of a source AuthClient, a Credential Access
* Boundary that specifies which resources the new credential can access, as
* well as an upper bound on the permissions that are available on each
* resource, has to be defined. A downscoped client can then be instantiated
* using the source AuthClient and the Credential Access Boundary.
* @param authClient The source AuthClient to be downscoped based on the
* provided Credential Access Boundary rules.
* @param credentialAccessBoundary The Credential Access Boundary which
* contains a list of access boundary rules. Each rule contains information
* on the resource that the rule applies to, the upper bound of the
* permissions that are available on that resource and an optional
* condition to further restrict permissions.
* @param additionalOptions Optional additional behavior customization
* options. These currently customize expiration threshold time and
* whether to retry on 401/403 API request errors.
* @param quotaProjectId Optional quota project id for setting up in the
* x-goog-user-project header.
*/
constructor(
private readonly authClient: AuthClient,
private readonly credentialAccessBoundary: CredentialAccessBoundary,
additionalOptions?: RefreshOptions,
quotaProjectId?: string
) {
super();
// Check 1-10 Access Boundary Rules are defined within Credential Access
// Boundary.
if (
credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0
) {
throw new Error('At least one access boundary rule needs to be defined.');
} else if (
credentialAccessBoundary.accessBoundary.accessBoundaryRules.length >
MAX_ACCESS_BOUNDARY_RULES_COUNT
) {
throw new Error(
'The provided access boundary has more than ' +
`${MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`
);
}
// Check at least one permission should be defined in each Access Boundary
// Rule.
for (const rule of credentialAccessBoundary.accessBoundary
.accessBoundaryRules) {
if (rule.availablePermissions.length === 0) {
throw new Error(
'At least one permission should be defined in access boundary rules.'
);
}
}
this.stsCredential = new sts.StsCredentials(STS_ACCESS_TOKEN_URL);
this.cachedDownscopedAccessToken = null;
// As threshold could be zero,
// eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the
// zero value.
if (typeof additionalOptions?.eagerRefreshThresholdMillis !== 'number') {
this.eagerRefreshThresholdMillis = EXPIRATION_TIME_OFFSET;
} else {
this.eagerRefreshThresholdMillis = additionalOptions!
.eagerRefreshThresholdMillis as number;
}
this.forceRefreshOnFailure = !!additionalOptions?.forceRefreshOnFailure;
this.quotaProjectId = quotaProjectId;
}
/**
* Provides a mechanism to inject Downscoped access tokens directly.
* The expiry_date field is required to facilitate determination of the token
* expiration which would make it easier for the token consumer to handle.
* @param credentials The Credentials object to set on the current client.
*/
setCredentials(credentials: Credentials) {
if (!credentials.expiry_date) {
throw new Error(
'The access token expiry_date field is missing in the provided ' +
'credentials.'
);
}
super.setCredentials(credentials);
this.cachedDownscopedAccessToken = credentials;
}
async getAccessToken(): Promise<DownscopedAccessTokenResponse> {
// If the cached access token is unavailable or expired, force refresh.
// The Downscoped access token will be returned in
// DownscopedAccessTokenResponse format.
if (
!this.cachedDownscopedAccessToken ||
this.isExpired(this.cachedDownscopedAccessToken)
) {
await this.refreshAccessTokenAsync();
}
// Return Downscoped access token in DownscopedAccessTokenResponse format.
return {
token: this.cachedDownscopedAccessToken!.access_token,
expirationTime: this.cachedDownscopedAccessToken!.expiry_date,
res: this.cachedDownscopedAccessToken!.res,
};
}
/**
* The main authentication interface. It takes an optional url which when
* present is the endpoint being accessed, and returns a Promise which
* resolves with authorization header fields.
*
* The result has the form:
* { Authorization: 'Bearer <access_token_value>' }
*/
async getRequestHeaders(): Promise<Headers> {
const accessTokenResponse = await this.getAccessToken();
const headers: Headers = {
Authorization: `Bearer ${accessTokenResponse.token}`,
};
return this.addSharedMetadataHeaders(headers);
}
/**
* Provides a request implementation with OAuth 2.0 flow. In cases of
* HTTP 401 and 403 responses, it automatically asks for a new access token
* and replays the unsuccessful request.
* @param opts Request options.
* @param callback callback.
* @return A promise that resolves with the HTTP response when no callback
* is provided.
*/
request<T>(opts: GaxiosOptions): GaxiosPromise<T>;
request<T>(opts: GaxiosOptions, callback: BodyResponseCallback<T>): void;
request<T>(
opts: GaxiosOptions,
callback?: BodyResponseCallback<T>
): GaxiosPromise<T> | void {
if (callback) {
this.requestAsync<T>(opts).then(
r => callback(null, r),
e => {
return callback(e, e.response);
}
);
} else {
return this.requestAsync<T>(opts);
}
}
/**
* Authenticates the provided HTTP request, processes it and resolves with the
* returned response.
* @param opts The HTTP request options.
* @param retry Whether the current attempt is a retry after a failed attempt.
* @return A promise that resolves with the successful response.
*/
protected async requestAsync<T>(
opts: GaxiosOptions,
retry = false
): Promise<GaxiosResponse<T>> {
let response: GaxiosResponse;
try {
const requestHeaders = await this.getRequestHeaders();
opts.headers = opts.headers || {};
if (requestHeaders && requestHeaders['x-goog-user-project']) {
opts.headers['x-goog-user-project'] =
requestHeaders['x-goog-user-project'];
}
if (requestHeaders && requestHeaders.Authorization) {
opts.headers.Authorization = requestHeaders.Authorization;
}
response = await this.transporter.request<T>(opts);
} catch (e) {
const res = (e as GaxiosError).response;
if (res) {
const statusCode = res.status;
// Retry the request for metadata if the following criteria are true:
// - We haven't already retried. It only makes sense to retry once.
// - The response was a 401 or a 403
// - The request didn't send a readableStream
// - forceRefreshOnFailure is true
const isReadableStream = res.config.data instanceof stream.Readable;
const isAuthErr = statusCode === 401 || statusCode === 403;
if (
!retry &&
isAuthErr &&
!isReadableStream &&
this.forceRefreshOnFailure
) {
await this.refreshAccessTokenAsync();
return await this.requestAsync<T>(opts, true);
}
}
throw e;
}
return response;
}
/**
* Forces token refresh, even if unexpired tokens are currently cached.
* GCP access tokens are retrieved from authclient object/source credential.
* Then GCP access tokens are exchanged for downscoped access tokens via the
* token exchange endpoint.
* @return A promise that resolves with the fresh downscoped access token.
*/
protected async refreshAccessTokenAsync(): Promise<CredentialsWithResponse> {
// Retrieve GCP access token from source credential.
const subjectToken = (await this.authClient.getAccessToken()).token;
// Construct the STS credentials options.
const stsCredentialsOptions: sts.StsCredentialsOptions = {
grantType: STS_GRANT_TYPE,
requestedTokenType: STS_REQUEST_TOKEN_TYPE,
subjectToken: subjectToken as string,
subjectTokenType: STS_SUBJECT_TOKEN_TYPE,
};
// Exchange the source AuthClient access token for a Downscoped access
// token.
const stsResponse = await this.stsCredential.exchangeToken(
stsCredentialsOptions,
undefined,
this.credentialAccessBoundary
);
/**
* The STS endpoint will only return the expiration time for the downscoped
* access token if the original access token represents a service account.
* The downscoped token's expiration time will always match the source
* credential expiration. When no expires_in is returned, we can copy the
* source credential's expiration time.
*/
const sourceCredExpireDate =
this.authClient.credentials?.expiry_date || null;
const expiryDate = stsResponse.expires_in
? new Date().getTime() + stsResponse.expires_in * 1000
: sourceCredExpireDate;
// Save response in cached access token.
this.cachedDownscopedAccessToken = {
access_token: stsResponse.access_token,
expiry_date: expiryDate,
res: stsResponse.res,
};
// Save credentials.
this.credentials = {};
Object.assign(this.credentials, this.cachedDownscopedAccessToken);
delete (this.credentials as CredentialsWithResponse).res;
// Trigger tokens event to notify external listeners.
this.emit('tokens', {
refresh_token: null,
expiry_date: this.cachedDownscopedAccessToken!.expiry_date,
access_token: this.cachedDownscopedAccessToken!.access_token,
token_type: 'Bearer',
id_token: null,
});
// Return the cached access token.
return this.cachedDownscopedAccessToken;
}
/**
* Returns whether the provided credentials are expired or not.
* If there is no expiry time, assumes the token is not expired or expiring.
* @param downscopedAccessToken The credentials to check for expiration.
* @return Whether the credentials are expired or not.
*/
private isExpired(downscopedAccessToken: Credentials): boolean {
const now = new Date().getTime();
return downscopedAccessToken.expiry_date
? now >=
downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis
: false;
}
} | the_stack |
import { DevToolsMonitor } from 'background/dev-tools-monitor';
import { TabContextManager } from 'background/tab-context-manager';
import { BrowserAdapter } from 'common/browser-adapters/browser-adapter';
import { IndexedDBAPI } from 'common/indexedDB/indexedDB';
import { Messages } from 'common/messages';
import {
DelayCreator,
PromiseFactory,
TimeoutCreator,
TimeoutError,
} from 'common/promises/promise-factory';
import { isEqual, max } from 'lodash';
import { flushSettledPromises } from 'tests/common/flush-settled-promises';
import { IMock, It, Mock, MockBehavior, Times } from 'typemoq';
import { DictionaryNumberTo } from 'types/common-types';
class TestDevToolsMonitor extends DevToolsMonitor {
public activeDevtoolTabIds: number[];
public async testPollLoop(): Promise<void> {
await super.monitorActiveDevtools();
}
}
describe(DevToolsMonitor, () => {
const messageTimeout = 10;
const pollInterval = 20;
const tabId = 1;
const anotherTabId = 10;
const messageSuccessResponse = { isActive: true };
const mockTimeoutResponse = { isTimeout: true };
let persistData: boolean;
let browserAdapterMock: IMock<BrowserAdapter>;
let timeoutMock: IMock<TimeoutCreator>;
let delayMock: IMock<DelayCreator>;
let promiseFactory: PromiseFactory;
let tabContextManagerMock: IMock<TabContextManager>;
let idbInstanceMock: IMock<IndexedDBAPI>;
let testSubject: TestDevToolsMonitor;
beforeEach(() => {
browserAdapterMock = Mock.ofType<BrowserAdapter>();
timeoutMock = Mock.ofType<TimeoutCreator>();
delayMock = Mock.ofType<DelayCreator>();
promiseFactory = {
timeout: timeoutMock.object,
delay: delayMock.object,
} as PromiseFactory;
tabContextManagerMock = Mock.ofType<TabContextManager>();
idbInstanceMock = Mock.ofType<IndexedDBAPI>(null, MockBehavior.Strict);
});
afterEach(() => {
browserAdapterMock.verifyAll();
timeoutMock.verifyAll();
delayMock.verifyAll();
tabContextManagerMock.verifyAll();
idbInstanceMock.verifyAll();
});
describe.each([true, false])('With persistData=%s', persist => {
beforeEach(() => {
persistData = persist;
testSubject = new TestDevToolsMonitor(
browserAdapterMock.object,
promiseFactory,
[],
tabContextManagerMock.object,
idbInstanceMock.object,
persistData,
messageTimeout,
pollInterval,
);
});
it('initialize() does nothing if activeDevtoolTabIds is empty', async () => {
timeoutMock.setup(t => t(It.isAny(), It.isAny())).verifiable(Times.never());
delayMock.setup(d => d(It.isAny(), It.isAny())).verifiable(Times.never());
browserAdapterMock
.setup(b => b.sendRuntimeMessage(It.isAny()))
.verifiable(Times.never());
testSubject.initialize();
await flushSettledPromises();
});
it('initialize() starts monitoring if activeDevtoolTabIds is not empty', async () => {
testSubject.activeDevtoolTabIds = [tabId, anotherTabId];
const tabPollCounts: DictionaryNumberTo<number> = {};
tabPollCounts[tabId] = 1;
tabPollCounts[anotherTabId] = 1;
setupDevtoolClosed(tabId);
setupDevtoolClosed(anotherTabId);
setupPollLoop(tabPollCounts);
testSubject.initialize();
await flushSettledPromises();
});
it.each([1, 3])(
'startMonitoringDevtool starts poll loop and run %s times when first devtool tab id is added',
async pollCount => {
const tabPollCounts: DictionaryNumberTo<number> = {};
tabPollCounts[tabId] = pollCount;
setupAddTab(tabId);
setupDevtoolClosed(tabId);
setupPollLoop(tabPollCounts);
await testSubject.startMonitoringDevtool(tabId);
await flushSettledPromises();
},
);
it('Polls two devtool tabs until both have closed', async () => {
testSubject.activeDevtoolTabIds = [tabId, anotherTabId];
const tabPollCounts: DictionaryNumberTo<number> = {};
tabPollCounts[tabId] = 2;
tabPollCounts[anotherTabId] = 4;
setupDevtoolClosed(tabId);
setupDevtoolClosed(anotherTabId);
setupPollLoop(tabPollCounts);
await testSubject.testPollLoop();
});
it('Add a devtool tab while monitor loop is running asynchronously', async () => {
let firstIteration = true;
let stopLoop = false;
setupDelayCreator(Times.atLeastOnce());
setupTimeoutCreator(Times.atLeastOnce());
browserAdapterMock
.setup(b => b.sendRuntimeMessage(It.isAny()))
.returns(async message => {
// During the first loop, add another tabId to monitor
if (firstIteration) {
firstIteration = false;
await testSubject.startMonitoringDevtool(anotherTabId);
}
// stop the loop on the next iteration after the second tab has been messaged
if (!stopLoop && message.tabId === anotherTabId) {
stopLoop = true;
} else if (stopLoop) {
return mockTimeoutResponse;
}
return messageSuccessResponse;
})
.verifiable(Times.atLeastOnce());
setupAddTab(tabId);
setupAddTab(anotherTabId);
setupDevtoolClosed(tabId);
setupDevtoolClosed(anotherTabId);
await testSubject.startMonitoringDevtool(tabId);
await flushSettledPromises();
browserAdapterMock.verify(
b => b.sendRuntimeMessage(It.isObjectWith({ tabId: tabId })),
Times.atLeastOnce(),
);
browserAdapterMock.verify(
b => b.sendRuntimeMessage(It.isObjectWith({ tabId: anotherTabId })),
Times.atLeastOnce(),
);
});
it("Handles 'Could not establish connection' error on message", async () => {
const testError = new Error(
'Error: Could not establish connection. Receiving end does not exist.',
);
browserAdapterMock
.setup(b =>
b.sendRuntimeMessage({ messageType: Messages.DevTools.StatusRequest, tabId }),
)
.throws(testError);
setupTimeoutCreator(Times.never()); // mock call is not verified if return hook throws
setupDelayCreator(Times.once());
setupDevtoolClosed(tabId);
testSubject.activeDevtoolTabIds = [tabId];
await testSubject.testPollLoop();
});
it('Throws in loop if a non timeout error occurs', async () => {
const testError = new Error('Non-timeout error');
browserAdapterMock
.setup(b =>
b.sendRuntimeMessage({ messageType: Messages.DevTools.StatusRequest, tabId }),
)
.throws(testError);
setupTimeoutCreator(Times.never()); // mock call is not verified if return hook throws
setupDelayCreator(Times.once());
testSubject.activeDevtoolTabIds = [tabId];
await expect(testSubject.testPollLoop()).rejects.toThrow(testError);
});
});
function setupPollLoop(expectedTabPollCounts: DictionaryNumberTo<number>): void {
let totalMessageCount = 0;
let totalLoopCount = 0;
Object.keys(expectedTabPollCounts).forEach(pollTabId => {
const tabPollCount: number = expectedTabPollCounts[pollTabId];
totalMessageCount += tabPollCount;
totalLoopCount = max([totalLoopCount, tabPollCount]);
setupPollTabTimes(parseInt(pollTabId), tabPollCount);
});
setupDelayCreator(Times.exactly(totalLoopCount));
setupTimeoutCreator(Times.exactly(totalMessageCount));
}
function setupPollTabTimes(pollTabId: number, times: number): void {
let tabPollCount = 0;
const expectedMessage = {
messageType: Messages.DevTools.StatusRequest,
tabId: pollTabId,
};
browserAdapterMock
.setup(b => b.sendRuntimeMessage(expectedMessage))
.returns(async message => {
tabPollCount += 1;
if (tabPollCount < times) {
return messageSuccessResponse;
} else {
return mockTimeoutResponse;
}
})
.verifiable(Times.exactly(times));
setupDevtoolClosed(pollTabId);
}
function setupTimeoutCreator(times: Times): void {
timeoutMock
.setup(t => t(It.isAny(), messageTimeout))
.returns(async (promise, timeout) => {
const result = await promise;
if (isEqual(result, mockTimeoutResponse)) {
return Promise.reject(new TimeoutError('Test timeout error'));
}
return result;
})
.verifiable(times);
}
function setupDelayCreator(times: Times): void {
delayMock.setup(d => d(It.isAny(), pollInterval)).verifiable(times);
}
function setupDevtoolClosed(tabId: number): void {
tabContextManagerMock
.setup(t =>
t.interpretMessageForTab(tabId, {
tabId: tabId,
messageType: Messages.DevTools.Closed,
}),
)
.verifiable();
if (persistData) {
idbInstanceMock
.setup(i =>
i.setItem(
'activeDevtoolTabIds',
It.is(list => !list.includes(tabId)),
),
)
.verifiable(Times.atLeastOnce());
}
}
function setupAddTab(tabId: number): void {
if (persistData) {
idbInstanceMock
.setup(i =>
i.setItem(
'activeDevtoolTabIds',
It.is(list => list.includes(tabId)),
),
)
.verifiable(Times.atLeastOnce());
}
}
}); | the_stack |
* This file was automatically generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
* In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
**/
gapi.load('client', () => {
/** now we can use gapi.client */
gapi.client.load('drive', 'v3', () => {
/** now we can use gapi.client.drive */
/** don't forget to authenticate your client before sending any request to resources: */
/** declare client_id registered in Google Developers Console */
const client_id = '<<PUT YOUR CLIENT ID HERE>>';
const scope = [
/** View and manage the files in your Google Drive */
'https://www.googleapis.com/auth/drive',
/** View and manage its own configuration data in your Google Drive */
'https://www.googleapis.com/auth/drive.appdata',
/** View and manage Google Drive files and folders that you have opened or created with this app */
'https://www.googleapis.com/auth/drive.file',
/** View and manage metadata of files in your Google Drive */
'https://www.googleapis.com/auth/drive.metadata',
/** View metadata for files in your Google Drive */
'https://www.googleapis.com/auth/drive.metadata.readonly',
/** View the photos, videos and albums in your Google Photos */
'https://www.googleapis.com/auth/drive.photos.readonly',
/** View the files in your Google Drive */
'https://www.googleapis.com/auth/drive.readonly',
/** Modify your Google Apps Script scripts' behavior */
'https://www.googleapis.com/auth/drive.scripts',
];
const immediate = true;
gapi.auth.authorize({ client_id, scope, immediate }, authResult => {
if (authResult && !authResult.error) {
/** handle succesfull authorization */
run();
} else {
/** handle authorization error */
}
});
run();
});
async function run() {
/** Gets information about the user, the user's Drive, and system capabilities. */
await gapi.client.drive.about.get({
});
/** Gets the starting pageToken for listing future changes. */
await gapi.client.drive.changes.getStartPageToken({
supportsTeamDrives: true,
teamDriveId: "teamDriveId",
});
/** Lists the changes for a user or Team Drive. */
await gapi.client.drive.changes.list({
includeCorpusRemovals: true,
includeRemoved: true,
includeTeamDriveItems: true,
pageSize: 4,
pageToken: "pageToken",
restrictToMyDrive: true,
spaces: "spaces",
supportsTeamDrives: true,
teamDriveId: "teamDriveId",
});
/** Subscribes to changes for a user. */
await gapi.client.drive.changes.watch({
includeCorpusRemovals: true,
includeRemoved: true,
includeTeamDriveItems: true,
pageSize: 4,
pageToken: "pageToken",
restrictToMyDrive: true,
spaces: "spaces",
supportsTeamDrives: true,
teamDriveId: "teamDriveId",
});
/** Stop watching resources through this channel */
await gapi.client.drive.channels.stop({
});
/** Creates a new comment on a file. */
await gapi.client.drive.comments.create({
fileId: "fileId",
});
/** Deletes a comment. */
await gapi.client.drive.comments.delete({
commentId: "commentId",
fileId: "fileId",
});
/** Gets a comment by ID. */
await gapi.client.drive.comments.get({
commentId: "commentId",
fileId: "fileId",
includeDeleted: true,
});
/** Lists a file's comments. */
await gapi.client.drive.comments.list({
fileId: "fileId",
includeDeleted: true,
pageSize: 3,
pageToken: "pageToken",
startModifiedTime: "startModifiedTime",
});
/** Updates a comment with patch semantics. */
await gapi.client.drive.comments.update({
commentId: "commentId",
fileId: "fileId",
});
/** Creates a copy of a file and applies any requested updates with patch semantics. */
await gapi.client.drive.files.copy({
fileId: "fileId",
ignoreDefaultVisibility: true,
keepRevisionForever: true,
ocrLanguage: "ocrLanguage",
supportsTeamDrives: true,
});
/** Creates a new file. */
await gapi.client.drive.files.create({
ignoreDefaultVisibility: true,
keepRevisionForever: true,
ocrLanguage: "ocrLanguage",
supportsTeamDrives: true,
useContentAsIndexableText: true,
});
/**
* Permanently deletes a file owned by the user without moving it to the trash. If the file belongs to a Team Drive the user must be an organizer on the
* parent. If the target is a folder, all descendants owned by the user are also deleted.
*/
await gapi.client.drive.files.delete({
fileId: "fileId",
supportsTeamDrives: true,
});
/** Permanently deletes all of the user's trashed files. */
await gapi.client.drive.files.emptyTrash({
});
/** Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB. */
await gapi.client.drive.files.export({
fileId: "fileId",
mimeType: "mimeType",
});
/** Generates a set of file IDs which can be provided in create requests. */
await gapi.client.drive.files.generateIds({
count: 1,
space: "space",
});
/** Gets a file's metadata or content by ID. */
await gapi.client.drive.files.get({
acknowledgeAbuse: true,
fileId: "fileId",
supportsTeamDrives: true,
});
/** Lists or searches files. */
await gapi.client.drive.files.list({
corpora: "corpora",
corpus: "corpus",
includeTeamDriveItems: true,
orderBy: "orderBy",
pageSize: 5,
pageToken: "pageToken",
q: "q",
spaces: "spaces",
supportsTeamDrives: true,
teamDriveId: "teamDriveId",
});
/** Updates a file's metadata and/or content with patch semantics. */
await gapi.client.drive.files.update({
addParents: "addParents",
fileId: "fileId",
keepRevisionForever: true,
ocrLanguage: "ocrLanguage",
removeParents: "removeParents",
supportsTeamDrives: true,
useContentAsIndexableText: true,
});
/** Subscribes to changes to a file */
await gapi.client.drive.files.watch({
acknowledgeAbuse: true,
fileId: "fileId",
supportsTeamDrives: true,
});
/** Creates a permission for a file or Team Drive. */
await gapi.client.drive.permissions.create({
emailMessage: "emailMessage",
fileId: "fileId",
sendNotificationEmail: true,
supportsTeamDrives: true,
transferOwnership: true,
useDomainAdminAccess: true,
});
/** Deletes a permission. */
await gapi.client.drive.permissions.delete({
fileId: "fileId",
permissionId: "permissionId",
supportsTeamDrives: true,
useDomainAdminAccess: true,
});
/** Gets a permission by ID. */
await gapi.client.drive.permissions.get({
fileId: "fileId",
permissionId: "permissionId",
supportsTeamDrives: true,
useDomainAdminAccess: true,
});
/** Lists a file's or Team Drive's permissions. */
await gapi.client.drive.permissions.list({
fileId: "fileId",
pageSize: 2,
pageToken: "pageToken",
supportsTeamDrives: true,
useDomainAdminAccess: true,
});
/** Updates a permission with patch semantics. */
await gapi.client.drive.permissions.update({
fileId: "fileId",
permissionId: "permissionId",
removeExpiration: true,
supportsTeamDrives: true,
transferOwnership: true,
useDomainAdminAccess: true,
});
/** Creates a new reply to a comment. */
await gapi.client.drive.replies.create({
commentId: "commentId",
fileId: "fileId",
});
/** Deletes a reply. */
await gapi.client.drive.replies.delete({
commentId: "commentId",
fileId: "fileId",
replyId: "replyId",
});
/** Gets a reply by ID. */
await gapi.client.drive.replies.get({
commentId: "commentId",
fileId: "fileId",
includeDeleted: true,
replyId: "replyId",
});
/** Lists a comment's replies. */
await gapi.client.drive.replies.list({
commentId: "commentId",
fileId: "fileId",
includeDeleted: true,
pageSize: 4,
pageToken: "pageToken",
});
/** Updates a reply with patch semantics. */
await gapi.client.drive.replies.update({
commentId: "commentId",
fileId: "fileId",
replyId: "replyId",
});
/** Permanently deletes a revision. This method is only applicable to files with binary content in Drive. */
await gapi.client.drive.revisions.delete({
fileId: "fileId",
revisionId: "revisionId",
});
/** Gets a revision's metadata or content by ID. */
await gapi.client.drive.revisions.get({
acknowledgeAbuse: true,
fileId: "fileId",
revisionId: "revisionId",
});
/** Lists a file's revisions. */
await gapi.client.drive.revisions.list({
fileId: "fileId",
pageSize: 2,
pageToken: "pageToken",
});
/** Updates a revision with patch semantics. */
await gapi.client.drive.revisions.update({
fileId: "fileId",
revisionId: "revisionId",
});
/** Creates a new Team Drive. */
await gapi.client.drive.teamdrives.create({
requestId: "requestId",
});
/** Permanently deletes a Team Drive for which the user is an organizer. The Team Drive cannot contain any untrashed items. */
await gapi.client.drive.teamdrives.delete({
teamDriveId: "teamDriveId",
});
/** Gets a Team Drive's metadata by ID. */
await gapi.client.drive.teamdrives.get({
teamDriveId: "teamDriveId",
useDomainAdminAccess: true,
});
/** Lists the user's Team Drives. */
await gapi.client.drive.teamdrives.list({
pageSize: 1,
pageToken: "pageToken",
q: "q",
useDomainAdminAccess: true,
});
/** Updates a Team Drive's metadata */
await gapi.client.drive.teamdrives.update({
teamDriveId: "teamDriveId",
});
}
}); | the_stack |
import {drag as d3drag} from "d3-drag";
import {event as d3event, select as d3select} from "d3-selection";
import {cloneArray, makeId, makeSpan, makeInputBox, px, parseDuration} from "../util";
import {EditBox} from "./editBox";
import {IHtmlElement, Point} from "./ui";
import * as FileSaver from "file-saver";
export enum FieldKind {
String,
Integer,
Double,
Boolean,
Password,
File,
Datetime,
Time,
ColumnName,
Object
}
/**
* Represents a field in the dialog.
*/
export class DialogField {
public html: HTMLSelectElement | HTMLInputElement | EditBox;
/**
* Optional kind of data expected to be input by the user.
*/
public type?: FieldKind;
}
/**
* Maps dialog fields to values. Used to cache previously-filled values
* in a dialog.
*/
class DialogValues {
/**
* Map field name to field value.
*/
public values: Map<string, string>;
constructor() { this.values = new Map<string, string>(); }
public set(field: string, value: string): void {
this.values.set(field, value);
}
public get(field: string): string {
return this.values.get(field);
}
}
/**
* Base class for implementing dialogs.
*/
class DialogBase implements IHtmlElement {
protected readonly topLevel: HTMLFormElement;
protected tabIndex: number;
protected dragging: boolean;
protected readonly buttonsDiv: HTMLDivElement;
private dragMousePosition: Point;
private dialogPosition: ClientRect;
/**
* The fieldsDiv is a div that contains all the form fields.
*/
protected readonly fieldsDiv: HTMLDivElement;
// True if any dialog is currently visible.
private static dialogVisible: boolean;
/**
* Create a dialog with the given name.
* @param title; header to show on top of the dialog.
* @param toolTip: help message to display on mouseover.
*/
constructor(title: string, toolTip: string) {
// Tab indexes seem to be global to the whole DOM.
// That's not good, since having an element with tabindex 2 will be behind all
// other elements with tabindex 1, no matter where they are in the document.
// We choose 10 here, and hope that all menu fields are at least consecutive
// in tab order in the whole DOM. Probably the right solution is to handle the
// tab keypress in an event handler.
this.tabIndex = 10;
this.dragging = false;
this.topLevel = document.createElement("form");
this.topLevel.title = toolTip;
this.topLevel.classList.add("dialog");
this.topLevel.style.left = "50%";
this.topLevel.style.top = "50%";
this.topLevel.style.transform = "translate(-50%, -50%)";
DialogBase.dialogVisible = false;
const titleElement = document.createElement("h1");
titleElement.textContent = title;
this.topLevel.appendChild(titleElement);
this.fieldsDiv = document.createElement("div");
this.topLevel.appendChild(this.fieldsDiv);
this.buttonsDiv = document.createElement("div");
this.topLevel.appendChild(this.buttonsDiv);
const drag = d3drag()
.on("start", () => this.dragStart())
.on("end", () => this.dragEnd())
.on("drag", () => this.dragMove());
d3select<Element, unknown>(this.topLevel).call(drag);
}
public dragStart(): void {
this.dragging = true;
this.dragMousePosition = { x: d3event.x, y: d3event.y };
this.dialogPosition = this.topLevel.getBoundingClientRect();
this.topLevel.style.transform = "";
this.topLevel.style.cursor = "move";
this.dragMove(); // put it in the right place; changing the transform may move it.
}
public dragMove(): void {
if (!this.dragging)
return;
const dx = this.dragMousePosition.x - d3event.x;
const dy = this.dragMousePosition.y - d3event.y;
this.topLevel.style.left = px(this.dialogPosition.left - dx);
this.topLevel.style.top = px(this.dialogPosition.top - dy);
}
public dragEnd(): void {
this.dragging = false;
this.topLevel.style.cursor = "default";
}
public hide(): void {
// Removes the menu from the DOM
this.topLevel.remove();
Dialog.dialogVisible = false;
}
public getHTMLRepresentation(): HTMLElement {
return this.topLevel;
}
public show(): void {
if (Dialog.dialogVisible)
return;
document.body.appendChild(this.topLevel);
// Prevent two dialogs from being shown at the same time.
Dialog.dialogVisible = true;
}
}
/**
* Dialog implementations - can be further subclassed.
* A dialog asks the user to fill in values for a set of fields.
*/
export class Dialog extends DialogBase {
/**
* Method to be invoked when dialog is closed with OK.
*/
public onConfirm: null | (() => void);
/**
* Stores the input elements and (optionally) their types.
*/
private fields: Map<string, DialogField> = new Map<string, DialogField>();
/**
* Maps a field name to the fieldsDiv that contains all the corresponding visual elements.
*/
private line: Map<string, HTMLElement>;
private readonly confirmButton: HTMLInputElement;
private readonly cancelButton: HTMLButtonElement;
/**
* Optional string which is used as an index in the dialogValueCache to
* populate a dialog with its previous values.
*/
private dialogCacheTitle: string | null;
/**
* This is a cache that can map a dialog title to a set of dialog values.
*/
public static dialogValueCache: Map<string, DialogValues> = new Map<string, DialogValues>();
/**
* Create a dialog with the given name.
* @param title; header to show on top of the dialog.
* @param toolTip: help message to display on mouseover.
*/
constructor(title: string, toolTip: string) {
// Tab indexes seem to be global to the whole DOM.
// That's not good, since having an element with tabindex 2 will be behind all
// other elements with tabindex 1, no matter where they are in the document.
// We choose 10 here, and hope that all menu fields are at least consecutive
// in tab order in the whole DOM. Probably the right solution is to handle the
// tab keypress in an event handler.
super(title, toolTip);
this.dialogCacheTitle = null;
this.line = new Map<string, HTMLElement>();
this.onConfirm = null;
const nodrag = d3drag()
.on("start", () => this.dragEnd());
this.cancelButton = document.createElement("button");
this.cancelButton.onclick = () => this.cancelAction();
this.cancelButton.textContent = "Cancel";
this.cancelButton.classList.add("cancel");
d3select<Element, unknown>(this.cancelButton).call(nodrag);
this.buttonsDiv.appendChild(this.cancelButton);
this.confirmButton = document.createElement("input");
this.confirmButton.type = "submit";
this.confirmButton.value = "Confirm";
this.confirmButton.classList.add("confirm");
d3select<Element, unknown>(this.confirmButton).call(nodrag);
this.buttonsDiv.appendChild(this.confirmButton);
}
/**
* Sets the dialog title. This indicates that the dialog values
* will be cached during a session and filled automatically if the
* dialog appears again. If a set of values for this title is already
* available, it is used to populate the dialog.
*/
public setCacheTitle(title: string | null): void {
this.dialogCacheTitle = title;
if (title != null) {
const values = Dialog.dialogValueCache.get(title);
if (values != null)
this.setAllValues(values);
}
}
public getAllValues(): DialogValues {
const retval = new DialogValues();
this.fields.forEach((v, k) => retval.set(k, this.getFieldValueChecked(k, false)));
return retval;
}
public setAllValues(values: DialogValues): void {
this.fields.forEach((v, k) => {
const value = values.get(k);
if (value != null)
this.setFieldValue(k, value);
});
}
protected handleKeypress(ev: KeyboardEvent): void {
if (ev.code === "Enter") {
this.hide();
this.cacheValues();
if (this.onConfirm != null)
this.onConfirm();
} else if (ev.code === "Escape") {
this.hide();
}
}
public cacheValues(): void {
if (this.dialogCacheTitle == null)
return;
const vals = this.getAllValues();
Dialog.dialogValueCache.set(this.dialogCacheTitle, vals);
}
/**
* Set the action to execute when the dialog is closed.
* @param {() => void} onConfirm Action to execute.
*/
public setAction(onConfirm: () => void): void {
this.onConfirm = onConfirm;
if (onConfirm != null)
this.confirmButton.onclick = () => {
if (this.topLevel.checkValidity()) {
this.hide();
this.cacheValues();
this.onConfirm!();
}
};
}
/**
* Display the dialog.
*/
public show(): void {
super.show();
this.confirmButton.tabIndex = this.tabIndex++;
this.cancelButton.tabIndex = this.tabIndex++;
if (this.fieldsDiv.childElementCount === 0) {
// If there are somehow no fields, focus on the container.
this.topLevel.setAttribute("tabindex", "10");
this.topLevel.focus();
} else {
// Focus on the first input element if present
const firstField = this.fields.values().next();
if (firstField.value)
firstField.value.html.focus();
else
this.topLevel.focus();
}
this.topLevel.onkeydown = (ev) => this.handleKeypress(ev);
}
private createRowContainer(fieldName: string, labelText: string, toolTip: string): HTMLDivElement {
const fieldDiv = document.createElement("div");
fieldDiv.style.display = "flex";
fieldDiv.style.alignItems = "center";
fieldDiv.title = toolTip;
fieldDiv.onmousedown = (e) => e.stopPropagation();
this.fieldsDiv.appendChild(fieldDiv);
const label = document.createElement("label");
label.textContent = labelText;
fieldDiv.appendChild(label);
this.line.set(fieldName, fieldDiv);
return fieldDiv;
}
private createInputElement(fieldName: string, labelText: string,
toolTip: string, type: string): HTMLInputElement {
const fieldDiv = this.createRowContainer(fieldName, labelText, toolTip);
if (type === "checkbox") {
const filler = document.createElement("span");
filler.style.flexGrow = "100";
fieldDiv.appendChild(filler);
}
const input: HTMLInputElement = document.createElement("input");
input.tabIndex = this.tabIndex++;
if (type !== "checkbox")
input.style.flexGrow = "100";
input.id = makeId(fieldName);
input.type = type;
fieldDiv.appendChild(input);
return input;
}
/**
* Add a text field with the given internal name, label, and data type.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param type: Data type of this field.
* @param value: Initial default value.
* @param toolTip: Help message to show as a tool-tip.
* @return The input element created for the user to type the text.
*/
public addTextField(fieldName: string, labelText: string,
type: FieldKind, value: string | null,
toolTip: string): HTMLInputElement {
let t = "string";
if (type === FieldKind.Integer)
t = "number";
else if (type === FieldKind.Password)
t = "password";
const input = this.createInputElement(fieldName, labelText, toolTip, t);
this.fields.set(fieldName, {html: input, type});
if (value != null)
input.value = value;
return input;
}
/**
* Add a field used to select a file name on the local filesystem.
* @param {string} fieldName Name of the field.
* @param {string} labelText Text in the dialog for this field.
* @param {string} toolTip Help message to show as a tooltip.
* @return The input element created for the user to type the text.
*/
public addFileField(
fieldName: string, labelText: string, toolTip: string): HTMLInputElement {
const input = this.createInputElement(fieldName, labelText, toolTip, "file");
this.fields.set(fieldName, {html: input, type: FieldKind.File});
return input;
}
/**
* Add a multi-line text field with the given internal name, label, and data type.
* @param fieldName Internal name. Has to be used when parsing the input.
* @param labelText Text in the dialog for this field.
* @param pre String to write before editable field.
* @param value Initial default value.
* @param post String to write after editable field.
* @param toolTip Help message to show as a tool-tip.
*/
public addMultiLineTextField(fieldName: string, labelText: string, pre: string | null,
value: string | null, post: string | null, toolTip: string): void {
const fieldDiv = this.createRowContainer(fieldName, labelText, toolTip);
const input = new EditBox(fieldName, pre, value, post);
input.setTabIndex(this.tabIndex++);
fieldDiv.appendChild(input.getHTMLRepresentation());
this.fields.set(fieldName, {html: input});
}
/**
* Adds a simple text to the dialog.
* @param textString Text to show in the dialog.
* @returns A reference to the HTML element holding the text.
*/
public addText(textString: string): HTMLElement {
const fieldDiv = this.createRowContainer("message", textString, "");
return fieldDiv.children[0] as HTMLElement;
}
/**
* Add a text field with the given internal name, label, and data type.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param value: Initial default value.
* @param toolTip: Help message to show as a tool-tip.
* @return The input element created for the user to type the text.
*/
public addBooleanField(fieldName: string, labelText: string,
value: boolean, toolTip: string): HTMLInputElement {
const input = this.createInputElement(fieldName, labelText, toolTip, "checkbox");
this.fields.set(fieldName, {html: input, type: FieldKind.Boolean });
if (value != null && value)
input.checked = true;
return input;
}
/**
* Add a datetime-local input field.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param value: Initial default value.
* @param toolTip: Help message to show as a tool-tip.
* @return The input element created for the user to type the text.
*/
public addDateTimeField(fieldName: string, labelText: string,
value: Date | null,
toolTip: string): HTMLInputElement {
const input = this.createInputElement(fieldName, labelText, toolTip, "datetime-local");
this.fields.set(fieldName, { html: input, type: FieldKind.Datetime });
if (value != null)
input.value = value.toISOString().slice(0, 16);
const close = document.createElement("span");
close.className = "close";
close.innerHTML = "×";
close.onclick = () => input.value = "";
close.title = "Clear date.";
input.parentElement!.appendChild(close);
return input;
}
private addSelectInternal(fieldName: string, labelText: string,
options: string[], value: string | null,
toolTip: string, type: FieldKind): HTMLInputElement | HTMLSelectElement {
let result: HTMLInputElement | HTMLSelectElement | null = null;
// If we have lots of options use a sorted datalist, otherwise
// use a select field.
if (options.length > 50) {
const select = this.createInputElement(fieldName, labelText, toolTip, "string");
const sortOptions = cloneArray(options);
sortOptions.sort();
const datalist = document.createElement("datalist");
this.topLevel.appendChild(datalist);
datalist.id = makeId("list" + fieldName);
select.setAttribute("list", datalist.id);
sortOptions.forEach((option) => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.text = option;
datalist.appendChild(optionElement);
});
result = select;
} else {
const fieldDiv = this.createRowContainer(fieldName, labelText, toolTip);
const select = document.createElement("select");
select.tabIndex = this.tabIndex++;
select.style.flexGrow = "100";
select.id = makeId(fieldName);
fieldDiv.appendChild(select);
options.forEach((option) => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.text = option;
select.add(optionElement);
});
if (value != null) {
let i;
for (i = 0; i < options.length; i++) {
if (options[i] === value) {
select.selectedIndex = i;
break;
}
}
if (i === options.length)
throw new Error(`Given default value ${value} not found in options.`);
}
result = select;
}
this.fields.set(fieldName, {html: result, type: type });
if (value != null)
result.value = value;
return result;
}
/**
* Add a drop-down selection field with the given options.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param options: List of strings that are the options in the selection box.
* @param value: Initial default value.
* @param toolTip: Help message to show as a tool-tip.
* @return A reference to the select html input field.
*/
public addSelectField(fieldName: string, labelText: string,
options: string[], value: string | null,
toolTip: string): HTMLInputElement | HTMLSelectElement {
return this.addSelectInternal(
fieldName, labelText, options, value, toolTip, FieldKind.String);
}
protected selectFields: Map<string, Map<string, any>> = new Map();
/**
* Add a drop-down selection field with the specified options.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param options: List of objects that are the options in the selection box.
* @param label: A function that computes the label for each option.
* @param toolTip: Help message to show as a tool-tip.
* @return A reference to the select html input field.
*/
public addSelectFieldAsObject<T>(fieldName: string, labelText: string,
options: T[], label: (t: T) => string,
toolTip: string): HTMLInputElement | HTMLSelectElement {
let v = null;
const names = options.map(p => label(p));
const map = new Map<string, T>();
for (let i = 0; i < names.length; i++)
map.set(names[i], options[i]);
this.selectFields.set(fieldName, map);
if (options.length > 0)
v = names[0];
return this.addSelectInternal(
fieldName, labelText, names,
v, toolTip, FieldKind.Object);
}
public getFieldValueAsObject<T>(fieldName: string): T | null {
if (this.fields.get(fieldName).type !== FieldKind.Object) {
console.assert(false, "Field is not an object");
return null;
}
// This must be a select field.
const map = this.selectFields.get(fieldName);
if (map == null)
return null;
return map.get(this.getFieldValue(fieldName)) as T;
}
/**
* Add a drop-down selection field for column names with the given options.
* @param fieldName: Internal name. Has to be used when parsing the input.
* @param labelText: Text in the dialog for this field.
* @param options: List of column display names that are the options in the selection box.
* @param value: Initial default value; if null the first value from the options is used.
* @param toolTip: Help message to show as a tool-tip.
* @return A reference to the select html input field.
*/
public addColumnSelectField(fieldName: string, labelText: string,
options: string[], value: string | null,
toolTip: string): HTMLInputElement | HTMLSelectElement {
let v = null;
if (value !== null)
v = value;
else if (options.length > 0)
v = options[0];
return this.addSelectInternal(
fieldName, labelText, options,
v, toolTip, FieldKind.ColumnName);
}
/**
* Make the specified field visible or invisible.
* @param {string} labelText Label associated to the field.
* @param {boolean} show If true show the field, else hide it.
*/
public showField(labelText: string, show: boolean): void {
const fieldDiv = this.line.get(labelText);
if (fieldDiv == null)
return;
if (show)
fieldDiv.style.display = "flex";
else
fieldDiv.style.display = "none";
}
private getFieldValueChecked(field: string, check: boolean): string {
const f = this.fields.get(field);
if (f.type === FieldKind.Boolean) {
const hi = f.html as HTMLInputElement;
return "" + hi.checked;
} else {
if (check)
console.assert(f.type !== FieldKind.ColumnName);
return f.html.value;
}
}
/**
* The value associated with a specific field in a dialog.
* @param {string} field Field whose value is sought.
* @returns {string} The value associated to the given field.
*/
public getFieldValue(field: string): string {
return this.getFieldValueChecked(field, true);
}
/**
* Get the value associated with a field that represents a column name.
* @param field Field name.
*/
public getColumnName(field: string): string {
const f = this.fields.get(field);
console.assert(f.type === FieldKind.ColumnName);
return f.html.value;
}
/**
* The value associated with a boolean (checkbox) field.
* @param {string} field Field name whose value is sought.
* @returns {boolean} True if the field is checked.
*/
public getBooleanValue(field: string): boolean {
return (this.fields.get(field).html as HTMLInputElement).checked;
}
/**
* The value associated with a datetime field.
* @param {string} field Field name whose value is sought.
*/
public getDateTimeValue(field: string): Date | null {
return new Date((this.fields.get(field).html as HTMLInputElement).value);
}
/**
* Set the value of a field in the dialog.
* @param {string} field Field whose value is set.
* @param {string} value Value that is being set.
*/
public setFieldValue(field: string, value: string | null): void {
let f = this.fields.get(field);
if (f.type === FieldKind.Boolean) {
const hi = f.html as HTMLInputElement;
hi.checked = (value === "true");
} else {
if (value != null)
f.html.value = value;
}
}
/**
* Set the value of a column field in the dialog.
* @param {string} field Field whose value is set.
* @param value Value that is being set.
*/
public setColumnValue(field: string, value: string): void {
const f = this.fields.get(field);
console.assert(f.type === FieldKind.ColumnName);
f.html.value = value;
}
/**
* The value associated with a field cast to an integer.
* Returns either a number or null if the value cannot be parsed.
*/
public getFieldValueAsInt(field: string): number | null {
const s = this.getFieldValue(field);
const result = parseInt(s, 10);
if (isNaN(result))
return null;
return result;
}
/**
* Gets the field value as a number, encoded using the Hillview time
* encoding rules.
*/
public getFieldValueAsInterval(field: string): number | null {
const s = this.getFieldValue(field);
return parseDuration(s);
}
/**
* The value associated with a field cast to a double.
* Returns either a number or null if the value cannot be parsed.
*/
public getFieldValueAsNumber(field: string): number | null {
const s = this.getFieldValue(field);
const result = parseFloat(s);
if (isNaN(result))
return null;
return result;
}
/**
* The value associated with a field representing a file selector.
*/
public getFieldValueAsFiles(field: string): FileList | null {
const f = this.fields.get(field).html as HTMLInputElement;
return f.files;
}
private cancelAction(): void {
// Remove this element from the DOM.
this.hide();
}
}
/**
* Notifications have no input elements, just an OK button.
*/
export class NotifyDialog extends DialogBase {
constructor(title: string, message: string | null, toolTip: string) {
super(title, toolTip);
const nodrag = d3drag()
.on("start", () => this.dragEnd());
const confirmButton = document.createElement("button");
confirmButton.textContent = "Confirm";
confirmButton.classList.add("confirm");
confirmButton.onclick = () => this.hide();
d3select<Element, unknown>(confirmButton).call(nodrag);
this.buttonsDiv.appendChild(confirmButton);
if (message != null)
this.fieldsDiv.appendChild(makeSpan(message, false));
}
public show(): void {
super.show();
this.topLevel.focus();
this.topLevel.onkeydown = (ev) => this.handleKeypress(ev);
}
protected handleKeypress(ev: KeyboardEvent): void {
if (ev.code === "Enter" || ev.code === "Escape")
this.hide();
}
}
/**
* Bookmark notification with a copy link button.
*/
export class NotifyBookmarkDialog extends NotifyDialog {
constructor(title: string, url: string | null, toolTip: string) {
super(title, null, toolTip);
const urlBox = makeInputBox(url) as HTMLInputElement;
urlBox.style.width = "100%";
urlBox.style.float = "left";
this.fieldsDiv.appendChild(urlBox);
const copyButton = document.createElement("button");
copyButton.textContent = "Copy Link";
copyButton.classList.add("confirm");
copyButton.addEventListener("click", () => {
urlBox.select();
urlBox.setSelectionRange(0, 99999);
document.execCommand("copy");
this.hide();
});
// replace the confirm button with copy button
this.buttonsDiv.replaceChild(
copyButton,
this.buttonsDiv.firstElementChild!
);
}
}
/**
* Save data in a file on the local filesystem.
* @param {string} filename File to save data to.
* @param {string} contents Contents to write in file.
*/
export function saveAs(filename: string, contents: string): void {
const blob = new Blob([contents], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, filename);
const notify = new NotifyDialog("File has been saved.",
"Look for file " + filename, "File has been saved");
notify.show();
}
/**
* Save data in a file on the local filesystem.
* @param {string} url Url to display.
*/
export function showBookmarkURL(url: string): void {
const notify = new NotifyBookmarkDialog(
"Bookmark has been saved.",
url, "Access the bookmark using this link");
notify.show();
} | the_stack |
import { EncodedString } from "../elements/elements";
import { EncodedContextData, GreaseMonkeyData, BrowserTabsQueryInfo, GreaseMonkeyDataInfo } from './background/sharedTypes';
declare const browserAPI: browserAPI;
declare global {
interface Window {
_crmAPIRegistry: any[];
}
}
export type CRMAPIMessage = {
id: CRM.GenericNodeId;
type: 'logCrmAPIValue';
tabId: TabId;
tabIndex: TabIndex;
data: {
type: 'evalResult';
value: {
type: 'success';
result: any;
}|{
type: 'error';
result: {
stack: string;
name: string;
message: string;
}
};
id: CRM.GenericNodeId;
tabIndex: TabIndex;
callbackIndex: number;
lineNumber: string;
timestamp: string;
tabId: TabId;
}
}|{
id: CRM.GenericNodeId;
type: 'displayHints';
tabId: TabId;
tabIndex: TabIndex;
data: {
hints: string[];
id: CRM.GenericNodeId;
tabIndex: TabIndex;
callbackIndex: number;
tabId: TabId;
}
}|{
id: CRM.GenericNodeId;
tabIndex: TabIndex;
tabId: TabId;
type: 'applyLocalStorage';
data: {
tabIndex: TabIndex;
key: string;
value: any;
}
}|{
id: CRM.GenericNodeId;
tabIndex: TabIndex;
type: 'respondToBackgroundMessage',
data: {
message: any,
id: CRM.GenericNodeId;
tabIndex: TabIndex;
tabId: TabId;
response: number;
},
tabId: TabId;
}|{
id: CRM.GenericNodeId;
type: 'sendInstanceMessage';
data: {
toInstanceId: number;
toTabIndex: TabIndex;
tabIndex: TabIndex;
message: any;
id: CRM.GenericNodeId;
tabId: TabId;
}
tabId: TabId;
tabIndex: TabIndex;
onFinish: {
maxCalls: number;
fn: number;
}
}|{
id: CRM.GenericNodeId;
type: 'changeInstanceHandlerStatus';
tabIndex: TabIndex;
data: {
tabIndex: TabIndex;
hasHandler: boolean;
};
tabId: TabId;
}|{
id: CRM.GenericNodeId;
type: 'updateStorage';
data: {
type: 'nodeStorage';
nodeStorageChanges: {
key: string;
oldValue: any;
newValue: any;
}[];
id: CRM.GenericNodeId;
tabIndex: TabIndex;
tabId: TabId;
};
tabIndex: TabIndex;
tabId: TabId;
}|{
id: CRM.GenericNodeId;
type: 'crmapi';
tabIndex: TabIndex;
action: string;
crmPath: number[];
data: any[];
onFinish: {
persistent: boolean;
maxCalls: number;
fn: number;
};
tabId: TabId;
}|{
type: 'chrome';
id: CRM.GenericNodeId;
tabIndex: TabIndex;
api: string;
args: ({
type: "fn";
isPersistent: boolean;
val: number;
}|{
type: "arg";
val: string;
}|{
type: "return";
val: number;
})[];
tabId: TabId;
requestType: 'GM_download'|'GM_notification'|undefined;
}|{
type: 'browser';
id: CRM.GenericNodeId;
tabIndex: TabIndex;
api: string;
args: ({
type: "fn";
isPersistent: boolean;
val: number;
}|{
type: "arg";
val: string;
}|{
type: "return";
val: number;
})[];
tabId: TabId;
requestType: 'GM_download'|'GM_notification'|undefined;
}|{
id: CRM.GenericNodeId;
type: 'addNotificationListener';
data: {
notificationId: number;
onClick: number;
tabIndex: TabIndex;
onDone: number;
id: CRM.GenericNodeId;
tabId: TabId;
};
tabIndex: TabIndex;
tabId: TabId;
}|{
id: CRM.GenericNodeId;
type: 'sendBackgroundpageMessage';
data: {
message: any;
id: CRM.GenericNodeId;
tabId: TabId;
tabIndex: TabIndex;
response: number;
},
tabIndex: TabIndex;
tabId: TabId;
}|{
id: CRM.GenericNodeId;
type: 'logCrmAPIValue',
tabId: TabId;
tabIndex: TabIndex;
data: {
type: 'log',
data: EncodedString<string[]>,
id: CRM.GenericNodeId;
logId: number;
tabIndex: TabIndex;
lineNumber: number;
tabId: TabId;
}
};
(function(window: Window) {
function runtimeGetURL(url: string): string {
if (typeof browserAPI !== 'undefined') {
return browserAPI.runtime.getURL(url);
} else if ('chrome' in window) {
return (window as any).chrome.runtime.getURL(url);
} else {
return url;
}
}
function runtimeConnect(id: string, options: {
name: string
}): _browser.runtime.Port|_chrome.runtime.Port {
if (typeof browserAPI !== 'undefined') {
return browserAPI.runtime.connect(id, options);
} else if ('chrome' in window) {
return (window as any).chrome.runtime.connect(id, options);
} else {
return null;
}
}
type Message<T> = T & {
messageType: string;
callbackId?: number;
};
interface CallbackMessage {
callbackId: number;
type: 'success'|'error'|'chromeError';
data: string|any;
lastError?: Error;
messageType: 'callback';
}
interface CreateCRMConfig {
position?: {
node?: number;
relation?: 'firstChild'|'firstSibling'|'lastChild'|
'lastSibling'|'before'|'after';
}
name?: string;
type?: CRM.NodeType;
usesTriggers?: boolean;
triggers?: {
url: string;
}[];
linkData?: Partial<CRM.LinkVal>;
scriptData?: Partial<CRM.ScriptVal>;
stylesheetData?: Partial<CRM.StylesheetVal>;
}
interface SpecialJSONObject {
refs: any[];
data: any[]|Object;
rootType: 'normal'|'array'|'object';
paths: (string|number)[][];
}
interface RestoredContextData {
target: HTMLElement;
toElement: HTMLElement;
srcElement: HTMLElement;
}
type SymbolType = 'string'|'number'|'boolean'|
'object'|'undefined'|'symbol'|'function'|'bigint';
type ModifiedSymbolTypes = SymbolType|'array';
interface CommInstance {
id: TabId;
tabIndex: TabIndex;
sendMessage(message: any, callback: (data: {
error: true;
success: false;
message: any;
}|{
error: false;
success: true;
}) => void): void;
}
interface Relation {
node?: CRM.GenericNodeId;
relation?: 'firstChild'|'firstSibling'|'lastChild'|'lastSibling'|'before'|'after';
}
type InstanceCallback = (data: {
error: true;
success: false;
message: any;
}|{
error: false;
success: true;
}) => void;
type InstanceListener = (message: any) => void;
type RespondableInstanceListener = (message: any, respond: (response: any) => void) => void;
interface CallbackStorageInterface<T> {
constructor: Function;
length: number;
add(item: T): number;
remove(itemORIndex: T|number): void;
get(index: number): T;
forEach(operation: (target: T, index: number) => void): void;
}
type StorageChangeListener = (key: string, oldValue: any, newValue: any, remote: boolean) => void;
type CRMNodeCallback = (node: CRM.SafeNode) => void;
type MaybeArray<T> = T | T[];
interface ChromeRequestInterface {
a?(...params: any[]): ChromeRequestInterface;
args?(...params: any[]): ChromeRequestInterface;
r?(handler: (...args: any[]) => void): ChromeRequestInterface;
return?(handler: (...args: any[]) => void): ChromeRequestInterface;
p?(...functions: ((...args: any[]) => void)[]): ChromeRequestInterface;
persistent?(...functions: ((...args: any[]) => void)[]): ChromeRequestInterface;
send?(): ChromeRequestInterface;
s?(): ChromeRequestInterface;
request?: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
onError?(error: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}): void;
};
}
interface BrowserRequestInterface {
a?(...params: any[]): BrowserRequestInterface;
args?(...params: any[]): BrowserRequestInterface;
p?(...functions: ((...args: any[]) => void)[]): BrowserRequestInterface;
persistent?(...functions: ((...args: any[]) => void)[]): BrowserRequestInterface;
send?(): Promise<any>;
s?(): Promise<any>;
request?: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
};
}
/**
* Settings for a GM_download call
*/
interface DownloadSettings {
/**
* The URL to download
*/
url?: string;
/**
* The name of the downloaded files
*/
name?: string;
/**
* Headers for the XHR
*/
headers?: { [headerKey: string]: string };
/**
* A function to call when downloaded
*/
onload?: () => void;
/**
* A function to call on error
*/
onerror?: (e: any) => void;
}
/**
* Settings for a GM_notification call
*/
interface NotificationOptions {
/**
* The text on the notification
*/
text?: string;
/**
* The URL of the image to use
*/
imageUrl?: string;
/**
* The title of the notification
*/
title?: string;
/**
* A function to run when the notification is clicked
*/
onclick?: (e: Event) => void;
/**
* Whether the notification should be clickable
*/
isClickable?: boolean;
/**
* A function to run when the notification disappears
*/
ondone?: () => void;
}
let localStorageProxy: {
[key: string]: any;
[key: number]: any;
} = { };
try {
Object.defineProperty(window, 'localStorageProxy', {
get: function() {
return localStorageProxy;
}
});
} catch(e) {
}
Object.defineProperty(localStorageProxy, 'getItem', {
get: function() {
return function(key: string) {
return localStorage[key];
}
}
});
const localStorageProxyData = {
onSet: function(_key: string, _value: string) { }
}
Object.defineProperty(localStorageProxy, 'setItem', {
get: function() {
return localStorageProxyData.onSet;
}
});
Object.defineProperty(localStorageProxy, 'clear', {
get: function() {
return function() {}
}
});
type TruePrivateClass<T> = T & {
__privates__: (keyof T)[];
};
function mapObject<T>(obj: T, privateKeys: (keyof T)[]): T {
const privateData: T = {} as T;
const privateValues: T = {} as T;
for (let key in obj) {
if (privateKeys.indexOf(key) === -1) {
Object.defineProperty(privateValues, key, {
get() {
return obj[key];
},
set(value) {
obj[key] = value;
}
});
} else {
Object.defineProperty(privateValues, key, {
get() {
return privateData[key];
},
set(value) {
privateData[key] = value;
}
});
privateData[key] = obj[key];
}
}
return privateValues;
}
function removePrivateValues<T>(target: T, privateKeys: (keyof T)[]) {
for (const privateKey of privateKeys) {
(target as any)[privateKey] = undefined;
}
}
class DataMap<K, V> {
_store: ([K, V])[] = [];
set(key: K, value: V) {
this._store.push([key, value]);
}
get(key: K): V {
for (const [storeKey, storeData] of this._store) {
if (key === storeKey) {
return storeData;
}
}
return null;
}
}
function getFunctionThisMap(original: Function,
thisMap: DataMap<Object, Object>, thisArgs: Object[]): (this: any, ...args: any[]) => any|void {
const newFn = function(this: any, ...args: any[]): any|void {
return original.apply(thisMap.get(this) || this, args);
};
for (const key in original) {
if (typeof (original as any)[key] === 'function') {
(newFn as any)[key] = function(this: any, ...args: any[]): any|void {
return (original as any)[key].apply(thisMap.get(this) || this, args);
}
if (thisArgs.indexOf(newFn) === -1) {
thisArgs.push(newFn);
}
} else {
(newFn as any)[key] = (original as any)[key];
}
}
newFn.prototype = original.prototype;
return newFn;
}
function mapObjThisArgs<T extends {
[key: string]: any;
[key: number]: any;
}|any[]>(target: T, thisMap: DataMap<Object, Object>, thisArgs: Object[]) {
const windowVar = typeof window === 'undefined' ? self : window;
let hasKeys = false;
for (let key in target) {
if (!hasKeys) {
hasKeys = true;
if (thisArgs.indexOf(target) === -1) {
thisArgs.push(target);
}
}
const value = target[key] as any;
if (value === windowVar || !value || key === '_chromeRequest') {
continue;
}
switch (typeof value) {
case 'function':
target[key] = getFunctionThisMap(value, thisMap, thisArgs);
break;
case 'object':
const htmlEl = (window as any).HTMLElement as any;
if (htmlEl && value instanceof htmlEl) {
target[key] = value;
} else {
mapObjThisArgs(value, thisMap, thisArgs);
}
break;
}
}
}
function truePrivateClass(target: typeof CrmAPIInstance) {
const thisMap = new DataMap<Object, Object>();
const proto = target.prototype as TruePrivateClass<typeof target.prototype>;
const thisArgs: Object[] = [];
return class extends target {
constructor(node: CRM.Node, id: CRM.GenericNodeId, tabData: _browser.tabs.Tab,
clickData: _browser.contextMenus.OnClickData, secretKey: number[],
nodeStorage: CRM.NodeStorage, contextData: EncodedContextData,
greasemonkeyData: GreaseMonkeyData, isBackground: boolean,
options: CRM.Options, enableBackwardsCompatibility: boolean, tabIndex: TabIndex,
extensionId: string, supportedAPIs: string, nodeStorageSync: CRM.NodeStorage) {
super(node, id, tabData, clickData, secretKey, nodeStorage,
contextData, greasemonkeyData, isBackground,
options, enableBackwardsCompatibility, tabIndex,
extensionId, supportedAPIs, nodeStorageSync);
mapObjThisArgs(this, thisMap, thisArgs);
const mapped = mapObject(this as any, proto.__privates__);
thisMap.set(this, mapped);
thisMap.set(mapped, mapped);
thisArgs.forEach((thisArg) => {
thisMap.set(thisArg, mapped);
});
removePrivateValues<CrmAPIInstance>(this, proto.__privates__);
this._init(enableBackwardsCompatibility);
}
}
}
function makePrivate(target: any, name: any) {
target.__privates__ = (target.__privates__ || []).concat([name]);
}
const enum STORAGE_TYPE {
SYNC,
LOCAL
}
type Wrappable = {
[key: string]: Wrappable|Function;
}
/**
* A class for constructing the CRM API
*
*
* @class
* @param {Object} node - The item currently being edited
* @param {CRM.GenericNodeId} id - The id of the current item
* @param {Object} tabData - Any data about the tab the script is currently running on
* @param {Object} clickData - Any data associated with clicking this item in the
* context menu, only available if launchMode is equal to 0 (on click)
* @param {number[]} secretKey - An array of integers, generated to keep downloaded
* scripts from finding local scripts with more privilege and act as if they
* are those scripts to run stuff you don't want it to.
* @param {Object} nodeStorage - The storage data for the node
* @param {Object} contextData - The data related to the click on the page
* @param {Object} greasemonkeyData - Any greasemonkey data, including metadata
* @param {Boolean} isBackground - If true, this page is functioning as a background page
* @param {Object} _options - The options the user has entered for this script/stylesheet
* @param {boolean} enableBackwardsCompatibility - Whether the localStorage object should reflect nodes
* @param {TabIndex} tabIndex - The index of this script (with this id) running on this tab
* @param {string} extensionId - The id of the extension
* @param {string} supportedAPIs - The supported browser APIs
*/
@truePrivateClass
class CrmAPIInstance {
@makePrivate
private __privates: {
_node: CRM.Node,
_id: CRM.GenericNodeId,
_tabData: _browser.tabs.Tab,
_clickData: _browser.contextMenus.OnClickData,
_secretKey: number[];
_nodeStorage: CRM.NodeStorage;
_nodeStorageSync: CRM.NodeStorage;
_contextData: EncodedContextData|RestoredContextData;
_greasemonkeyData: GreaseMonkeyData;
_isBackground: boolean;
_options: CRM.Options;
_enableBackwardsCompatibility: boolean;
_tabIndex: TabIndex;
_instanceId: number;
_extensionId: string;
_supportedAPIs: string;
_sendMessage: (message: any) => void;
_queue: any[];
_port: {
postMessage(data: any): void;
onMessage?: {
addListener(listener: (message: any) => void): void;
}
};
_findElementsOnPage(contextData: EncodedContextData): void;
_setupStorages(): void;
_setupBrowserAPI(instance: CrmAPIInstance): void;
_callInfo: CallbackStorageInterface<{
callback(...args: any[]): void;
stackTrace: string[];
persistent: boolean;
maxCalls: number;
}>;
_getStackTrace(error: Error): string[];
_createDeleterFunction(index: number): () => void;
_createCallback(callback: (...args: any[]) => void, error: Error, options: {
persistent?: boolean;
maxCalls?: number;
}): number;
/**
* Creates a callback function that gets executed here instead of in the background page
*
* @param {function} callback - The function to run
* @param {Error} error - The "new Error" value to formulate a useful stack trace
* @param {Object} [options] - An options object containing the persistent and
* maxCalls properties
* @param {boolean} [options.persistent] - If this value is true the callback will not be deleted
* even after it has been called
* @param {number} [options.maxCalls] - The maximum amount of times the function can be called
* before the crmapi stops listening for it.
* @returns {number} - The index of the callback to use (can be used to retrieve it)
*/
_createCallbackFunction(callback: Function, error: Error, options: {
persistent?: boolean;
maxCalls?: number;
}): number;
_handshakeFunction(this: CrmAPIInstance): void;
_lastError: {
checked: boolean;
err: Error;
}
_callbackHandler(message: CallbackMessage): void;
_executeCode(message: Message<{
messageType: 'executeCRMCode';
code: string;
logCallbackIndex: number;
}>): void;
_getObjectProperties(target: any): string[];
_leadingWordRegex: RegExp,
_sectionRegex: RegExp,
_endRegex: RegExp,
_getCodeSections(code: string): {
lead: string;
words: string[];
end: {
type: 'brackets'|'dotnotation';
currentWord: string;
}|null;
};
_getSuggestions(message: Message<{
messageType: 'getCRMHints';
code: string;
logCallbackIndex: number;
}>): string[];
_getHints(message: Message<{
messageType: 'getCRMHints';
code: any;
logCallbackIndex: number;
}>): void;
_remoteStorageChange(changes: {
oldValue: any;
newValue: any;
key: string;
}[], isSync: STORAGE_TYPE): void;
_instancesReady: boolean,
_instancesReadyListeners: ((instances: CommInstance[]) => void)[],
_instances: CallbackStorageInterface<CommInstance>;
_instancesChange(change: {
type: 'removed';
value: number;
}|{
type: 'added';
value: number;
tabIndex: number;
}): void;
_commListeners: CallbackStorageInterface<InstanceListener>;
_instanceMessageHandler(message: Message<{
message: any;
}>): void;
_handleValueChanges(oldData: string[], newData: string[], indexes: {
[key: string]: any;
[key: number]: any;
}, index: number): () => void;
_localStorageProxyHandler(message: Message<{
message: {
[key: string]: any;
[key: number]: any;
} & {
indexIds: {
[key: string]: any;
[key: number]: any;
}
};
}>): void;
_generateBackgroundResponse(message: Message<{
message: any;
respond: number;
tabId: TabId;
id: CRM.GenericNodeId;
}>): (data: any) => void;
_backgroundPageListeners: CallbackStorageInterface<RespondableInstanceListener>;
_backgroundPageMessageHandler(message: Message<{
message: any;
respond: number;
tabId: TabId
id: CRM.GenericNodeId;
}>): void;
_createVariable(log: {
logObj: SpecialJSONObject;
originalValues: any[];
}, index: number): void;
_sentLogs:{
logObj: SpecialJSONObject;
originalValues: any[];
}[];
_createLocalVariable(message: Message<{
code: {
index: number;
logId: number;
path: string;
};
logCallbackIndex: number;
}>): void;
_messageHandler(message: Message<any>): void;
_connect(): void;
_saveLogValues(arr: any[]): {
data: string;
logId: number;
};
_generateSendInstanceMessageFunction(instanceId: number, tabIndex: TabIndex): (message: any, callback: (result: {
error: true;
success: false;
message: any;
}|{
error: false;
success: true;
}) => void) => void;
_sendInstanceMessage(instanceId: number, tabIndex: TabIndex, message: any, callback: (result: {
error: true;
success: false;
message: any;
}| {
error: false;
success: true;
}) => void): void;
_updateCommHandlerStatus(hasHandler: boolean): void;
_storageListeners: CallbackStorageInterface<{
callback: StorageChangeListener;
type: STORAGE_TYPE;
key: string;
}>,
_storagePrevious: {
[key: string]: any;
[key: number]: any;
}
_storagePreviousSync: {
[key: string]: any;
[key: number]: any;
}
/**
* Notifies any listeners of changes to the storage object
*/
_notifyChanges(storageType: STORAGE_TYPE,
keyPath: string|string[]|number[], oldValue: any,
newValue: any, remote?: boolean): void;
_localStorageChange(keyPath: string|string[]|number[], oldValue: any,
newValue: any, isSync: STORAGE_TYPE): void;
/**
* Sends a message to the background script with given parameters
*
* @param {string} action - What the action is
* @param {function} callback - The function to run when done
* @param {Object} params - Any options or parameters
*
* @returns {Promise<any>} A promise resolving with the result of the call
*/
_sendOptionalCallbackCrmMessage(this: CrmAPIInstance, action: string, callback: (...args: any[]) => void, params: {
[key: string]: any;
[key: number]: any;
}, persistent?: boolean): Promise<any>;
/**
* Sends a message to the background script with given parameters
*
* @param {string} action - What the action is
* @param {function} callback - The function to run when done
* @param {Object} params - Any options or parameters
* @returns {Promise<any>} A promise that resolves with the response to the message
*/
_sendCrmMessage(action: string, callback: (...args: any[]) => void, params?: {
[key: string]: any;
[key: number]: any;
}): Promise<any>;
/**
* Send a message to the background script with a promise instead of a callback
*
* @param {string} action - What the action is
* @param {Object} params - Any options or parameters
*/
_sendPromiseMessage(this: CrmAPIInstance, action: string, params?: {
[key: string]: any;
[key: number]: any;
}): Promise<any>;
_ensureBackground(): boolean;
/**
* Wraps a browser object to keep track of each level's parents
*
* @param {Object} toWrap - The object to wrap
* @param {Object} instance - The CRM API instance that is the parent
* @param {string[]} [parents] - The parents of this call
*/
_wrapBrowserObject<T extends Wrappable>(toWrap: T, instance: CrmAPIInstance, parents?: string[]): T;
/**
* Uses given arguments as arguments for the API in order specified. If the argument is
* not a function, it is simply passed along, if it is, it's converted to a
* function that will preserve scope but is not passed to the browser API itself.
* Instead a placeholder is passed that will take any arguments the browser API passes to it
* and calls your fn function with local scope with the arguments the browser API passed. Keep in
* mind that there is no connection between your function and the browser API, the browser API only
* sees a placeholder function with which it can do nothing so don't use this as say a forEach handler.
*/
_browserRequest: BrowserRequestInterface & {
new(__this: CrmAPIInstance, api: string, type?: string): BrowserRequestInterface;
};
/**
* Uses given arguments as arguments for the API in order specified. If the argument is
* not a function, it is simply passed along, if it is, it's converted to a
* function that will preserve scope but is not passed to the chrome API itself.
* Instead a placeholder is passed that will take any arguments the chrome API passes to it
* and calls your fn function with local scope with the arguments the chrome API passed. Keep in
* mind that there is no connection between your function and the chrome API, the chrome API only
* sees a placeholder function with which it can do nothing so don't use this as say a forEach handler.
*/
_chromeRequest: ChromeRequestInterface & {
new(__this: CrmAPIInstance, api: string, type?: string): ChromeRequestInterface;
};
_specialRequest(api: string, type: string): BrowserRequestInterface;
_setupRequestEvent(aOpts: {
method?: string,
url?: string,
headers?: { [headerKey: string]: string },
data?: any,
binary?: boolean,
timeout?: number,
context?: any,
responseType?: string,
overrideMimeType?: string,
anonymous?: boolean,
fetch?: boolean,
username?: string,
password?: string,
onload?: (e: Event) => void,
onerror?: (e: Event) => void,
onreadystatechange?: (e: Event) => void,
onprogress?: (e: Event) => void,
onloadstart?: (e: Event) => void,
ontimeout?: (e: Event) => void
}, aReq: XMLHttpRequest, aEventName: string): void;
/**
* Adds a listener for the notification with ID notificationId
*
* @param {number} notificationId - The id of te notification to listen for
* @param {number} onclick - The onclick handler for the notification
* @param {number} ondone - The onclose handler for the notification
*/
_addNotificationListener(notificationId: number, onclick: number, ondone: number): void;
_setGlobalFunctions(): void;
_storageGet(storageType: STORAGE_TYPE, keyPath?: string|string[]|number[]): any;
_storageSet(storageType: STORAGE_TYPE, keyPath: string|string[]|number[]|{
[key: string]: any;
[key: number]: any;
}, value?: any): void;
_storageRemove(storageType: STORAGE_TYPE, keyPath: string|string[]|number[]): void;
_addStorageOnChangeListener(storageType: STORAGE_TYPE,
listener: StorageChangeListener, key?: string): number;
_removeStorageChangeListener(storageType: STORAGE_TYPE,
listener: StorageChangeListener|number, key: string): void;
} = {
_node: null,
_id: null,
_tabData: null,
_clickData: null,
_secretKey: null,
_nodeStorage: null,
_nodeStorageSync: null,
_contextData: null,
_greasemonkeyData: null,
_isBackground: null,
_options: null,
_enableBackwardsCompatibility: null,
_tabIndex: null,
_instanceId: null,
_extensionId: null,
_supportedAPIs: null,
_sendMessage: null,
_queue: [],
_port: {
postMessage: null,
onMessage: {
addListener: null
}
},
/**
* Turns the class-index based number back to an element
*/
_findElementsOnPage(this: CrmAPIInstance, contextData: EncodedContextData) {
//It's ran without a click
if (typeof window.document === 'undefined' || !contextData) {
this.contextData = {
target: null,
toElement: null,
srcElement: null
};
return;
}
const targetClass = 'crm_element_identifier_' + contextData.target;
const toElementClass = 'crm_element_identifier_' + contextData.toElement;
const srcElementClass = 'crm_element_identifier_' + contextData.srcElement;
this.contextData = {
target: window.document.querySelector('.' + targetClass) as HTMLElement,
toElement: window.document.querySelector('.' + toElementClass) as HTMLElement,
srcElement: window.document.querySelector('.' + srcElementClass) as HTMLElement
}
this.contextData.target && this.contextData.target.classList.remove(targetClass);
this.contextData.toElement && this.contextData.toElement.classList.remove(toElementClass);
this.contextData.srcElement && this.contextData.srcElement.classList.remove(srcElementClass);
},
_setupBrowserAPI(instance: CrmAPIInstance) {
const __this = this;
const listener = {
addListener() {},
removeListener() {}
}
instance.browser = {...this._wrapBrowserObject({
alarms: {
create() {},
get() {},
getAll() {},
clear() {},
clearAll() {},
onAlarm: listener
},
bookmarks: {
create() {},
get() {},
getChildren() {},
getRecent() {},
getSubTree() {},
getTree() {},
move() {},
remove() {},
removeTree() {},
search() {},
update() {},
onCreated: listener,
onRemoved: listener,
onChanged: listener,
onMoved: listener
},
browserAction: {
setTitle() {},
getTitle() {},
setIcon() {},
setPopup() {},
getPopup() {},
openPopup() {},
setBadgeText() {},
getBadgeText() {},
setBadgeBackgroundColor() {},
getBadgeBackgroundColor() {},
enable() {},
disable() {},
onClicked: listener
},
browsingData: {
remove() {},
removeCache() {},
removeCookies() {},
removeDownloads() {},
removeFormData() {},
removeHistory() {},
removePasswords() {},
removePluginData() {},
settings() {}
},
commands: {
getAll() {},
onCommand: listener
},
contextMenus: {
create() {},
update() {},
remove() {},
removeAll() {},
onClicked: listener
},
contextualIdentities: {
create() {},
get() {},
query() {},
update() {},
remove() {}
},
cookies: {
get() {},
getAll() {},
set() {},
remove() {},
getAllCookieStores() {},
onChanged: listener
},
devtools: {
inspectedWindow: {
eval() {},
reload() {}
},
network: {
onNavigated: listener
},
panels: {
create() {},
}
},
downloads: {
download() {},
search() {},
pause() {},
resume() {},
cancel() {},
open() {},
show() {},
showDefaultFolder() {},
erase() {},
removeFile() {},
onCreated: listener,
onErased: listener,
onChanged: listener
},
extension: {
getURL() {},
getViews() {},
getBackgroundPage() {},
isAllowedIncognitoAccess() {},
isAllowedFileSchemeAccess() {},
},
history: {
search() {},
getVisits() {},
addUrl() {},
deleteUrl() {},
deleteRange() {},
deleteAll() {},
onVisited: listener,
onVisitRemoved: listener
},
i18n: {
getAcceptLanguage() {},
getMessage() {},
getUILanguage() {},
detectLanguage() {},
},
identity: {
getRedirectURL() {},
launchWebAuthFlow() {}
},
idle: {
queryState() {},
setDetectionInterval() {},
onStateChanged: listener
},
management: {
getSelf() {},
uninstallSelf() {},
},
notifications: {
create() {},
clear() {},
getAll() {},
onClicked: listener,
onClosed: listener
},
omnibox: {
setDefaultSuggestion() {},
onInputStarted: listener,
onInputChanged: listener,
onInputEntered: listener,
onInputCancelled: listener
},
pageAction: {
show() {},
hide() {},
setTitle() {},
getTitle() {},
setIcon() {},
setPopup() {},
getPopup() {},
onClicked: listener
},
permissions: {
contains() {},
getAll() {},
request() {},
remove() {}
},
runtime: {
setUninstallURL() {},
connectNative() {},
sendNativeMessage() {},
getBrowserInfo() {},
connect() {},
getBackgroundPage() {},
getManifest() {},
getURL() {},
getPlatformInfo() {},
openOptionsPage() {},
reload() {},
sendMessage() {},
onStartup: listener,
onUpdateAvailable: listener,
onInstalled: listener,
onConnectExternal: listener,
onConnect: listener,
onMessage: listener,
onMessageExternal: listener,
lastError: undefined,
id: null
},
sessions: {
getRecentlyClosed() {},
restore() {},
setTabValue() {},
getTabValue() {},
removeTabValue() {},
setWindowValue() {},
getWindowValue() {},
removeWindowValue() {},
onChanged: listener
},
sidebarAction: {
setPanel() {},
getPanel() {},
setTitle() {},
getTitle() {},
setIcon() {},
open() {},
close() {}
},
storage: {
local: {
get() {},
set() {},
remove() {},
clear() {}
},
sync: {
get() {},
set() {},
remove() {},
clear() {}
},
onChanged: listener
},
tabs: {
connect() {},
detectLanguage() {},
duplicate() {},
getZoom() {},
getZoomSettings() {},
insertCSS() {},
removeCSS() {},
move() {},
print() {},
printPreview() {},
reload() {},
remove() {},
saveAsPDF() {},
setZoom() {},
setZoomSettings() {},
create() {},
get() {},
getCurrent() {},
captureVisibleTab() {},
update() {},
query() {},
executeScript() {},
sendMessage() {},
onActivated: listener,
onAttached: listener,
onCreated: listener,
onDetached: listener,
onMoved: listener,
onReplaced: listener,
onZoomChanged: listener,
onUpdated: listener,
onRemoved: listener,
onHighlighted: listener
},
topSites: {
get() {},
},
webNavigation: {
getFrame() {},
getAllFrames() {},
onBeforeNavigate: listener,
onCommitted: listener,
onCreateNavigationTarget: listener,
onDOMContentLoaded: listener,
onCompleted: listener,
onErrorOccurred: listener,
onReferenceFragmentUpdated: listener,
onHistoryStateUpdated: listener
},
webRequest: {
onBeforeRequest: listener,
onBeforeSendHeaders: listener,
onSendHeaders: listener,
onHeadersReceived: listener,
onAuthRequired: listener,
onResponseStarted: listener,
onBeforeRedirect: listener,
onCompleted: listener,
onErrorOccurred: listener,
filterResponseData() {},
},
windows: {
get() {},
getCurrent() {},
getLastFocused() {},
getAll() {},
create() {},
update() {},
remove() {},
onCreated: listener,
onRemoved: listener,
onFocusChanged: listener
},
theme: {
getCurrent() {},
update() {},
reset() {}
}
}, instance), ...{
any(api: string) {
return new __this._browserRequest(this, api);
}
}}
},
_setupStorages(this: CrmAPIInstance) {
this.__privates._callInfo = new CrmAPIInstance._helpers.CallbackStorage<{
callback(...args: any[]): void;
stackTrace: string[];
persistent: boolean;
maxCalls: number;
}>()
this.__privates._instances = new CrmAPIInstance._helpers.CallbackStorage<CommInstance>();
this.__privates._commListeners = new CrmAPIInstance._helpers.CallbackStorage<InstanceListener>();
this.__privates._backgroundPageListeners = new CrmAPIInstance._helpers.CallbackStorage<
RespondableInstanceListener
>();
this.__privates._storageListeners = new CrmAPIInstance._helpers.CallbackStorage<{
callback: StorageChangeListener;
type: STORAGE_TYPE;
key: string;
}>()
},
_callInfo: null,
_getStackTrace(error: Error): string[] {
return error.stack.split('\n');
},
_createDeleterFunction(this: CrmAPIInstance, index: number): () => void {
return () => {
this.__privates._callInfo.remove(index);
};
},
/**
* Creates a callback function that gets executed here instead of in the background page
*
* @param {function} callback - A handler for the callback function that gets passed
* the status of the call (error or success), some data (error message or function params)
* and a stacktrace.
* @param {Error} error - The "new Error" value to formulate a useful stack trace
* @param {Object} [options] - An options object containing the persistent and
* maxCalls properties
* @param {boolean} [options.persistent] - If this value is true the callback will not be deleted
* even after it has been called
* @param {number} [options.maxCalls] - The maximum amount of times the function can be called
* before the crmapi stops listening for it.
* @returns {number} - The index of the callback to use (can be used to retrieve it)
*/
_createCallback(this: CrmAPIInstance, callback: (...args: any[]) => void, error: Error, options: {
persistent?: boolean;
maxCalls?: number;
}): number {
options = options || {};
const persistent = options.persistent;
const maxCalls = options.maxCalls || 1;
error = error || new Error();
const index = this.__privates._callInfo.add({
callback: callback,
stackTrace: this.stackTraces && this.__privates._getStackTrace(error),
persistent: persistent,
maxCalls: maxCalls
});
//Wait an hour for the extreme cases, an array with a few numbers in it can't be that horrible
if (!persistent) {
setTimeout(this.__privates._createDeleterFunction(index), 3600000);
}
return index;
},
/**
* Creates a callback function that gets executed here instead of in the background page
*
* @param {function} callback - The function to run
* @param {Error} error - The "new Error" value to formulate a useful stack trace
* @param {Object} [options] - An options object containing the persistent and
* maxCalls properties
* @param {boolean} [options.persistent] - If this value is true the callback will not be deleted
* even after it has been called
* @param {number} [options.maxCalls] - The maximum amount of times the function can be called
* before the crmapi stops listening for it.
* @returns {number} - The index of the callback to use (can be used to retrieve it)
*/
_createCallbackFunction(this: CrmAPIInstance, callback: Function, error: Error, options: {
persistent?: boolean;
maxCalls?: number;
}): number {
const __this = this;
function onFinish(status: 'error'|'chromeError'|'success', messageOrParams: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}, stackTrace: string[]) {
if (status === 'error') {
__this.onError && __this.onError(messageOrParams);
if (__this.stackTraces) {
setTimeout(() => {
console.log('stack trace: ');
stackTrace.forEach((line) => {
console.log(line);
});
}, 5);
}
if (__this.errors) {
throw new Error('CrmAPIError: ' + messageOrParams.error);
} else {
console.warn('CrmAPIError: ' + messageOrParams.error);
}
} else {
callback.apply(__this, messageOrParams);
}
}
return this.__privates._createCallback(onFinish, error, options);
},
_handshakeFunction(this: CrmAPIInstance, ) {
this.__privates._sendMessage = (message) => {
if (message.onFinish) {
message.onFinish = this.__privates._createCallback(message.onFinish.fn, new Error(), {
maxCalls: message.onFinish.maxCalls,
persistent: message.onFinish.persistent
});
}
this.__privates._port.postMessage(message);
};
this.__privates._queue.forEach((message) => {
this.__privates._sendMessage(message);
});
this.__privates._queue = null;
},
_lastError: null,
_callbackHandler(this: CrmAPIInstance, message: CallbackMessage) {
const call = this.__privates._callInfo.get(message.callbackId);
if (call) {
if (message.data && message.data.lastError) {
this.__privates._lastError = {
checked: false,
err: message.data.lastError
}
}
call.callback(message.type, message.data, call.stackTrace);
if (message.data && message.data.lastError) {
if (!this.__privates._lastError.checked) {
if (this.onError) {
this.onError({
error: 'Unchecked lastError',
message: 'Unchecked lastError',
lineNumber: 0,
stackTrace: (call.stackTrace && call.stackTrace.join('\n')) || ''
});
} else {
throw new Error('Unchecked lastError');
}
}
this.__privates._lastError = undefined;
}
if (!call.persistent) {
call.maxCalls--;
if (call.maxCalls === 0) {
this.__privates._callInfo.remove(message.callbackId);
}
}
}
},
_executeCode(this: CrmAPIInstance, message: Message<{
messageType: 'executeCRMCode';
code: string;
logCallbackIndex: number;
}>) {
const timestamp = new Date().toLocaleString();
let err = (new Error()).stack.split('\n')[1];
if (err.indexOf('eval') > -1) {
err = (new Error()).stack.split('\n')[2];
}
let val;
try {
const global = (this.__privates._isBackground ? self : window);
val = {
type: 'success',
result: JSON.stringify(CrmAPIInstance._helpers.specialJSON.toJSON.apply(CrmAPIInstance._helpers.specialJSON, [(
eval.apply(global, [message.code]))]))
};
} catch(e) {
val = {
type: 'error',
result: {
stack: e.stack,
name: e.name,
message: e.message
}
};
}
this.__privates._sendMessage({
id: this.__privates._id,
type: 'logCrmAPIValue',
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
data: {
type: 'evalResult',
value: val,
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
callbackIndex: message.logCallbackIndex,
lineNumber: '<eval>:0',
timestamp: timestamp,
tabId: this.__privates._tabData.id
}
});
},
_getObjectProperties(this: CrmAPIInstance, target: any): string[]{
const prototypeKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(target));
const targetKeys = [];
for (const key in target) {
targetKeys.push(key);
}
return prototypeKeys.concat(targetKeys);
},
_leadingWordRegex: /^(\w+)/,
_sectionRegex: /^((\[(['"`])(\w+)\3\])|(\.(\w+)))/,
_endRegex: /^(\.(\w+)?|\[((['"`])((\w+)(\11)?)?)?)?/,
_getCodeSections(this: CrmAPIInstance, code: string): {
lead: string;
words: string[];
end: {
type: 'brackets'|'dotnotation';
currentWord: string;
}|null;
} {
const leadingWord = this.__privates._leadingWordRegex.exec(code)[1];
code = code.slice(leadingWord.length);
const subsections = [];
let subsection;
while ((subsection = this.__privates._sectionRegex.exec(code))) {
const word = subsection[4] || subsection[5];
subsections.push(word);
code = code.slice(word.length);
}
const endRegex = this.__privates._endRegex.exec(code);
let end: {
type: 'brackets'|'dotnotation';
currentWord: string;
} = null;
if (endRegex) {
end = {
type: endRegex[3] ? 'brackets' : 'dotnotation',
currentWord: endRegex[2] || endRegex[6]
};
}
return {
lead: leadingWord,
words: subsections,
end: end
}
},
_getSuggestions(this: CrmAPIInstance, message: Message<{
messageType: 'getCRMHints';
code: string;
logCallbackIndex: number;
}>): string[] {
const { lead, words, end } = this.__privates._getCodeSections(message.code);
if (!end) {
return null;
}
if (!(lead in window)) {
return null;
}
let target = (window as any)[lead];
if (target) {
for (let i = 0; i < words.length; i++) {
if (!(words[i] in target)) {
return null;
}
target = target[words[i]];
}
//Now for the actual hinting
const hints: {
full: string[];
partial: string[];
} = {
full: [],
partial: []
};
const properties = this.__privates._getObjectProperties(target);
for (let i = 0; i < properties.length; i++) {
if (properties[i] === end.currentWord) {
hints.full.push(properties[i]);
} else if (properties[i].indexOf(end.currentWord) === 0) {
hints.partial.push(properties[i]);
}
}
return hints.full.sort().concat(hints.partial.sort());
}
return null;
},
_getHints(this: CrmAPIInstance, message: Message<{
messageType: 'getCRMHints';
code: any;
logCallbackIndex: number;
}>) {
const suggestions = this.__privates._getSuggestions(message) || [];
this.__privates._sendMessage({
id: this.__privates._id,
type: 'displayHints',
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
data: {
hints: suggestions,
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
callbackIndex: message.logCallbackIndex,
tabId: this.__privates._tabData.id
}
});
},
_remoteStorageChange(this: CrmAPIInstance, changes: {
oldValue: any;
newValue: any;
key: string;
}[], storageType: STORAGE_TYPE) {
const src = storageType === STORAGE_TYPE.SYNC ?
this.__privates._nodeStorageSync :
this.__privates._nodeStorage;
for (let i = 0; i < changes.length; i++) {
const keyPath = changes[i].key.split('.');
this.__privates._notifyChanges(storageType,
keyPath, changes[i].oldValue, changes[i].newValue, true);
const data = CrmAPIInstance._helpers.lookup(keyPath, src, true) || {};
(data as any)[keyPath[keyPath.length - 1]] = changes[i].newValue;
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
}
},
_instancesReady: false,
_instancesReadyListeners: [],
_instances: null,
_instancesChange(this: CrmAPIInstance, change: {
type: 'removed';
value: CRM.GenericNodeId;
}|{
type: 'added';
value: CRM.GenericNodeId;
tabIndex: number;
}) {
switch (change.type) {
case 'removed':
this.__privates._instances.forEach((instance, idx) => {
if (instance.id === change.value) {
this.__privates._instances.remove(idx);
}
});
break;
case 'added':
this.__privates._instances.add({
id: change.value,
tabIndex: change.tabIndex,
sendMessage: this.__privates._generateSendInstanceMessageFunction(change.value, change.tabIndex)
});
break;
}
},
_commListeners: null,
_instanceMessageHandler(this: CrmAPIInstance, message: Message<{
message: any;
}>) {
this.__privates._commListeners.forEach((listener) => {
listener && typeof listener === 'function' && listener(message.message);
});
},
_handleValueChanges(this: CrmAPIInstance, oldData: string[], newData: string[], indexes: {
[key: string]: any;
[key: number]: any;
}, index: number): () => void {
return () => {
if (oldData[2] !== newData[2]) {
//Data was changed
switch (newData[1]) {
case 'Link':
const newLinks = newData[2].split(',').map((link) => {
return {
url: link,
newTab: true
}
});
(this.crm.link as any).setLinks(indexes[index], newLinks);
break;
case 'Script':
const newScriptData = newData[2].split('%124');
(this.crm.script as any).setScript(indexes[index], newScriptData[1], () => {
(this.crm as any).setLaunchMode(indexes[index], ~~newScriptData[0] as CRMLaunchModes);
});
break;
}
}
}
},
_localStorageProxyHandler(this: CrmAPIInstance, message: Message<{
message: {
[key: string]: any;
[key: number]: any;
} & {
indexIds: {
[key: string]: any;
[key: number]: any;
}
};
}>) {
const indexes = message.message.indexIds;
for (const key in message.message) {
if (key !== 'indexIds') {
try {
Object.defineProperty(localStorageProxy, key, {
get: function() {
return localStorageProxy[key];
},
set: function(value) {
localStorageProxyData.onSet(key, value);
}
});
} catch(e) {
//Already defined
}
}
}
localStorageProxyData.onSet = (key, value) => {
if (!isNaN(parseInt(key, 10))) {
const index = parseInt(key, 10);
//It's an index key
const oldValue = localStorageProxy[key] as string;
const newValue = value;
localStorageProxy[key] = value;
const oldData = oldValue.split('%123');
const newData = newValue.split('%123');
if (index >= message.message.numberofrows) {
//Create new node
const createOptions = {
name: newData[0],
type: newData[1].toLowerCase()
} as Partial<CreateCRMConfig> & {
position?: Relation;
};
switch (newData[1]) {
case 'Link':
createOptions.linkData = newData[2].split(',').map((link) => {
return {
url: link,
newTab: true
}
});
break;
case 'Script':
const newScriptData = newData[2].split('%124');
createOptions.scriptData = {
launchMode: ~~newScriptData[0],
script: newScriptData[1]
}
break;
}
(this.crm as any).createNode(createOptions);
} else {
const changeData = {} as Partial<CreateCRMConfig>;
if (oldData[0] !== newData[0]) {
//Name was changed
changeData.name = newData[0];
}
if (oldData[1] !== newData[1]) {
//Type was changed
changeData.type = newData[1].toLowerCase() as CRM.NodeType;
}
if (changeData.name || changeData.type) {
(this.crm as any).editNode(indexes[index], changeData,
this.__privates._handleValueChanges(oldData, newData, indexes, index));
} else {
this.__privates._handleValueChanges(oldData, newData, indexes, index)();
}
}
} else {
//Send message
localStorageProxy[key] = value;
this.__privates._sendMessage({
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
type: 'applyLocalStorage',
data: {
tabIndex: this.__privates._tabIndex,
key: key,
value: value
},
tabId: this.__privates._tabData.id
});
}
}
},
_generateBackgroundResponse(this: CrmAPIInstance, message: Message<{
message: any;
respond: number;
tabId: TabId;
id: CRM.GenericNodeId;
}>): (data: any) => void {
return (data: any) => {
this.__privates._sendMessage({
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
type: 'respondToBackgroundMessage',
data: {
message: data,
id: message.id,
tabIndex: this.__privates._tabIndex,
tabId: message.tabId,
response: message.respond
},
tabId: this.__privates._tabData.id
});
};
},
_backgroundPageListeners: null,
_backgroundPageMessageHandler(this: CrmAPIInstance, message: Message<{
message: any;
respond: number;
tabId: TabId
id: CRM.GenericNodeId;
}>) {
this.__privates._backgroundPageListeners.forEach((listener) => {
listener && typeof listener === 'function' &&
listener(message.message, this.__privates._generateBackgroundResponse(message));
});
},
_createVariable(this: CrmAPIInstance, log: {
logObj: SpecialJSONObject;
originalValues: any[];
}, index: number) {
const global = (this.__privates._isBackground ? self : window);
let i;
for (i = 1; 'temp' + i in global; i++) { }
(global as any)[('temp' + i)] = log.originalValues[index];
return 'temp' + i;
},
_sentLogs: [null],
_createLocalVariable(this: CrmAPIInstance, message: Message<{
code: {
index: number;
logId: number;
path: string;
};
logCallbackIndex: number;
}>) {
const log = this.__privates._sentLogs[message.code.logId];
const bracketPathArr = ('[' + message.code.index + ']' +
message.code.path.replace(/\.(\w+)/g, (_fullString, match) => {
return '["' + match + '"]';
})).split('][');
bracketPathArr[0] = bracketPathArr[0].slice(1);
bracketPathArr[bracketPathArr.length - 1] = bracketPathArr[bracketPathArr.length - 1].slice(
0, bracketPathArr[bracketPathArr.length - 1].length - 1
);
const bracketPath = JSON.stringify(bracketPathArr.map((pathValue: EncodedString<number>) => {
return JSON.parse(pathValue);
}));
for (let i = 0; i < log.logObj.paths.length; i++) {
if (bracketPath === JSON.stringify(log.logObj.paths[i])) {
const createdVariableName = this.__privates._createVariable(log, i);
this.log('Created local variable ' + createdVariableName);
return;
}
}
this.log('Could not create local variable');
},
_messageHandler(this: CrmAPIInstance, message: Message<any>) {
if (this.__privates._queue) {
//Update instance array
const { instances, currentInstance } = (message as Message<{
data: 'connected';
instances: {
id: TabId;
tabIndex: TabIndex;
}[];
currentInstance: {
id: TabId;
tabIndex: TabIndex;
};
}>);
if (currentInstance === null) {
this.__privates._instanceId = -1;
this.instanceId = -1;
} else {
this.__privates._instanceId = currentInstance.id;
this.instanceId = currentInstance.id;
}
for (let i = 0; i < instances.length; i++) {
this.__privates._instances.add({
id: instances[i].id,
tabIndex: instances[i].tabIndex,
sendMessage: this.__privates._generateSendInstanceMessageFunction(instances[i].id, instances[i].tabIndex)
});
}
const instancesArr: CommInstance[] = [];
this.__privates._instances.forEach((instance) => {
instancesArr.push(instance);
});
this.__privates._instancesReady = true;
this.__privates._instancesReadyListeners.forEach((listener) => {
listener(instancesArr);
});
this.__privates._handshakeFunction.apply(this, []);
} else {
switch (message.messageType) {
case 'callback':
this.__privates._callbackHandler(message);
break;
case 'executeCRMCode':
this.__privates._executeCode(message);
break;
case 'getCRMHints':
this.__privates._getHints(message);
break;
case 'storageUpdate':
this.__privates._remoteStorageChange(message.changes, message.isSync);
break;
case 'instancesUpdate':
this.__privates._instancesChange(message.change);
break;
case 'instanceMessage':
this.__privates._instanceMessageHandler(message);
break;
case 'localStorageProxy':
this.__privates._localStorageProxyHandler(message);
break;
case 'backgroundMessage':
this.__privates._backgroundPageMessageHandler(message);
break;
case 'createLocalLogVariable':
this.__privates._createLocalVariable(message);
break;
case 'dummy':
break;
}
}
},
_connect(this: CrmAPIInstance, ) {
//Connect to the background-page
this.__privates._queue = [];
this.__privates._sendMessage = (message: any) => {
this.__privates._queue.push(message);
};
if (!this.__privates._isBackground) {
this.__privates._port = runtimeConnect(this.__privates._extensionId, {
name: JSON.stringify(this.__privates._secretKey)
});
}
if (!this.__privates._isBackground) {
this.__privates._port.onMessage.addListener(this.__privates._messageHandler.bind(this));
this.__privates._port.postMessage({
id: this.__privates._id,
key: this.__privates._secretKey,
tabId: this.__privates._tabData.id
});
} else {
this.__privates._port = (self as any).handshake(this.__privates._id, this.__privates._secretKey, this.__privates._messageHandler.bind(this));
}
},
_saveLogValues(this: CrmAPIInstance, arr: any[]): {
data: string;
logId: number;
} {
const { json, originalValues } = CrmAPIInstance._helpers.specialJSON.toJSON.apply(
CrmAPIInstance._helpers.specialJSON, [arr, true]);
this.__privates._sentLogs.push({
logObj: json as SpecialJSONObject,
originalValues: originalValues
});
return {
data: JSON.stringify(json),
logId: this.__privates._sentLogs.length - 1
};
},
_generateSendInstanceMessageFunction(this: CrmAPIInstance, instanceId: number,
tabIndex: TabIndex): (message: any, callback: (result: {
error: true;
success: false;
message: any;
}|{
error: false;
success: true;
}) => void) => void {
return (message: any, callback: (result: {
error: true;
success: false;
message: any;
}|{
error: false;
success: true;
}) => void) => {
this.__privates._sendInstanceMessage(instanceId, tabIndex, message, callback);
};
},
_sendInstanceMessage(this: CrmAPIInstance, instanceId: number, tabIndex: TabIndex, message: any, callback: (result: {
error: true;
success: false;
message: any;
}| {
error: false;
success: true;
}) => void) {
function onFinish(type: 'error'|'success', data: string) {
if (!callback || typeof callback !== 'function') {
return;
}
if (type === 'error') {
callback({
error: true,
success: false,
message: data
});
} else {
callback({
error: false,
success: true
});
}
}
this.__privates._sendMessage({
id: this.__privates._id,
type: 'sendInstanceMessage',
data: {
toInstanceId: instanceId,
toTabIndex: tabIndex,
tabIndex: this.__privates._tabIndex,
message: message,
id: this.__privates._id,
tabId: this.__privates._tabData.id
},
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
onFinish: {
maxCalls: 1,
fn: onFinish
}
});
},
_updateCommHandlerStatus(this: CrmAPIInstance, hasHandler: boolean) {
this.__privates._sendMessage({
id: this.__privates._id,
type: 'changeInstanceHandlerStatus',
tabIndex: this.__privates._tabIndex,
data: {
tabIndex: this.__privates._tabIndex,
hasHandler: hasHandler
},
tabId: this.__privates._tabData.id
});
},
_storageListeners: null,
_storagePrevious: {},
_storagePreviousSync: {},
/**
* Notifies any listeners of changes to the storage object
*/
_notifyChanges(this: CrmAPIInstance, storageType: STORAGE_TYPE,
keyPath: string|string[]|number[], oldValue: any,
newValue: any, remote: boolean = false) {
let keyPathString: string;
if (Array.isArray(keyPath)) {
keyPathString = keyPath.join('.');
} else {
keyPathString = keyPath;
}
this.__privates._storageListeners.forEach((listener) => {
if (listener.type !== storageType) {
return;
}
if (!listener.key || listener.key.indexOf(keyPathString) === 0) {
CrmAPIInstance._helpers.isFn(listener.callback) &&
listener.callback(keyPathString, oldValue, newValue, remote || false);
}
});
this.__privates._storagePrevious = this.__privates._nodeStorage;
},
_localStorageChange(this: CrmAPIInstance, keyPath: string|string[]|number[], oldValue: any,
newValue: any, storageType: STORAGE_TYPE) {
this.__privates._sendMessage({
id: this.__privates._id,
type: 'updateStorage',
data: {
type: 'nodeStorage',
isSync: storageType === STORAGE_TYPE.SYNC,
nodeStorageChanges: [
{
key: typeof keyPath === 'string' ? keyPath : keyPath.join('.'),
oldValue: oldValue,
newValue: newValue
}
],
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
tabId: this.__privates._tabData.id
},
tabIndex: this.__privates._tabIndex,
tabId: this.__privates._tabData.id
});
this.__privates._notifyChanges(storageType,
keyPath, oldValue, newValue, false);
},
/**
* Sends a message to the background script with given parameters
*
* @param {string} action - What the action is
* @param {function} callback - The function to run when done
* @param {Object} params - Any options or parameters
*/
_sendOptionalCallbackCrmMessage(this: CrmAPIInstance, action: string, callback: (...args: any[]) => void, params: {
[key: string]: any;
[key: number]: any;
}, persistent: boolean = false) {
return new Promise<any>((resolve, reject) => {
const onFinish = (status: 'error'|'chromeError'|'success', messageOrParams: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}, stackTrace: string[]) => {
if (status === 'error') {
this.onError && this.onError(messageOrParams);
if (this.stackTraces) {
setTimeout(() => {
console.log('stack trace: ');
stackTrace.forEach((line) => {
console.log(line);
});
}, 5);
}
if (this.errors) {
reject(new Error('CrmAPIError: ' + messageOrParams.error));
} else {
console.warn('CrmAPIError: ' + messageOrParams.error);
}
} else {
callback && callback.apply(this, messageOrParams);
resolve((messageOrParams as any)[0]);
}
}
const message = {
type: 'crmapi',
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
action: action,
crmPath: this.__privates._node.path,
data: params,
onFinish: {
persistent: persistent,
maxCalls: 1,
fn: onFinish
},
tabId: this.__privates._tabData.id
};
this.__privates._sendMessage(message);
});
},
/**
* Sends a message to the background script with given parameters
*
* @param {string} action - What the action is
* @param {function} callback - The function to run when done
* @param {Object} params - Any options or parameters
*/
_sendCrmMessage(this: CrmAPIInstance, action: string, callback: (...args: any[]) => void, params: {
[key: string]: any;
[key: number]: any;
} = {}) {
return new Promise<any>((resolve, reject) => {
const prom = this.__privates._sendOptionalCallbackCrmMessage
.call(this, action, callback, params);
prom.then(resolve, reject);
});
},
/**
* Send a message to the background script with a promise instead of a callback
*
* @param {string} action - What the action is
* @param {Object} params - Any options or parameters
*/
_sendPromiseMessage(this: CrmAPIInstance, action: string, params: {
[key: string]: any;
[key: number]: any;
} = {}) {
return this.__privates._sendOptionalCallbackCrmMessage
.call(this, action, () => {}, params);
},
_ensureBackground(this: CrmAPIInstance): boolean {
if (!this.__privates._isBackground) {
throw new Error('Attempting to use background-page function from non-background page');
}
return true;
},
_wrapBrowserObject<T extends Wrappable>(toWrap: T, instance: CrmAPIInstance, parents: string[] = []): T {
const __this = this;
const wrapped: T = {} as T;
for (const key in toWrap) {
const value = toWrap[key];
if (typeof value === 'object') {
wrapped[key] = this._wrapBrowserObject(value as {
[key: string]: Function|T;
}, instance, [...parents, key]) as T[Extract<keyof T, string>];
} else if (typeof value === 'function') {
const obj = CrmAPIInstance._helpers.mergeObjects(function(this: any, ...args: any[]) {
return new __this._browserRequest(this,
[...parents, key].join('.')).args(...args);
}, {
a(...args: any[]): BrowserRequestInterface {
return obj.args.apply(this, args);
},
args(...args: any[]): BrowserRequestInterface {
return new __this._browserRequest(this as any,
[...parents, key].join('.')).args(...args);
},
p(...fns: any[]): BrowserRequestInterface {
return obj.persistent.apply(this, fns);
},
persistent(...fns: any[]): BrowserRequestInterface {
return new __this._browserRequest(this as any,
[...parents, key].join('.')).persistent(...fns);
},
s(): Promise<any> {
return obj.send.apply(this, []);
},
send(): Promise<any> {
return new __this._browserRequest(this as any,
[...parents, key].join('.')).send();
}
});
Object.defineProperty(obj, 'request', {
get() {
return new __this._browserRequest(this as any,
[...parents, key].join('.')).request;
}
});
wrapped[key] = obj as any;
} else {
wrapped[key] = toWrap[key];
}
}
return wrapped;
},
_browserRequest: class BrowserRequest implements BrowserRequestInterface {
request: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
onError?(error: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}): void;
};
returnedVal: BrowserRequestInterface;
constructor(public __this: CrmAPIInstance, api: string, type?: string) {
const request: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
} = {
api: api,
chromeAPIArguments: [],
_sent: false
};
this.request = request;
if (__this.warnOnChromeFunctionNotSent) {
window.setTimeout(() => {
if (!request._sent) {
console.warn('Looks like you didn\'t send your chrome function,' +
' set crmAPI.warnOnChromeFunctionNotSent to false to disable this message');
}
}, 5000);
}
Object.defineProperty(request, 'type', {
get: function () {
return type;
}
});
const returnVal: BrowserRequestInterface = CrmAPIInstance._helpers.mergeObjects((...args: any[]) => {
return this.a.bind(this)(...args);
}, {
a: this.a.bind(this),
args: this.args.bind(this),
p: this.p.bind(this),
persistent: this.persistent.bind(this),
send: this.send.bind(this),
s: this.s.bind(this),
request: this.request
});
this.returnedVal = returnVal;
return this.returnedVal as any;
}
new(__this: CrmAPIInstance, _api: string, _type?: string): BrowserRequest {
return this;
}
args(...args: any[]): BrowserRequestInterface {
for (let i = 0; i < args.length; i++) {
const arg = arguments[i];
if (typeof arg === 'function') {
this.request.chromeAPIArguments.push({
type: 'fn',
isPersistent: false,
val: this.__this.__privates._createCallback(arg, new Error(), {
maxCalls: 1
})
});
}
else {
this.request.chromeAPIArguments.push({
type: 'arg',
val: CrmAPIInstance._helpers.jsonFn.stringify(arg)
});
}
}
return this.returnedVal;
};
a(...args: any[]): BrowserRequestInterface {
return this.args(...args);
}
/**
* A function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
*/
persistent(...fns: any[]): BrowserRequestInterface {
for (let i = 0; i < fns.length; i++) {
this.request.chromeAPIArguments.push({
type: 'fn',
isPersistent: true,
val: this.__this.__privates._createCallback(fns[i], new Error(), {
persistent: true
})
});
}
return this.returnedVal;
}
p(...fns: any[]): BrowserRequestInterface {
return this.persistent(...fns);
}
s<T>(): Promise<T> {
return this.send<T>();
}
send<T>(): Promise<T> {
return new Promise<T>((resolve, reject) => {
const requestThis = this;
this.request._sent = true;
let maxCalls = 0;
let isPersistent = false;
this.request.chromeAPIArguments.forEach((arg) => {
if (arg.type === 'fn') {
maxCalls++;
if ((arg as {
type: 'fn';
isPersistent: true;
val: number;
}).isPersistent) {
isPersistent = true;
}
}
});
const onFinishFn = (status: 'success'|'error'|'chromeError', messageOrParams: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}|any, _stackTrace: string[]) => {
if (status === 'error' || status === 'chromeError') {
reject(new Error(messageOrParams.error));
} else {
const successMessage = messageOrParams as {
callbackId: number;
params: any[];
};
if (successMessage && typeof successMessage.callbackId === 'number') {
this.__this.__privates._callInfo.get(successMessage.callbackId).callback.apply(window, successMessage.params);
if (!this.__this.__privates._callInfo.get(successMessage.callbackId).persistent) {
this.__this.__privates._callInfo.remove(successMessage.callbackId);
}
} else {
resolve(messageOrParams);
}
}
}
const onFinish = {
maxCalls: maxCalls,
persistent: isPersistent,
fn: onFinishFn
};
const message = {
type: 'browser',
id: this.__this.__privates._id,
tabIndex: this.__this.__privates._tabIndex,
api: requestThis.request.api,
args: requestThis.request.chromeAPIArguments,
tabId: this.__this.__privates._tabData.id,
requestType: requestThis.request.type,
onFinish: onFinish
};
this.__this.__privates._sendMessage(message);
});
}
},
/**
* Uses given arguments as arguments for the API in order specified. If the argument is
* not a function, it is simply passed along, if it is, it's converted to a
* function that will preserve scope but is not passed to the chrome API itself.
* Instead a placeholder is passed that will take any arguments the chrome API passes to it
* and calls your fn function with local scope with the arguments the chrome API passed. Keep in
* mind that there is no connection between your function and the chrome API, the chrome API only
* sees a placeholder function with which it can do nothing so don't use this as say a forEach handler.
*/
_chromeRequest: class ChromeRequest implements ChromeRequestInterface {
request: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
onError?(error: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}): void;
};
returnedVal: ChromeRequestInterface;
constructor(public __this: CrmAPIInstance, api: string, type?: string) {
const request: {
api: string;
chromeAPIArguments: ({
type: 'fn';
isPersistent: boolean;
val: number;
}|{
type: 'arg';
val: string;
}|{
type: 'return';
val: number;
})[];
_sent: boolean;
type?: string;
onError?(error: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}): void;
} = {
api: api,
chromeAPIArguments: [],
_sent: false
};
this.request = request;
if (__this.warnOnChromeFunctionNotSent) {
window.setTimeout(() => {
if (!request._sent) {
console.warn('Looks like you didn\'t send your chrome function,' +
' set crmAPI.warnOnChromeFunctionNotSent to false to disable this message');
}
}, 5000);
}
Object.defineProperty(request, 'type', {
get: function () {
return type;
}
});
const returnVal: ChromeRequestInterface = CrmAPIInstance._helpers.mergeObjects((...args: any[]) => {
return this.a.bind(this)(...args);
}, {
a: this.a.bind(this),
args: this.args.bind(this),
r: this.r.bind(this),
return: this.return.bind(this),
p: this.p.bind(this),
persistent: this.persistent.bind(this),
send: this.send.bind(this),
s: this.s.bind(this),
request: this.request
});
this.returnedVal = returnVal;
return this.returnedVal as any;
}
new(__this: CrmAPIInstance, _api: string, _type?: string): ChromeRequest {
return this;
}
args(...args: any[]): ChromeRequestInterface {
for (let i = 0; i < args.length; i++) {
const arg = arguments[i];
if (typeof arg === 'function') {
this.request.chromeAPIArguments.push({
type: 'fn',
isPersistent: false,
val: this.__this.__privates._createCallback(arg, new Error(), {
maxCalls: 1
})
});
}
else {
this.request.chromeAPIArguments.push({
type: 'arg',
val: CrmAPIInstance._helpers.jsonFn.stringify(arg)
});
}
}
return this.returnedVal;
};
a(...args: any[]): ChromeRequestInterface {
return this.args(...args);
}
/**
* A function that is called with the value that the chrome API returned. This can
* be used for APIs that don't use callbacks and instead just return values such as
* chrome.runtime.getURL().
*/
return(handler: (...args: any[]) => void): ChromeRequestInterface {
this.request.chromeAPIArguments.push({
type: 'return',
val: this.__this.__privates._createCallback(handler, new Error(), {
maxCalls: 1
})
});
return this.returnedVal;
}
/**
* A function that is called with the value that the chrome API returned. This can
* be used for APIs that don't use callbacks and instead just return values such as
* chrome.runtime.getURL().
*/
r(handler: (...args: any[]) => void): ChromeRequestInterface {
return this.return(handler);
}
/**
* A function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
*/
persistent(...fns: any[]): ChromeRequestInterface {
for (let i = 0; i < fns.length; i++) {
this.request.chromeAPIArguments.push({
type: 'fn',
isPersistent: true,
val: this.__this.__privates._createCallback(fns[i], new Error(), {
persistent: true
})
});
}
return this.returnedVal;
}
p(...fns: any[]): ChromeRequestInterface {
return this.persistent(...fns);
}
/**
* Executes the request
*/
send() {
const requestThis = this;
this.request._sent = true;
let maxCalls = 0;
let isPersistent = false;
this.request.chromeAPIArguments.forEach((arg) => {
if (arg.type === 'fn' || arg.type === 'return') {
maxCalls++;
if ((arg as {
type: 'fn';
isPersistent: true;
val: number;
}).isPersistent) {
isPersistent = true;
}
}
});
function showStackTrace(messageOrParams: {
message: string;
stackTrace: string;
lineNumber: number;
}, stackTrace: string[]) {
if (messageOrParams.stackTrace) {
console.warn('Remote stack trace:');
messageOrParams.stackTrace.split('\n').forEach((line) => { console.warn(line); });
}
console.warn((messageOrParams.stackTrace ? 'Local s': 'S') + 'tack trace:');
stackTrace.forEach((line) => { console.warn(line); });
}
const onFinishFn = (status: 'success'|'error'|'chromeError', messageOrParams: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}|{
callbackId: number;
params: any[];
}, stackTrace: string[]) => {
if (status === 'error' || status === 'chromeError') {
const errMessage = messageOrParams as {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
};
if (this.request.onError) {
this.request.onError(errMessage);
} else if (this.__this.onError) {
this.__this.onError(errMessage);
}
if (this.__this.stackTraces) {
window.setTimeout(() => {
showStackTrace(errMessage, stackTrace);
}, 5);
}
if (this.__this.errors) {
throw new Error('CrmAPIError: ' + errMessage.error);
} else if (!this.__this.onError) {
console.warn('CrmAPIError: ' + errMessage.error);
}
} else {
const successMessage = messageOrParams as {
callbackId: number;
params: any[];
};
this.__this.__privates._callInfo.get(successMessage.callbackId).callback.apply(window, successMessage.params);
if (!this.__this.__privates._callInfo.get(successMessage.callbackId).persistent) {
this.__this.__privates._callInfo.remove(successMessage.callbackId);
}
}
}
const onFinish = {
maxCalls: maxCalls,
persistent: isPersistent,
fn: onFinishFn
};
const message = {
type: 'chrome',
id: this.__this.__privates._id,
tabIndex: this.__this.__privates._tabIndex,
api: requestThis.request.api,
args: requestThis.request.chromeAPIArguments,
tabId: this.__this.__privates._tabData.id,
requestType: requestThis.request.type,
onFinish: onFinish
};
this.__this.__privates._sendMessage(message);
return this.returnedVal;
}
s() {
return this.send();
}
},
_specialRequest(this: CrmAPIInstance, api: string, type: string) {
return new this.__privates._browserRequest(this, api, type);
},
//From https://gist.github.com/arantius/3123124
_setupRequestEvent(this: CrmAPIInstance, aOpts: {
method?: string,
url?: string,
headers?: { [headerKey: string]: string },
data?: any,
binary?: boolean,
timeout?: number,
context?: any,
responseType?: string,
overrideMimeType?: string,
anonymous?: boolean,
fetch?: boolean,
username?: string,
password?: string,
onload?: (e: Event) => void,
onerror?: (e: Event) => void,
onreadystatechange?: (e: Event) => void,
onprogress?: (e: Event) => void,
onloadstart?: (e: Event) => void,
ontimeout?: (e: Event) => void
}, aReq: XMLHttpRequest, aEventName: string) {
if (!aOpts[('on' + aEventName) as keyof typeof aOpts]) {
return;
}
aReq.addEventListener(aEventName, (aEvent) => {
const responseState: {
responseText: string;
responseXML: Document;
readyState: number;
responseHeaders: string;
status: number;
statusText: string;
finalUrl: string;
lengthComputable?: any;
loaded?: any;
total?: any;
} = {
responseText: aReq.responseText,
responseXML: aReq.responseXML,
readyState: aReq.readyState,
responseHeaders: null,
status: null,
statusText: null,
finalUrl: null
};
switch (aEventName) {
case 'progress':
responseState.lengthComputable = (aEvent as any).lengthComputable;
responseState.loaded = (aEvent as any).loaded;
responseState.total = (aEvent as any).total;
break;
case 'error':
break;
default:
if (4 !== aReq.readyState) {
break;
}
responseState.responseHeaders = aReq.getAllResponseHeaders();
responseState.status = aReq.status;
responseState.statusText = aReq.statusText;
break;
}
aOpts[('on' + aEventName) as keyof typeof aOpts](responseState);
});
},
/**
* Adds a listener for the notification with ID notificationId
*
* @param {number} notificationId - The id of te notification to listen for
* @param {number} onclick - The onclick handler for the notification
* @param {number} ondone - The onclose handler for the notification
*/
_addNotificationListener(this: CrmAPIInstance, notificationId: number, onclick: number, ondone: number) {
this.__privates._sendMessage({
id: this.__privates._id,
type: 'addNotificationListener',
data: {
notificationId: notificationId,
onClick: onclick,
tabIndex: this.__privates._tabIndex,
onDone: ondone,
id: this.__privates._id,
tabId: this.__privates._tabData.id
},
tabIndex: this.__privates._tabIndex,
tabId: this.__privates._tabData.id
});
},
_setGlobalFunctions(this: CrmAPIInstance) {
const GM = this.GM;
for (const gmKey in GM) {
if (GM.hasOwnProperty(gmKey)) {
const GMProperty = GM[gmKey as keyof typeof GM];
(window as any)[gmKey] = typeof GMProperty === 'function' ?
GMProperty.bind(this) : GMProperty;
}
}
(window as any).$ = (window as any).$ || this.$crmAPI as any;
(window as any).log = (window as any).log || this.log as any;
},
_storageGet(this: CrmAPIInstance, storageType: STORAGE_TYPE,
keyPath?: string|string[]|number[]): any {
const src = storageType === STORAGE_TYPE.SYNC ?
this.__privates._nodeStorageSync :
this.__privates._nodeStorage;
if (!keyPath) {
return src;
}
if (CrmAPIInstance._helpers.checkType(keyPath, 'string', true)) {
const keyPathString = keyPath;
if (typeof keyPathString === 'string') {
if (keyPathString.indexOf('.') === -1) {
return src[keyPathString];
}
else {
keyPath = keyPathString.split('.');
}
}
}
CrmAPIInstance._helpers.checkType(keyPath, 'array', 'keyPath');
if (Array.isArray(keyPath)) {
return CrmAPIInstance._helpers.lookup(keyPath, src);
}
},
_storageSet(this: CrmAPIInstance, storageType: STORAGE_TYPE,
keyPath: string|string[]|number[]|{
[key: string]: any;
[key: number]: any;
}, value?: any): void {
const src = storageType === STORAGE_TYPE.SYNC ?
this.__privates._nodeStorageSync :
this.__privates._nodeStorage;
if (CrmAPIInstance._helpers.checkType(keyPath, 'string', true)) {
const keyPathStr = keyPath;
if (typeof keyPathStr === 'string') {
if (keyPathStr.indexOf('.') === -1) {
this.__privates._localStorageChange(keyPath as string,
src[keyPathStr], value,
storageType);
src[keyPathStr] = value;
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
}
else {
keyPath = keyPathStr.split('.');
}
}
}
if (CrmAPIInstance._helpers.checkType(keyPath, 'array', true)) {
const keyPathArr = keyPath;
if (Array.isArray(keyPathArr)) {
//Lookup and in the meantime create object containers if new
let dataCont = src;
const length = keyPathArr.length - 1;
for (let i = 0; i < length; i++) {
if (dataCont[keyPathArr[i]] === undefined) {
dataCont[keyPathArr[i]] = {};
}
dataCont = dataCont[keyPathArr[i]];
}
this.__privates._localStorageChange(keyPathArr,
dataCont[keyPathArr[keyPathArr.length - 1]], value,
STORAGE_TYPE.LOCAL);
dataCont[keyPathArr[keyPathArr.length - 1]] = value;
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
}
}
CrmAPIInstance._helpers.checkType(keyPath, ['object'], 'keyPath');
const keyPathObj = keyPath;
if (typeof keyPathObj === 'object') {
for (const key in keyPathObj) {
if (keyPathObj.hasOwnProperty(key)) {
this.__privates._localStorageChange(key,
src[key], keyPathObj[key],
storageType);
src[key] = keyPathObj[key];
}
}
}
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
},
_storageRemove(this: CrmAPIInstance, storageType: STORAGE_TYPE,
keyPath: string|string[]|number[]): void {
const src = storageType === STORAGE_TYPE.SYNC ?
this.__privates._nodeStorageSync :
this.__privates._nodeStorage;
if (CrmAPIInstance._helpers.checkType(keyPath, 'string', true)) {
const keyPathStr = keyPath;
if (typeof keyPathStr === 'string') {
if (keyPathStr.indexOf('.') === -1) {
this.__privates._notifyChanges(
storageType, keyPathStr, src[keyPathStr], undefined);
delete src[keyPathStr];
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
}
else {
keyPath = keyPathStr.split('.');
}
}
}
if (CrmAPIInstance._helpers.checkType(keyPath, 'array', true)) {
const keyPathArr = keyPath;
if (Array.isArray(keyPathArr)) {
const data = CrmAPIInstance._helpers.lookup(keyPathArr, src, true);
this.__privates._notifyChanges(
storageType, keyPathArr.join('.'),
(data as any)[keyPathArr[keyPathArr.length - 1]], undefined);
delete (data as any)[keyPathArr[keyPathArr.length - 1]];
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
}
}
if (storageType === STORAGE_TYPE.SYNC) {
this.__privates._storagePreviousSync = src;
} else {
this.__privates._storagePrevious = src;
}
return undefined;
},
_addStorageOnChangeListener(this: CrmAPIInstance, storageType: STORAGE_TYPE,
listener: StorageChangeListener, key: string): number {
return this.__privates._storageListeners.add({
callback: listener,
type: storageType,
key: key
});
},
_removeStorageChangeListener(this: CrmAPIInstance, storageType: STORAGE_TYPE,
listener: StorageChangeListener|number, key: string): void {
if (typeof listener === 'number') {
this.__privates._storageListeners.remove(listener);
}
else {
this.__privates._storageListeners.forEach((storageListener, index) => {
if (storageListener.callback === listener &&
storageListener.type === storageType) {
if (key !== undefined) {
if (storageListener.key === key) {
this.__privates._storageListeners.remove(index);
}
} else {
this.__privates._storageListeners.remove(index);
}
}
});
}
}
}
/**
* Generates the class
*
* @param {Object} node - The item currently being edited
* @param {CRM.GenericNodeId} id - The id of the current item
* @param {Object} tabData - Any data about the tab the script is currently running on
* @param {Object} clickData - Any data associated with clicking this item in the
* context menu, only available if launchMode is equal to 0 (on click)
* @param {number[]} secretKey - An array of integers, generated to keep downloaded
* scripts from finding local scripts with more privilege and act as if they
* are those scripts to run stuff you don't want it to.
* @param {Object} nodeStorage - The storage data for the node
* @param {Object} contextData - The data related to the click on the page
* @param {Object} greasemonkeyData - Any greasemonkey data, including metadata
* @param {Boolean} isBackground - If true, this page is functioning as a background page
* @param {Object} options - The options the user has entered for this script/stylesheet
* @param {boolean} enableBackwardsCompatibility - Whether the localStorage object should reflect nodes
* @param {TabId} tabIndex - The index of this script (with this id) running on this tab
* @param {string} extensionId - The id of the extension
* @param {string} supportedAPIs - The supported browser APIs
* @param {CRM.NodeStorage} nodeStorageSync - Synced node storage
*/
constructor(node: CRM.Node, id: CRM.GenericNodeId, tabData: _browser.tabs.Tab,
clickData: _browser.contextMenus.OnClickData, secretKey: number[],
nodeStorage: CRM.NodeStorage, contextData: EncodedContextData,
greasemonkeyData: GreaseMonkeyData, isBackground: boolean,
options: CRM.Options, enableBackwardsCompatibility: boolean, tabIndex: TabId,
extensionId: string, supportedAPIs: string, nodeStorageSync: CRM.NodeStorage) {
this.__privates._node = node;
this.__privates._id = id;
this.__privates._tabData = tabData;
this.__privates._clickData = clickData;
this.__privates._secretKey = secretKey;
this.__privates._nodeStorage = nodeStorage;
this.__privates._contextData = contextData;
this.__privates._greasemonkeyData = greasemonkeyData;
this.__privates._isBackground = isBackground;
this.__privates._options = options;
this.__privates._enableBackwardsCompatibility = enableBackwardsCompatibility;
this.__privates._tabIndex = tabIndex;
this.__privates._extensionId = extensionId;
this.__privates._supportedAPIs = supportedAPIs;
this.__privates._nodeStorageSync = nodeStorageSync;
this.tabId = tabData.id;
this.currentTabIndex = tabIndex;
this.permissions = JSON.parse(JSON.stringify(node.permissions || []));
this.id = id;
this.isBackground = isBackground;
this.chromeAPISupported = supportedAPIs.split(',').indexOf('chrome') > -1;
this.browserAPISupported = supportedAPIs.split(',').indexOf('browser') > -1;
const privates = this.__privates;
Object.defineProperty(this, 'lastError', {
get: () => {
if (privates._lastError) {
privates._lastError.checked = true;
return privates._lastError.err;
}
return undefined;
}
});
this.__privates._findElementsOnPage.bind(this)(contextData);
this.__privates._setupBrowserAPI(this);
}
_init(enableBackwardsCompatibility: boolean) {
if (!enableBackwardsCompatibility) {
localStorageProxy = typeof localStorage === 'undefined' ? {} : localStorage;
}
this.__privates._setupStorages();
this.__privates._setGlobalFunctions();
this.__privates._connect();
}
/**
* When true, shows stacktraces on error in the console of the page
* the script runs on, true by default.
*
* @type boolean
*/
stackTraces: boolean = true;
/**
* If true, throws an error when one of your crmAPI calls is incorrect
* (such as a type mismatch or any other fail). True by default.
*
* @type boolean
*/
errors: boolean = true;
/**
* If true, when an error occurs anywhere in the script, opens the
* chrome debugger by calling the debugger command. This does
* not preserve the stack or values. If you want that, use the
* "catchErrors" option on the options page.
*
* @type boolean
*/
debugOnerror: boolean = false;
/**
* Is set if a chrome call triggered an error, otherwise unset
*
* @type Error
*/
lastError: Error = undefined;
/**
* If set, calls this function when an error occurs
*
* @type Function
*/
onError: (error: {
error: string;
message: string;
stackTrace: string;
lineNumber: number;
}) => void = null;
/**
* When true, warns you after 5 seconds of not sending a chrome function
* that you probably forgot to send it
*
* @type boolean
*/
warnOnChromeFunctionNotSent = true;
/**
* Returns the options for this script/stylesheet. Any missing values are
* filled in with the corresponding field in the 'defaults' param
*
* @param {Object} [defaults] - The default values of any key-value pairs
* @returns {Object} The options combined with the defaults
*/
options<T extends Object>(defaults?: T): T & CRM.Options {
return CrmAPIInstance._helpers.mergeObjects(defaults || {}, this.__privates._options) as T & CRM.Options;
}
/**
* The tab ID for the tab this script was executed on (0 if backgroundpage)
*
* @type {TabId}
*/
tabId: TabId;
/**
* The tab index for this tab relative to its parent window
*
* @type {TabIndex}
*/
currentTabIndex: TabIndex;
/**
* The ID of this instance of this script. Can be used to filter it
* from all instances or to send to another instance.
*
* @type {number}
*/
instanceId: number;
/**
* The permissions that are allowed for this script
*
* @type {string[]}
*/
permissions: CRM.Permission[];
/**
* The id of this script
*
* @type {CRM.GenericNodeId}
*/
id: CRM.GenericNodeId;
/**
* The context data for the click on the page (if any)
*
* @type {Object}
*/
contextData: RestoredContextData;
/**
* Whether this script is running on the backgroundpage
*
* @type {boolean}
*/
isBackground: boolean;
/**
* Whether the chrome API is supported (it's running in a chrome browser)
*
* @type {boolean}
*/
chromeAPISupported: boolean;
/**
* Whether the browser API is supported
*
* @type {boolean}
*/
browserAPISupported: boolean;
/**
* Registers a function to be called
* when all CRM classes have been handled
*
* @param {function} callback - The function to be called
* when the CRM classes have been handled
*/
onReady(callback: () => void) {
if (window._crmAPIRegistry.length === 0) {
callback();
} else {
let called: boolean = false;
const previousPop = window._crmAPIRegistry.pop.bind(window._crmAPIRegistry);
window._crmAPIRegistry.pop = () => {
const retVal = previousPop();
if (window._crmAPIRegistry.length === 0) {
!called && callback && callback();
called = true;
}
return retVal;
}
}
}
@makePrivate
private static _helpers = class Helpers {
/**
* JSONfn - javascript (both node.js and browser) plugin to stringify,
* parse and clone objects with Functions, Regexp and Date.
*
* Version - 0.60.00
* Copyright (c) 2012 - 2014 Vadim Kiryukhin
* vkiryukhin @ gmail.com
* http://www.eslinstructor.net/jsonfn/
*
* Licensed under the MIT license ( http://www.opensource.org/licenses/mit-license.php )
*/
static jsonFn = {
stringify: function (obj: any): string {
return JSON.stringify(obj, function (_key, value) {
if (value instanceof Function || typeof value === 'function') {
return value.toString();
}
if (value instanceof RegExp) {
return '_PxEgEr_' + value;
}
return value;
});
},
parse: function (str: string, date2Obj?: boolean): any {
const iso8061 = date2Obj ? /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d *)?)Z$/ : false;
return JSON.parse(str, function (_key, value) {
if (typeof value !== 'string') {
return value;
}
if (value.length < 8) {
return value;
}
const prefix = value.substring(0, 8);
if (iso8061 && value.match(iso8061 as any)) {
return new Date(value);
}
if (prefix === 'function') {
return new Function(value);
}
if (prefix === '_PxEgEr_') {
return new RegExp(value.slice(8));
}
return value;
});
}
}
static specialJSON = {
_regexFlagNames: ['global', 'multiline', 'sticky', 'unicode', 'ignoreCase'],
_getRegexFlags(this: SpecialJSON, expr: RegExp): string[] {
const flags: string[] = [];
this._regexFlagNames.forEach((flagName: string) => {
if ((expr as any)[flagName]) {
if (flagName === 'sticky') {
flags.push('y');
} else {
flags.push(flagName[0]);
}
}
});
return flags;
},
_stringifyNonObject(this: SpecialJSON, data: string | number | Function | RegExp | Date | boolean): string {
if (typeof data === 'function') {
const fn = data.toString();
const match = this._fnRegex.exec(fn);
data = `__fn$${`(${match[2]}){${match[10]}}`}$fn__`;
} else if (data instanceof RegExp) {
data = `__regexp$${JSON.stringify({
regexp: (data as RegExp).source,
flags: this._getRegexFlags(data)
})}$regexp__`;
} else if (data instanceof Date) {
data = `__date$${data + ''}$date__`;
} else if (typeof data === 'string') {
data = (data as string).replace(/\$/g, '\\$');
}
return JSON.stringify(data);
},
_fnRegex: /^(.|\s)*\(((\w+((\s*),?(\s*)))*)\)(\s*)(=>)?(\s*)\{((.|\n|\r)+)\}$/,
_specialStringRegex: /^__(fn|regexp|date)\$((.|\n)+)\$\1__$/,
_fnCommRegex: /^\(((\w+((\s*),?(\s*)))*)\)\{((.|\n|\r)+)\}$/,
_parseNonObject(this: SpecialJSON, data: string): string | number | Function | RegExp | Date | boolean {
const dataParsed = JSON.parse(data);
if (typeof dataParsed === 'string') {
let matchedData: RegExpExecArray;
if ((matchedData = this._specialStringRegex.exec(dataParsed))) {
const dataContent = matchedData[2];
switch (matchedData[1]) {
case 'fn':
const fnRegexed = this._fnCommRegex.exec(dataContent);
if (fnRegexed[1].trim() !== '') {
return Function(...fnRegexed[1].split(','), fnRegexed[6]);
} else {
return new Function(fnRegexed[6]);
}
case 'regexp':
const regExpParsed = JSON.parse(dataContent);
return new RegExp(regExpParsed.regexp, regExpParsed.flags.join(''));
case 'date':
return new Date();
}
} else {
return dataParsed.replace(/\\\$/g, '$');
}
}
return dataParsed;
},
_iterate(this: SpecialJSON, copyTarget: ArrOrObj, iterable: ArrOrObj,
fn: (data: any, index: string | number, container: ArrOrObj) => any) {
if (Array.isArray(iterable)) {
copyTarget = copyTarget || [];
(iterable as any[]).forEach((data: any, key: number, container: any[]) => {
(copyTarget as any)[key] = fn(data, key, container);
});
} else {
copyTarget = copyTarget || {};
Object.getOwnPropertyNames(iterable).forEach((key) => {
(copyTarget as any)[key] = fn(iterable[key], key, iterable);
});
}
return copyTarget;
},
_isObject(this: SpecialJSON, data: any): boolean {
if (data instanceof Date || data instanceof RegExp || data instanceof Function) {
return false;
}
return typeof data === 'object' && !Array.isArray(data);
},
_toJSON(this: SpecialJSON, copyTarget: ArrOrObj, data: any, path: (string|number)[], refData: {
refs: Refs,
paths: (string|number)[][],
originalValues: any[]
}): {
refs: Refs;
data: any[];
rootType: 'array';
} | {
refs: Refs;
data: {
[key: string]: any;
};
rootType: 'object';
} | {
refs: Refs;
data: string;
rootType: 'normal';
} {
if (!(this._isObject(data) || Array.isArray(data))) {
return {
refs: [],
data: this._stringifyNonObject(data),
rootType: 'normal'
};
} else {
if (refData.originalValues.indexOf(data) === -1) {
const index = refData.refs.length;
refData.refs[index] = copyTarget;
refData.paths[index] = path;
refData.originalValues[index] = data;
}
copyTarget = this._iterate(copyTarget, data, (element: any, key: string | number) => {
if (!(this._isObject(element) || Array.isArray(element))) {
return this._stringifyNonObject(element);
} else {
let index: number;
if ((index = refData.originalValues.indexOf(element)) === -1) {
index = refData.refs.length;
copyTarget = (Array.isArray(element) ? [] : {});
//Filler
refData.refs.push(null);
refData.paths[index] = path;
const newData = this._toJSON((copyTarget as any)[key as keyof typeof copyTarget], element, path.concat(key), refData);
refData.refs[index] = newData.data;
refData.originalValues[index] = element;
}
return `__$${index}$__`;
}
});
const isArr = Array.isArray(data);
if (isArr) {
return {
refs: refData.refs,
data: copyTarget as any[],
rootType: 'array'
};
} else {
return {
refs: refData.refs,
data: copyTarget as {
[key: string]: any;
},
rootType: 'object'
};
}
}
},
toJSON(this: SpecialJSON, data: any, noJSON: boolean = false, refs: Refs = []): {
json: string|SpecialJSONObject;
originalValues: any[];
} {
const paths: (string|number)[][] = [[]];
const originalValues = [data];
if (!(this._isObject(data) || Array.isArray(data))) {
const returnObj: SpecialJSONObject = {
refs: [],
data: this._stringifyNonObject(data),
rootType: 'normal',
paths: []
};
return {
json: noJSON ? returnObj : JSON.stringify(returnObj),
originalValues: originalValues
}
} else {
let copyTarget = (Array.isArray(data) ? [] : {});
refs.push(copyTarget);
copyTarget = this._iterate(copyTarget, data, (element: any, key: string | number) => {
if (!(this._isObject(element) || Array.isArray(element))) {
return this._stringifyNonObject(element);
} else {
let index: number;
if ((index = originalValues.indexOf(element)) === -1) {
index = refs.length;
//Filler
refs.push(null);
const newData = this._toJSON((copyTarget as any)[key], element, [key], {
refs: refs,
paths: paths,
originalValues: originalValues
}).data;
originalValues[index] = element;
paths[index] = [key];
refs[index] = newData;
}
return `__$${index}$__`;
}
});
const returnObj: SpecialJSONObject = {
refs: refs,
data: copyTarget,
rootType: Array.isArray(data) ? 'array' : 'object',
paths: paths
};
return {
json: noJSON ? returnObj : JSON.stringify(returnObj),
originalValues: originalValues
}
}
},
_refRegex: /^__\$(\d+)\$__$/,
_replaceRefs(this: SpecialJSON, data: ArrOrObj, refs: ParsingRefs): ArrOrObj {
this._iterate(data, data, (element: string) => {
let match: RegExpExecArray;
if ((match = this._refRegex.exec(element))) {
const refNumber = match[1];
const ref = refs[~~refNumber];
if (ref.parsed) {
return ref.ref;
}
ref.parsed = true;
return this._replaceRefs(ref.ref, refs);
} else {
return this._parseNonObject(element);
}
});
return data;
},
fromJSON(this: SpecialJSON, str: string): any {
const parsed: {
refs: Refs;
data: any;
rootType: 'normal' | 'array' | 'object';
} = JSON.parse(str);
parsed.refs = parsed.refs.map((ref) => {
return {
ref: ref,
parsed: false
};
});
const refs = parsed.refs as {
ref: any[] | {
[key: string]: any
};
parsed: boolean;
}[];
if (parsed.rootType === 'normal') {
return JSON.parse(parsed.data);
}
refs[0].parsed = true;
return this._replaceRefs(refs[0].ref, refs as ParsingRefs);
}
}
static CallbackStorage = class CallbackStorage<T> implements CallbackStorageInterface<T> {
constructor() {
this.items = {};
this.index = 0;
}
private items: {
[key: number]: T;
}
private index: number;
private _updateLength() {
let length = 0;
this.forEach(() => {
length++;
});
this.length = length;
}
add(item: T): number {
this.items[++this.index] = item;
this._updateLength();
return this.index;
}
remove(itemOrIndex: T|number) {
if (typeof itemOrIndex === 'number' || typeof itemOrIndex === 'string') {
delete this.items[~~itemOrIndex];
} else {
for (let fnId in this.items) {
if (this.items[fnId] === itemOrIndex) {
delete this.items[fnId];
}
}
}
this._updateLength();
}
get(index: number): T {
return this.items[index];
}
forEach(operation: (target: T, index: number) => void) {
for (let fnId in this.items) {
operation(this.items[fnId], (fnId as any) as number);
}
}
length: number = 0;
}
/**
* Checks whether value matches given type and is defined and not null,
* third parameter can be either a string in which case it will be
* mentioned in the error message, or it can be a boolean which if
* true will prevent an error message and instead just returns a
* success or no success boolean.
*
* @param {*} value The value to check
* @param {string} type - The type that the value should be
* @param {string|boolean} nameOrMode If a string, the name of the value to check (shown in error message),
* if a boolean and true, turns on non-error-mode
* @returns {boolean} - Whether the type matches
*/
static checkType(value: any, type: ModifiedSymbolTypes|ModifiedSymbolTypes[], nameOrMode: string|true): boolean {
let typeArray: ModifiedSymbolTypes[];
if (!Array.isArray(type)) {
typeArray = [type];
}
else {
typeArray = type;
}
if (typeof nameOrMode === 'boolean' && nameOrMode) {
return (
value !== undefined && value !== null &&
(
(typeArray.indexOf(typeof value) > -1 && !value.splice) ||
(typeArray.indexOf('array') > -1 && typeof value === 'object' && value.splice)
)
);
}
if (value === undefined || value === null) {
throw new Error('Value ' + (nameOrMode ? 'of ' + nameOrMode : '') + ' is undefined or null');
}
if (!((typeArray.indexOf(typeof value) > -1 && !value.splice) ||
(typeArray.indexOf('array') > -1 && typeof value === 'object' && value.splice))) {
throw new Error('Value ' + (nameOrMode ? 'of ' + nameOrMode : '') + ' is not of type' + ((typeArray.length > 1) ? 's ' + typeArray.join(', ') : ' ' + typeArray));
}
return true;
}
/**
* Looks up the data at given path
*
* @param {array} path - The path at which to look
* @param {Object} data - The data to look at
* @param {boolean} hold - Whether to return the second-to-last instead of the last data
* @returns {*} The found value
*/
static lookup<T extends {
[key: string]: T|U;
[key: number]: T|U;
}, U>(path: (string|number)[], data: T, hold: boolean = false): T|U {
this.checkType(path, 'array', 'path');
this.checkType(data, 'object', 'data');
let length = path.length;
hold && length--;
let dataChild: T|U = data;
for (let i = 0; i < length; i++) {
if (!(dataChild as T)[path[i]] && (i + 1) !== length) {
((dataChild as T)[path[i] as keyof T] as any) = {} as T|U;
}
dataChild = (dataChild as T)[path[i]];
}
return dataChild as U;
}
static emptyFn = function () { };
/**
* Returns the function if the function was actually a function and exists
* returns an empty function if it's not
*
* @param {any} fn - The function to check
* @returns {boolean} - Whether given data is a function
*/
static isFn<T extends Function>(fn: T): fn is T {
return fn && typeof fn === 'function';
}
static mergeArrays<T extends T[] | U[], U>(mainArray: T, additionArray: T): T {
for (let i = 0; i < additionArray.length; i++) {
if (mainArray[i] && typeof additionArray[i] === 'object' &&
mainArray[i] !== undefined && mainArray[i] !== null) {
if (Array.isArray(additionArray[i])) {
mainArray[i] = this.mergeArrays(mainArray[i] as T,
additionArray[i] as T);
} else {
mainArray[i] = this.mergeObjects(mainArray[i], additionArray[i]);
}
} else {
mainArray[i] = additionArray[i];
}
}
return mainArray;
}
static mergeObjects<T extends {
[key: string]: any;
[key: number]: any;
}, Y extends Partial<T> & Object>(mainObject: T, additions: Y): T & Y {
for (const key in additions) {
if (additions.hasOwnProperty(key)) {
if (typeof additions[key] === 'object' &&
key in mainObject) {
if (Array.isArray(additions[key])) {
mainObject[key] = this.mergeArrays(mainObject[key], additions[key] as any);
} else {
mainObject[key] = this.mergeObjects(mainObject[key], additions[key] as any);
}
} else {
mainObject[key] = additions[key] as any
}
}
}
return mainObject as T & Y;
}
static instantCb(cb: Function) {
cb();
}
}
/**
* The communications API used to communicate with other scripts and other instances
*
* @type Object
*/
comm = {
/**
* Returns all instances running in other tabs, these instances can be passed
* to the .comm.sendMessage function to send a message to them, you can also
* call instance.sendMessage on them
*
* @param {function} [callback] - A function to call with the instances
* @returns {Promise<CommInstance[]>} A promise that resolves with the instances
*/
getInstances(this: CrmAPIInstance, callback?: (instances: CommInstance[]) => void): Promise<CommInstance[]> {
return new Promise<CommInstance[]>((resolve) => {
if (this.__privates._instancesReady) {
const instancesArr: CommInstance[] = [];
this.__privates._instances.forEach((instance) => {
instancesArr.push(instance);
});
callback && callback(instancesArr);
resolve(instancesArr);
} else {
this.__privates._instancesReadyListeners.push((instances) => {
callback && callback(instances);
resolve(instances);
});
}
});
},
/**
* Sends a message to given instance
*
* @param {CommInstance|number} instance - The instance to send the message to
* @param {Object} message - The message to send
* @param {function} [callback] - A callback that tells you the result,
* gets passed one argument (object) that contains the two boolean
* values "error" and "success" indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
* @returns {InstanceCallback} A promise that resolves with the result,
* an object that contains the two boolean
* values `error` and `success` indicating whether the message
* succeeded. If it did not succeed and an error occurred,
* the message key of that object will be filled with the reason
* it failed ("instance no longer exists" or "no listener exists")
*/
sendMessage(this: CrmAPIInstance, instance: CommInstance|number, message: any, callback?: InstanceCallback): Promise<InstanceCallback> {
let instanceObj: CommInstance;
if ((callback !== undefined && typeof callback !== 'function' && typeof message === 'number') || arguments.length === 4) {
//Third parameter is the message and second parameter is the tabIndex
message = callback;
callback = arguments[3];
}
if (typeof instance === "number") {
instanceObj = this.__privates._instances.get(instance);
} else {
instanceObj = instance;
}
return new Promise<any>((resolve) => {
if (CrmAPIInstance._helpers.isFn(instanceObj.sendMessage)) {
instanceObj.sendMessage(message, (response: any) => {
callback && callback(response);
resolve(response);
});
}
});
},
/**
* Adds a listener for any comm-messages sent from other instances of
* this script
*
* @param {function} listener - The listener that gets called with the message
* @returns {number} An id that can be used to remove the listener
*/
addListener(this: CrmAPIInstance, listener: InstanceListener): number {
const prevLength = this.__privates._commListeners.length;
const idx = this.__privates._commListeners.add(listener);
if (prevLength === 0) {
this.__privates._updateCommHandlerStatus(true);
}
return idx;
},
/**
* Removes a listener currently added by using comm.addListener
*
* @param {listener|number} listener - The listener to remove or the number returned
* by adding it.
*/
removeListener(this: CrmAPIInstance, listener: number|InstanceListener) {
this.__privates._commListeners.remove(listener);
if (this.__privates._commListeners.length === 0) {
this.__privates._updateCommHandlerStatus(false);
}
},
/**
* Sends a message to the background page for this script
*
* @param {any} message - The message to send
* @param {Function} callback - A function to be called with a response
* @returns {Promise<any>} A promise that resolves with the response
*/
messageBackgroundPage(this: CrmAPIInstance, message: any, callback: InstanceListener): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (this.__privates._isBackground) {
reject('The function messageBackgroundPage is not available in background pages');
} else {
this.__privates._sendMessage({
id: this.__privates._id,
type: 'sendBackgroundpageMessage',
data: {
message: message,
id: this.__privates._id,
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
response: this.__privates._createCallbackFunction((response: any) => {
callback(response);
resolve(response);
}, new Error(), {
maxCalls: 1
})
},
tabIndex: this.__privates._tabIndex,
tabId: this.__privates._tabData.id
});
}
});
},
/**
* Listens for any messages to the background page
*
* @param {Function} callback - The function to call on message.
* Contains the message and the respond params respectively.
* Calling the respond param with data sends a message back.
*/
listenAsBackgroundPage(this: CrmAPIInstance, callback: InstanceListener) {
if (this.__privates._isBackground) {
this.__privates._backgroundPageListeners.add(callback);
} else {
this.log('The function listenAsBackgroundPage is not available in non-background script');
}
}
};
/**
* The storage API used to store and retrieve data for this script
*
* @type Object
*/
storage = {
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {string|array} [keyPath] - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, or just a plain string without dots as the key,
* can also hold nothing to return the entire storage
* @returns {any} - The data you are looking for
*/
get(this: CrmAPIInstance, keyPath?: string|string[]|number[]): any {
return this.__privates._storageGet(STORAGE_TYPE.LOCAL,
keyPath);
},
/**
* Sets the data at given key to given value
*
* @param {string|array|Object} keyPath - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, a plain string without dots as the key or
* an object. This object will be written on top of the storage object
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(this: CrmAPIInstance, keyPath: string|string[]|number[]|{
[key: string]: any;
[key: number]: any;
}, value?: any): void {
return this.__privates._storageSet(STORAGE_TYPE.LOCAL,
keyPath, value);
},
/**
* Deletes the data at given key given value
*
* @param {string|array} keyPath - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, or just a plain string without dots as the key
*/
remove(this: CrmAPIInstance, keyPath: string|string[]|number[]): void {
return this.__privates._storageRemove(STORAGE_TYPE.LOCAL,
keyPath);
},
/**
* Functions related to the onChange event of the storage API
*
* @type Object
*/
onChange: {
/**
* Adds an onchange listener for the storage, listens for a key if given
*
* @param {function} listener - The function to run, gets called
* gets called with the first argument being the key, the second being
* the old value, the third being the new value and the fourth
* a boolean indicating if the change was on a remote tab
* @param {string} [key] - The key to listen for, if it's nested separate it by dots
* like a.b.c
* @returns {number} A number that can be used to remove the listener
*/
addListener(this: CrmAPIInstance, listener: StorageChangeListener, key?: string): number {
return this.__privates._addStorageOnChangeListener(
STORAGE_TYPE.LOCAL, listener, key);
},
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {function|number} listener - The listener to remove or the number to
* to remove it.
* @param {string} [key] - The key to check
*/
removeListener(this: CrmAPIInstance, listener: StorageChangeListener|number, key: string) {
this.__privates._removeStorageChangeListener(
STORAGE_TYPE.LOCAL, listener, key);
}
}
};
/**
* The synced storage API used to store and retrieve data for this script across
* browser instances
*
* @type Object
*/
storageSync = {
/**
* Gets the value at given key, if no key is given returns the entire storage object
*
* @param {string|array} [keyPath] - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, or just a plain string without dots as the key,
* can also hold nothing to return the entire storage
* @returns {any} - The data you are looking for
*/
get(this: CrmAPIInstance, keyPath?: string|string[]|number[]): any {
return this.__privates._storageGet(STORAGE_TYPE.SYNC,
keyPath);
},
/**
* Sets the data at given key to given value
*
* @param {string|array|Object} keyPath - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, a plain string without dots as the key or
* an object. This object will be written on top of the storage object
* @param {any} [value] - The value to set it to, optional if keyPath is an object
*/
set(this: CrmAPIInstance, keyPath: string|string[]|number[]|{
[key: string]: any;
[key: number]: any;
}, value?: any): void {
return this.__privates._storageSet(STORAGE_TYPE.SYNC,
keyPath, value);
},
/**
* Deletes the data at given key given value
*
* @param {string|array} keyPath - The path at which to look, can be either
* a string with dots separating the path, an array with each entry holding
* one section of the path, or just a plain string without dots as the key
*/
remove(this: CrmAPIInstance, keyPath: string|string[]|number[]): void {
return this.__privates._storageRemove(STORAGE_TYPE.SYNC,
keyPath);
},
/**
* Functions related to the onChange event of the storage API
*
* @type Object
*/
onChange: {
/**
* Adds an onchange listener for the storage, listens for a key if given
*
* @param {function} listener - The function to run, gets called
* gets called with the first argument being the key, the second being
* the old value, the third being the new value and the fourth
* a boolean indicating if the change was on a remote tab
* @param {string} [key] - The key to listen for, if it's nested separate it by dots
* like a.b.c
* @returns {number} A number that can be used to remove the listener
*/
addListener(this: CrmAPIInstance, listener: StorageChangeListener, key?: string) {
return this.__privates._addStorageOnChangeListener(
STORAGE_TYPE.SYNC, listener, key);
},
/**
* Removes ALL listeners with given listener (function) as the listener,
* if key is given also checks that they have that key
*
* @param {function|number} listener - The listener to remove or the number to
* to remove it.
* @param {string} [key] - The key to check
*/
removeListener(this: CrmAPIInstance, listener: StorageChangeListener|number, key: string) {
this.__privates._removeStorageChangeListener(
STORAGE_TYPE.SYNC, listener, key);
}
}
};
/**
* The contextMenuItem API which controls the look of this contextmenu item
* None of these changes are persisted to the source node and only affect
* the properties of the contextmenu item this session.
*
* @type Object
*/
contextMenuItem = {
/**
* Set the type of this contextmenu item. Options are "normal" for a regular one,
* "checkbox" for one that can be checked, "radio" for one of many that can be
* checked and "separator" for a divider line. Is not saved across sessions.
*
* @param {CRM.ContextMenuItemType} itemType - The type to set it to
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setType(this: CrmAPIInstance, itemType: CRM.ContextMenuItemType, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setType', {
itemType,
allTabs
});
},
/**
* Sets whether this item should be checked or not. If the contextmenu item type is either
* "normal" or "separator", the type is first changed to "checkbox".
* Is not saved across sessions.
*
* @param {boolean} checked - Whether it should be checked
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setChecked(this: CrmAPIInstance, checked: boolean, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setChecked', {
checked,
allTabs
});
},
/**
* Sets the content types on which this item should appear. This is an array
* containing the types it should appear on. It will not appear on types that
* are not in the array. Possible values are "page", "link", "selection",
* "image", "video" and "audio". Is not saved across sessions.
*
* @param {CRM.ContentTypeString[]} contentTypes - The content types it should appear on
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setContentTypes(this: CrmAPIInstance, contentTypes: CRM.ContentTypeString[], allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setContentTypes', {
contentTypes,
allTabs
});
},
/**
* Sets whether this item should be visible or not. This is only available in
* chrome 62 and above (no other browsers), won't throw an error if
* executed on a different browser/version. If this node is invisible by default
* (for example run on specified), this won't do anything and throw an error.
* Is not saved across sessions.
*
* @param {boolean} isVisible - Whether it should be visible
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setVisibility(this: CrmAPIInstance, isVisible: boolean, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setVisibility', {
isVisible,
allTabs
});
},
/**
* Sets whether this item should be disabled or not. A disabled node
* is simply greyed out and can not be clicked. Is not saved across sessions.
*
* @param {boolean} isDisabled - Whether it should be disabled
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setDisabled(this: CrmAPIInstance, isDisabled: boolean, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setDisabled', {
isDisabled,
allTabs
});
},
/**
* Changes the display name of this item (can't be empty).
* Requires the "crmContextmenu" permission in order to prevent nodes from
* pretending to be other nodes. Can be reset to the default name by calling
* crmAPI.contextMenuItem.resetName. Is not saved across sessions.
*
* @permission crmContextmenu
* @param {string} name - The new name
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
setName(this: CrmAPIInstance, name: string, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.setName', {
name,
allTabs
});
},
/**
* Resets the name to the original node name.
*
* @param {boolean} [allTabs] - Whether to apply this change to all tabs, defaults to false
* @returns {Promise<void>} A promise that resolves with nothing and throws if something
* went wrong
*/
resetName(this: CrmAPIInstance, allTabs: boolean = false): Promise<void> {
return this.__privates._sendPromiseMessage.call(this,
'contextMenuItem.resetName', {
allTabs
});
},
};
/**
* Gets the current text selection
*
* @returns {string} - The current selection
*/
getSelection(): string {
return (this.__privates._clickData.selectionText || window.getSelection() && window.getSelection().toString()) || '';
};
/**
* All of the remaining functions in this region below this message will only work if your
* script runs on clicking, not if your script runs automatically, in that case you will always
* get undefined (except for the function above). For more info check out this page's onclick
* section (https://developer.chrome.com/extensions/contextMenus#method-create)
*/
/**
* Returns any data about the click on the page, check (https://developer.chrome.com/extensions/contextMenus#method-create)
* for more info of what can be returned.
*
* @returns {Object} - An object containing any info about the page, some data may be undefined if it doesn't apply
*/
getClickInfo(): _browser.contextMenus.OnClickData {
return this.__privates._clickData;
};
/**
* Gets any info about the current tab/window
*
* @returns {Object} - An object of type tab (https://developer.chrome.com/extensions/tabs#type-Tab)
*/
getTabInfo(): _browser.tabs.Tab {
return this.__privates._tabData;
};
/**
* Gets the current node
*
* @returns {Object} - The node that is being executed right now
*/
getNode(): CRM.Node {
return this.__privates._node;
};
/**
* The value of a standard node, all nodes inherit from this
*
* @typedef {Object} CrmNode
* @property {Number} id - The ID of the node
* @property {Number} index - The index of the node in its parent's children
* @property {string} name - The name of the node
* @property {string} type - The type of the node (link, script, menu or divider)
* @property {CrmNode[]} children - The children of the object, only possible if type is menu and permission "CRM" is present
* @property {Object} nodeInfo - Any info about the node, it's author and where it's downloaded from
* @property {string} nodeInfo.installDate - The date on which the node was installed or created
* @property {boolean} nodeInfo.isRoot - Whether the node is downloaded (false) or created locally (true)
* @property {string[]} nodeInfo.permissions - Permissions required by the node on install
* @property {string|Object} nodeInfo.source - 'Local' if the node is non-remotely or created here,
* object if it IS remotely installed
* @property {string} nodeInfo.source.url - The url that the node was installed from
* @property {string} nodeInfo.source.author - The author of the node
* @property {Number[]} path - The path to the node from the tree's root
* @property {boolean[]} onContentTypes - The content types on which the node is visible
* there's 6 slots, for each slot true indicates it's shown and false indicates it's hidden
* on that content type, the content types are 'page','link','selection','image','video' and 'audio'
* respectively
* @property {string[]} permissions - The permissions required by this script
* @property {Object[]} triggers - The triggers for which to run this node
* @property {string} triggers.url - The URL of the site on which to run,
* if launchMode is 2 aka run on specified pages can be any of these
* https://wiki.greasespot.net/Include_and_exclude_rules
* otherwise the url should match this pattern, even when launchMode does not exist on the node (links etc)
* https://developer.chrome.com/extensions/match_patterns
* @property {boolean} triggers.not - If true does NOT run on given site
* @property {LinkVal} linkVal - The value of the node if it were to switch to type link
* @property {ScriptVal} scriptVal - The value of the node if it were to switch to type script
* @property {StylesheetVal} stylesheetVal - The value fo the node if it were to switch to type stylesheet
* @property {Object[]} menuVal - The children of the node if it were to switch to type menu
*/
/**
* The properties of a node if it's of type link
*
* @augments CrmNode
* @typedef {Object[]} LinkVal
* @property {Object[]} value - The links in this link-node
* @property {string} value.url - The URL to open
* @property {boolean} value.newTab - True if the link is opened in a new tab
* @property {boolean} showOnSpecified - Whether the triggers are actually used, true if they are
*/
/**
* The properties of a node if it's of type script
*
* @augments CrmNode
* @typedef {Object} ScriptVal
* @property {Object} value - The value of this script-node
* @property {Number} value.launchMode - When to launch the script,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @property {string} value.script - The script for this node
* @property {string} value.backgroundScript - The backgroundscript for this node
* @property {Object} value.metaTags - The metaTags for the script, keys are the metaTags, values are
* arrays where each item is one instance of the key-value pair being in the metatags
* @property {Object[]} value.libraries - The libraries that are used in this script
* @property {script} value.libraries.name - The name of the library
* @property {Object[]} value.backgroundLibraries - The libraries that are used in the background page
* @property {script} value.backgroundLibraries.name - The name of the library
*/
/**
* The properties of a node if it's of type stylesheet
*
* @augments CrmNode
* @typedef {Object} StylesheetVal
* @property {Object} value - The value of this stylesheet
* @property {Number} value.launchMode - When to launch the stylesheet,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @property {string} value.stylesheet - The script that is ran itself
* @property {boolean} value.toggle - Whether the stylesheet is always on or toggle-able by clicking (true = toggle-able)
* @property {boolean} value.defaultOn - Whether the stylesheet is on by default or off, only used if toggle is true
*/
/**
* The properties of a node if it's of type menu
*
* @augments CrmNode
* @typedef {Object} MenuVal
* @property {boolean} showOnSpecified - Whether the triggers are actually used, true if they are
*/
/**
* The properties of a node if it's of type divider
*
* @augments CrmNode
* @typedef {Object} DividerVal
* @property {boolean} showOnSpecified - Whether the triggers are actually used, true if they are
*/
/**
* This callback is called on most crm functions
*
* @callback CrmCallback
* @param {CrmNode} node - The node that has been processed/retrieved
*/
/**
* The crm API, used to make changes to the crm, some API calls may require permissions crmGet and crmWrite
*
* @type Object
*/
crm = {
/**
* Gets the root contextmenu ID (used by browser.contextMenus).
* Keep in mind that this is not a node id. See:
* https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/menus
*
* @param {function} [callback] - A function that is called with
* the contextmenu ID as an argument
* @returns {Promise<string|number>} A promise that resolves with the ID
*/
getRootContextMenuId(this: CrmAPIInstance, callback?: (contextMenuId: string|number) => void): Promise<string|number> {
return this.__privates._sendCrmMessage('crm.getRootContextMenuId', callback);
},
/**
* Gets the CRM tree from the tree's root
*
* @permission crmGet
* @param {function} [callback] - A function that is called when done with the data as an argument
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the tree
*/
getTree(this: CrmAPIInstance, callback?: (data: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]> {
return this.__privates._sendCrmMessage('crm.getTree', callback);
},
/**
* Gets the CRM's tree from either the root or from the node with ID nodeId
*
* @permission crmGet
* @param {number} nodeId - The ID of the subtree's root node
* @param {function} [callback] - A function that is called when done with the data as an argument
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the subtree
*/
getSubTree(this: CrmAPIInstance, nodeId: number, callback?: (data: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]> {
return this.__privates._sendCrmMessage('crm.getSubTree', callback, {
nodeId: nodeId
});
},
/**
* Gets the node with ID nodeId
*
* @permission crmGet
* @param {CrmCallback} [callback] - A function that is called when done
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
getNode(this: CrmAPIInstance, nodeId: number, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendCrmMessage('crm.getNode', callback, {
nodeId: nodeId
});
},
/**
* Gets a node's ID from a path to the node
*
* @permission crmGet
* @param {number[]} path - An array of numbers representing the path, each number
* represents the n-th child of the current node, so [1,2] represents the 2nd item(0,>1<,2)'s third child (0,1,>2<,3)
* @param {function} [callback] - The function that is called with the ID as an argument
* @returns {Promise<number>} A promise that resolves with the ID
*/
getNodeIdFromPath(this: CrmAPIInstance, path: number[], callback?: (id: number) => void): Promise<number> {
return this.__privates._sendCrmMessage('crm.getNodeIdFromPath', callback, {
path: path
});
},
/**
* Queries the CRM for any items matching your query
*
* @permission crmGet
* @param {crmCallback} callback - The function to call when done, returns one array of results
* @param {Object} query - The query to look for
* @param {string} [query.name] - The name of the item
* @param {string} [query.type] - The type of the item (link, script, stylesheet, divider or menu)
* @param {number} [query.inSubTree] - The subtree in which this item is located (the number given is the id of the root item)
* @param {CrmCallback} [callback] - A callback with the resulting nodes in an array
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the resulting nodes
*/
queryCrm(this: CrmAPIInstance, query: { name?: string, type?: CRM.NodeType, inSubTree?: number},
callback?: (results: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]> {
return this.__privates._sendCrmMessage('crm.queryCrm', callback, {
query: query
});
},
/**
* Gets the parent of the node with ID nodeId
*
* @permission crmGet
* @param {number} nodeId - The node of which to get the parent
* @param {(node: CRM.SafeNode|CRM.SafeNode[]) => void} [callback] - A callback with the parent of the given node as an argument
* @returns {Promise<CRM.SafeNode|CRM.SafeNode[]>} A promise that resolves with the parent of given node
*/
getParentNode(this: CrmAPIInstance, nodeId: number, callback?: (node: CRM.SafeNode|CRM.SafeNode[]) => void): Promise<CRM.SafeNode|CRM.SafeNode[]> {
return this.__privates._sendCrmMessage('crm.getParentNode', callback, {
nodeId: nodeId
});
},
/**
* Gets the type of node with ID nodeId
*
* @permission crmGet
* @param {number} nodeId - The id of the node whose type to get
* @param {function} [callback] - A callback with the type of the node as the parameter (link, script, menu or divider)
* @returns {Promise<CRM.NodeType>} A promise that resolves with the type of the node
*/
getNodeType(this: CrmAPIInstance, nodeId: number, callback?: CRMNodeCallback): Promise<CRM.NodeType> {
return this.__privates._sendCrmMessage('crm.getNodeType', callback, {
nodeId: nodeId
});
},
/**
* Gets the value of node with ID nodeId
*
* @permission crmGet
* @param {number} nodeId - The id of the node whose value to get
* @param {function} [callback] - A callback with parameter LinkVal, ScriptVal, StylesheetVal or an empty object depending on type
* @returns {Promise<CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null>} A promise that resolves with the value of the node
*/
getNodeValue(this: CrmAPIInstance, nodeId: number, callback?: CRMNodeCallback): Promise<CRM.LinkVal|CRM.ScriptVal|CRM.StylesheetVal|null> {
return this.__privates._sendCrmMessage('crm.getNodeValue', callback, {
nodeId: nodeId
});
},
/**
* Creates a node with the given options
*
* @permission crmGet
* @permission crmWrite
* @param {Object} options - An object containing all the options for the node
* @param {Object} [options.position] - An object containing info about where to place the item, defaults to last if not given
* @param {number} [options.position.node] - The other node's id, if not given, "relates" to the root
* @param {string} [options.position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {string} [options.name] - The name of the object, not required, defaults to "name"
* @param {string} [options.type] - The type of the node (link, script, divider or menu), not required, defaults to link
* @param {boolean} [options.usesTriggers] - Whether the node uses triggers to launch or if it just always launches (only applies to
* link, menu and divider)
* @param {Object[]} [options.triggers] - An array of objects telling the node to show on given triggers. (only applies to link,
* menu and divider)
* @param {string} [options.triggers.url ] - The URL of the site on which to run,
* if launchMode is 2 aka run on specified pages can be any of these
* https://wiki.greasespot.net/Include_and_exclude_rules
* otherwise the url should match this pattern, even when launchMode does not exist on the node (links etc)
* https://developer.chrome.com/extensions/match_patterns
* @param {Object[]} [options.linkData] - The links to which the node of type "link" should... link (defaults to example.com in a new tab),
* consists of an array of objects each containing a URL property and a newTab property, the url being the link they open and the
* newTab boolean being whether or not it opens in a new tab.
* @param {string} [options.linkData.url] - The url to open when clicking the link, this value is required.
* @param {boolean} [options.linkData.newTab] - Whether or not to open the link in a new tab, not required, defaults to true
* @param {Object} [options.scriptData] - The data of the script, required if type is script
* @param {string} [options.scriptData.script] - The actual script, will be "" if none given, required
* @param {Number} [options.scriptData.launchMode] - The time at which this script launches, not required, defaults to 0,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @param {Object[]} [options.scriptData.libraries] - The libraries for the script to include, if the library is not yet
* registered throws an error, so do that first, value not required
* @param {string} [options.scriptData.libraries.name] - The name of the library
* @param {Object[]} [options.scriptData.backgroundLibraries] - The libraries for the backgroundpage to include, if the library is not yet
* registered throws an error, so do that first, value not required
* @param {string} [options.scriptData.backgroundLibraries.name] - The name of the library
* @param {Object} [options.stylesheetData] - The data of the stylesheet, required if type is stylesheet
* @param {Number} [options.stylesheetData.launchMode] - The time at which this stylesheet launches, not required, defaults to 0,
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified
* 4 = disabled
* @param {string} [options.stylesheetData.stylesheet] - The stylesheet that is ran itself
* @param {boolean} [options.stylesheetData.toggle] - Whether the stylesheet is always on or toggle-able by clicking (true = toggle-able), not required, defaults to true
* @param {boolean} [options.stylesheetData.defaultOn] - Whether the stylesheet is on by default or off, only used if toggle is true, not required, defaults to true
* @param {CrmCallback} [callback] - A callback given the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the created node
*/
createNode(this: CrmAPIInstance, options: Partial<CreateCRMConfig> & {
position?: Relation;
}, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.createNode', callback, {
options: options
});
},
/**
* Copies given node,
* WARNING: following properties are not copied:
* file, storage, id, permissions, nodeInfo
* Full permissions rights only if both the to be cloned and the script executing this have full rights
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node to copy
* @param {Object} options - An object containing all the options for the node
* @param {string} [options.name] - The new name of the object (same as the old one if none given)
* @param {Object} [options.position] - An object containing info about where to place the item, defaults to last if not given
* @param {number} [options.position.node] - The other node's id, if not given, "relates" to the root
* @param {string} [options.position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {CrmCallback} [callback] - A callback given the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the copied node
*/
copyNode(this: CrmAPIInstance, nodeId: number, options: {
name?: string;
position?: Relation;
} = {}, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
//To prevent the user's stuff from being disturbed if they re-use the object
const optionsCopy = JSON.parse(JSON.stringify(options));
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.copyNode', callback, {
nodeId: nodeId,
options: optionsCopy
});
},
/**
* Moves given node to position specified in "position"
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node to move
* @param {Object} [position] - An object containing info about where to place the item, defaults to last child of root if not given
* @param {number} [position.node] - The other node, if not given, "relates" to the root
* @param {string} [position.relation] - The position relative to the other node, possibilities are:
* firstChild: becomes the first child of given node, throws an error if given node is not of type menu
* firstSibling: first of the subtree that given node is in
* lastChild: becomes the last child of given node, throws an error if given node is not of type menu
* lastSibling: last of the subtree that given node is in
* before: before given node
* after: after the given node
* @param {CrmCallback} [callback] - A function that gets called with the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the moved node
*/
moveNode(this: CrmAPIInstance, nodeId: number, position: Relation, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
//To prevent the user's stuff from being disturbed if they re-use the object
let positionCopy;
if (position) {
positionCopy = JSON.parse(JSON.stringify(position));
}
else {
positionCopy = {};
}
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.moveNode', callback, {
nodeId: nodeId,
position: positionCopy
});
},
/**
* Deletes given node
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node to delete
* @param {function} [callback] - A function to run when done
* @returns {((errorMessage: string) => void)((successStatus: boolean) => void)} A promise
* that resolves with an error message or the success status
*/
deleteNode(this: CrmAPIInstance, nodeId: number, callback?: (result: string|boolean) => void): Promise<string|boolean> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.deleteNode', callback, {
nodeId: nodeId
});
},
/**
* Edits given settings of the node
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node to edit
* @param {Object} options - An object containing the settings for what to edit
* @param {string} [options.name] - Changes the name to given string
* @param {string} [options.type] - The type to switch to (link, script, stylesheet, divider or menu)
* @param {CrmCallback} [callback] - A function to run when done, contains the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the edited node
*/
editNode(this: CrmAPIInstance, nodeId: number, options: {
name?: string;
type?: CRM.NodeType;
}, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
options = options || {};
//To prevent the user's stuff from being disturbed if they re-use the object
const optionsCopy = JSON.parse(JSON.stringify(options));
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.editNode', callback, {
options: optionsCopy,
nodeId: nodeId
});
},
/**
* Gets the triggers for given node
*
* @permission crmGet
* @param {number} nodeId - The node of which to get the triggers
* @param {CrmCallback} [callback] - A function to run when done, with the triggers as an argument
* @returns {Promise<CRM.Trigger[]>} A promise that resolves with the triggers
*/
getTriggers(this: CrmAPIInstance, nodeId: number, callback?: (triggers: CRM.Trigger[]) => void): Promise<CRM.Trigger[]> {
return this.__privates._sendCrmMessage('crm.getTriggers', callback, {
nodeId: nodeId
});
},
/**
* Sets the triggers for given node
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to get the triggers
* @param {Object[]} triggers - The triggers that launch this node, automatically turns triggers on
* @param {string} triggers.url - The URL of the site on which to run,
* if launchMode is 2 aka run on specified pages can be any of these
* https://wiki.greasespot.net/Include_and_exclude_rules
* otherwise the url should match this pattern, even when launchMode does not exist on the node (links etc)
* https://developer.chrome.com/extensions/match_patterns
* @param {boolean} triggers.not - If true does NOT show the node on that URL
* @param {CrmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setTriggers(this: CrmAPIInstance, nodeId: number, triggers: CRM.Triggers[], callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.setTriggers', callback, {
nodeId: nodeId,
triggers: triggers
});
},
/**
* Gets the trigger' usage for given node (true - it's being used, or false), only works on
* link, menu and divider
*
* @permission crmGet
* @param {number} nodeId - The node of which to get the triggers
* @param {CrmCallback} [callback] - A function to run when done, with the triggers' usage as an argument
* @returns {Promise<boolean>} A promise that resolves with a boolean indicating whether triggers are used
*/
getTriggerUsage(this: CrmAPIInstance, nodeId: number, callback?: CRMNodeCallback): Promise<boolean> {
return this.__privates._sendCrmMessage('crm.getTriggerUsage', callback, {
nodeId: nodeId
});
},
/**
* Sets the usage of triggers for given node, only works on link, menu and divider
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to set the triggers
* @param {boolean} useTriggers - Whether the triggers should be used or not
* @param {CrmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setTriggerUsage(this: CrmAPIInstance, nodeId: number, useTriggers: boolean, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.setTriggerUsage', callback, {
nodeId: nodeId,
useTriggers: useTriggers
});
},
/**
* Gets the content types for given node
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to get the content types
* @param {CrmCallback} [callback] - A function to run when done, with the content types array as an argument
* @returns {Promise<CRM.ContentTypes>} A promise that resolves with the content types
*/
getContentTypes(this: CrmAPIInstance, nodeId: number, callback?: (contentTypes: CRM.ContentTypes) => void): Promise<CRM.ContentTypes> {
return this.__privates._sendCrmMessage('crm.getContentTypes', callback, {
nodeId: nodeId
});
},
/**
* Sets the content type at index "index" to given value "value"
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node whose content types to set
* @param {number|CRM.ContentTypeString} indexOrName - The index of the array to set, 0-5, ordered this way:
* page, link, selection, image, video, audio. Can also be the name of the index (one of those words)
* @param {boolean} value - The new value at index "index"
* @param {CrmCallback} [callback] - A function to run when done, with the new array as an argument
* @returns {Promise<CRM.ContentTypes>} A promise that resolves with the new content types
*/
setContentType(this: CrmAPIInstance, nodeId: number, indexOrName: number|CRM.ContentTypeString, value: boolean, callback?: (contentTypes: CRM.ContentTypes) => void): Promise<CRM.ContentTypes> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.setContentType', callback, {
index: indexOrName,
value: value,
nodeId: nodeId
});
},
/**
* Sets the content types to given contentTypes array
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node whose content types to set
* @param {string[]} contentTypes - An array of strings, if a string is present it means that it is displayed
* on that content type. Requires at least one type to be active, otherwise all are activated.
* The options are:
* page, link, selection, image, video, audio
* @param {CrmCallback} [callback] - A function to run when done, with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setContentTypes(this: CrmAPIInstance, nodeId: number, contentTypes: CRM.ContentTypes, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.setContentTypes', callback, {
contentTypes: contentTypes,
nodeId: nodeId
});
},
/**
* Sets the launch mode of node with ID nodeId to "launchMode", node should be either
* a script or a stylesheet
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to edit
* @param {number} launchMode - The new launchMode, which is the time at which this script/stylesheet runs
* 0 = run on clicking
* 1 = always run
* 2 = run on specified pages
* 3 = only show on specified pages
* 4 = disabled
* @param {CrmCallback} [callback] - A function that is ran when done with the new node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setLaunchMode(this: CrmAPIInstance, nodeId: number, launchMode: CRMLaunchModes, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.setLaunchMode', callback, {
nodeId: nodeId,
launchMode: launchMode
});
},
/**
* Gets the launchMode of the node with ID nodeId, node should be either a script
* or a stylesheet
*
* @permission crmGet
* @param {number} nodeId - The id of the node to get the launchMode of
* @param {function} [callback] - A callback with the launchMode as an argument
* @returns {Promise<CRMLaunchModes>} A promise that resolves with the launchMode
*/
getLaunchMode(this: CrmAPIInstance, nodeId: number, callback?: (launchMode: CRMLaunchModes) => void): Promise<CRMLaunchModes> {
return this.__privates._sendCrmMessage('crm.getLaunchMode', callback, {
nodeId: nodeId
});
},
/**
* All functions related specifically to the stylesheet type
*
* @type Object
*/
stylesheet: {
/**
* Sets the stylesheet of node with ID nodeId to value "stylesheet"
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to change the stylesheet
* @param {string} stylesheet - The code to change to
* @param {CrmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setStylesheet(this: CrmAPIInstance, nodeId: number, stylesheet: string, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.stylesheet.setStylesheet', callback, {
nodeId: nodeId,
stylesheet: stylesheet
});
},
/**
* Gets the value of the stylesheet
*
* @permission crmGet
* @param {number} nodeId - The id of the node of which to get the stylesheet
* @param {function} [callback] - A callback with the stylesheet's value as an argument
* @returns {Promise<string>} A promise that resolves with the stylesheet
*/
getStylesheet(this: CrmAPIInstance, nodeId: number, callback?: CRMNodeCallback): Promise<string> {
return this.__privates._sendCrmMessage('crm.stylesheet.getStylesheet', callback, {
nodeId: nodeId
});
}
},
/**
* All functions related specifically to the link type
*
* @type Object
*/
link: {
/**
* Gets the links of the node with ID nodeId
*
* @permission crmGet
* @param {number} nodeId - The id of the node to get the links from
* @param {function} [callback] - A callback with an array of objects as parameters, all containing two keys:
* newTab: Whether the link should open in a new tab or the current tab
* url: The URL of the link
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the links
*/
getLinks(this: CrmAPIInstance, nodeId: number, callback?: (result: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]> {
return this.__privates._sendCrmMessage('crm.link.getLinks', callback, {
nodeId: nodeId
});
},
/**
* Gets the links of the node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node to get the links from
* @param {Object[]|Object} items - The items to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the links
*/
setLinks(this: CrmAPIInstance, nodeId: number, items: MaybeArray<CRM.LinkNodeLink>, callback?: (result: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.link.setLinks', callback, {
nodeId: nodeId,
items: items
});
},
/**
* Pushes given items into the array of URLs of node with ID nodeId
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to push the items to
* @param {Object[]|Object} items - An array of items or just one item to push
* @param {boolean} [items.newTab] - Whether the link should open in a new tab, defaults to true
* @param {string} [items.url] - The URL to open on clicking the link
* @param {function} [callback] - A function that gets called when done with the new array as an argument
* @returns {Promise<CRM.LinkNodeLink[]>} A promise that resolves with the new links array
*/
push(this: CrmAPIInstance, nodeId: number, items: MaybeArray<CRM.LinkNodeLink>, callback?: (result: CRM.LinkNodeLink[]) => void): Promise<CRM.LinkNodeLink[]> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.link.push', callback, {
items: items,
nodeId: nodeId
});
},
/**
* Splices the array of URLs of node with ID nodeId. Start at "start" and splices "amount" items (just like array.splice)
* and returns them as an array in the callback function
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.LinkNodeLink[], newArr: CRM.LinkNodeLink[]}>} A promise that resolves with an object
* containing a `spliced` property, which holds the spliced items, and a `newArr` property, holding the new array
*/
splice(this: CrmAPIInstance, nodeId: number, start: number, amount: number,
callback?: (spliced: CRM.LinkNodeLink[], newArr: CRM.LinkNodeLink[]) => void): Promise<{
spliced: CRM.LinkNodeLink[];
newArr: CRM.LinkNodeLink[];
}> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.link.splice', ({
spliced, newArr
}: {
spliced: CRM.LinkNodeLink[];
newArr: CRM.LinkNodeLink[];
}) => {
callback && callback(spliced, newArr);
}, {
nodeId: nodeId,
start: start,
amount: amount
});
}
},
/**
* All functions related specifically to the script type
*
* @type Object
*/
script: {
/**
* Sets the script of node with ID nodeId to value "script"
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to change the script
* @param {string} value - The code to change to
* @param {CrmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the new node
*/
setScript(this: CrmAPIInstance, nodeId: number, script: string, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.script.setScript', callback, {
nodeId: nodeId,
script: script
});
},
/**
* Gets the value of the script
*
* @permission crmGet
* @param {number} nodeId - The id of the node of which to get the script
* @param {function} [callback] - A callback with the script's value as an argument
* @returns {Promise<string>} A promise that resolves with the script
*/
getScript(this: CrmAPIInstance, nodeId: number, callback?: (script: string) => void): Promise<string> {
return this.__privates._sendCrmMessage('crm.script.getScript', callback, {
nodeId: nodeId
});
},
/**
* Sets the backgroundScript of node with ID nodeId to value "script"
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node of which to change the script
* @param {string} value - The code to change to
* @param {CrmCallback} [callback] - A function with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the node
*/
setBackgroundScript(this: CrmAPIInstance, nodeId: number, script: string, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.script.setBackgroundScript', callback, {
nodeId: nodeId,
script: script
});
},
/**
* Gets the value of the backgroundScript
*
* @permission crmGet
* @param {number} nodeId - The id of the node of which to get the backgroundScript
* @param {function} [callback] - A callback with the backgroundScript's value as an argument
* @returns {Promise<string>} A promise that resolves with the backgroundScript
*/
getBackgroundScript(this: CrmAPIInstance, nodeId: number, callback?: (backgroundScript: string) => void): Promise<string> {
return this.__privates._sendCrmMessage('crm.script.getBackgroundScript', callback, {
nodeId: nodeId
});
},
/**
* All functions related specifically to the script's libraries
*
* @type Object
*/
libraries: {
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to edit
* @param {Object[]|Object} libraries - One library or an array of libraries to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(this: CrmAPIInstance, nodeId: number, libraries: MaybeArray<{
name: string;
}>, callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.script.libraries.push', callback, {
nodeId: nodeId,
libraries: libraries
});
},
/**
* Splices the array of libraries of node with ID nodeId. Start at "start" and splices "amount" items (just like array.splice)
* and returns them as an array in the callback function, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.Library[], newArr: CRM.Library[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced items and a `newArr` property containing the new array
*/
splice(this: CrmAPIInstance, nodeId: number, start: number, amount: number,
callback?: (spliced: CRM.Library[], newArr: CRM.Library[]) => void): Promise<{
spliced: CRM.Library[];
newArr: CRM.Library[];
}> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.script.libraries.splice', ({
spliced, newArr
}: {
spliced: CRM.Library[];
newArr: CRM.Library[];
}) => {
callback && callback(spliced, newArr);
}, {
nodeId: nodeId,
start: start,
amount: amount
});
}
},
/**
* All functions related specifically to the background script's libraries
*
* @type Object
*/
backgroundLibraries: {
/**
* Pushes given libraries to the node with ID nodeId's libraries array,
* make sure to register them first or an error is thrown, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to edit
* @param {Object[]|Object} libraries - One library or an array of libraries to push
* @param {string} libraries.name - The name of the library
* @param {function} [callback] - A callback with the new array as an argument
* @returns {Promise<CRM.Library[]>} A promise that resolves with the new libraries
*/
push(this: CrmAPIInstance, nodeId: number, libraries: MaybeArray<{
name: string;
}>, callback?: (libs: CRM.Library[]) => void): Promise<CRM.Library[]> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this,
'crm.script.backgroundLibraries.push', callback, {
nodeId: nodeId,
libraries: libraries
});
},
/**
* Splices the array of libraries of node with ID nodeId. Start at "start" and splices "amount" items (just like array.splice)
* and returns them as an array in the callback function, only works on script nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The node to splice
* @param {number} start - The index of the array at which to start splicing
* @param {number} amount - The amount of items to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.Library[], newArr: CRM.Library[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced items and a `newArr` property containing the new array
*/
splice(this: CrmAPIInstance, nodeId: number, start: number, amount: number,
callback?: (spliced: CRM.Library[], newArr: CRM.Library[]) => void): Promise<{
spliced: CRM.Library[];
newArr: CRM.Library[];
}> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this,
'crm.script.backgroundLibraries.splice', ({
spliced, newArr
}: {
spliced: CRM.Library[];
newArr: CRM.Library[];
}) => {
callback && callback(spliced, newArr);
}, {
nodeId: nodeId,
start: start,
amount: amount
});
}
}
},
/**
* All functions related specifically to the menu type
*
* @type Object
*/
menu: {
/**
* Gets the children of the node with ID nodeId, only works for menu type nodes
*
* @permission crmGet
* @param {number} nodeId - The id of the node of which to get the children
* @param {CrmCallback} [callback] - A callback with the nodes as an argument
* @returns {Promise<CRM.SafeNode[]>} A promise that resolves with the children
*/
getChildren(this: CrmAPIInstance, nodeId: number, callback?: (children: CRM.SafeNode[]) => void): Promise<CRM.SafeNode[]> {
return this.__privates._sendCrmMessage('crm.menu.getChildren', callback, {
nodeId: nodeId
});
},
/**
* Sets the children of node with ID nodeId to the nodes with IDs childrenIds,
* removes the to-be-child-node from the old location
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node of which to set the children
* @param {number[]} childrenIds - Each number in the array represents a node that will be a new child
* @param {CrmCallback} [callback] - A callback with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the menu node
*/
setChildren(this: CrmAPIInstance, nodeId: number, childrenIds: number[], callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.menu.setChildren', callback, {
nodeId: nodeId,
childrenIds: childrenIds
});
},
/**
* Pushes the nodes with IDs childrenIds to the node with ID nodeId,
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node of which to push the children
* @param {number[]} childrenIds - Each number in the array represents a node that will be a new child
* @param {CrmCallback} [callback] - A callback with the node as an argument
* @returns {Promise<CRM.SafeNode>} A promise that resolves with the menu
*/
push(this: CrmAPIInstance, nodeId: number, childrenIds: MaybeArray<number>, callback?: CRMNodeCallback): Promise<CRM.SafeNode> {
if (!Array.isArray(childrenIds)) {
childrenIds = [childrenIds];
}
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.menu.push', callback, {
nodeId: nodeId,
childrenIds: childrenIds
});
},
/**
* Splices the children of the node with ID nodeId, starting at "start" and splicing "amount" items,
* the removed items will be put in the root of the tree instead,
* only works for menu type nodes
*
* @permission crmGet
* @permission crmWrite
* @param {number} nodeId - The id of the node of which to splice the children
* @param {number} start - The index at which to start
* @param {number} amount - The amount to splice
* @param {function} [callback] - A function that gets called with the spliced items as the first parameter and the new array as the second parameter
* @returns {Promise<{spliced: CRM.SafeNode[], newArr: CRM.SafeNode[]}>} A promise that resolves with an object
* that contains a `spliced` property, which contains the spliced children and a `newArr` property containing the new children array
*/
splice(this: CrmAPIInstance, nodeId: number, start: number, amount: number,
callback?: (spliced: CRM.SafeNode[], newArr: CRM.SafeNode[]) => void): Promise<{
spliced: CRM.SafeNode[];
newArr: CRM.SafeNode[];
}> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.menu.splice', ({
spliced, newArr
}: {
spliced: CRM.SafeNode[];
newArr: CRM.SafeNode[];
}) => {
callback && callback(spliced, newArr);
}, {
nodeId: nodeId,
start: start,
amount: amount
});
}
}
};
/**
* Background-page specific APIs
*
* @type Object
*/
background = {
/**
* Runs given script on given tab(s)
*
* @permission crmRun
* @param {number} id - The id of the script to run
* @param {Object} options - The options for the tab to run it on
* @param {boolean} [options.all] - Whether to execute on all tabs
* @param {string} [options.status] - Whether the tabs have completed loading.
* One of: "loading", or "complete"
* @param {boolean} [options.lastFocusedWindow] - Whether the tabs are in the last focused window.
* @param {number} [options.windowId] - The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window
* @param {string} [options.windowType] - The type of window the tabs are in (normal, popup, panel, app or devtools)
* @param {boolean} [options.active] - Whether the tabs are active in their windows
* @param {number} [options.index] - The position of the tabs within their windows
* @param {string} [options.title] - The title of the page
* @param {string|string[]} [options.url] - The URL of the page, can use chrome match patterns
* @param {boolean} [options.currentWindow] - Whether the tabs are in the current window
* @param {boolean} [options.highlighted] - Whether the tabs are highlighted
* @param {boolean} [options.pinned] - Whether the tabs are pinned
* @param {boolean} [options.audible] - Whether the tabs are audible
* @param {boolean} [options.muted] - Whether the tabs are muted
* @param {number|number[]} [options.tabId] - The IDs of the tabs
*/
runScript(this: CrmAPIInstance, id: number, options: BrowserTabsQueryInfo & {
tabId?: MaybeArray<number>;
all?: boolean;
}): void {
if (!this.__privates._ensureBackground()) {
return;
}
return this.__privates._sendOptionalCallbackCrmMessage.call(this,
'crm.background.runScript', null, {
id: id,
options: options
}, true);
},
/**
* Runs this script on given tab(s)
*
* @permission crmRun
* @param {Object} options - The options for the tab to run it on
* @param {boolean} [options.all] - Whether to execute on all tabs
* @param {string} [options.status] - Whether the tabs have completed loading.
* One of: "loading", or "complete"
* @param {boolean} [options.lastFocusedWindow] - Whether the tabs are in the last focused window.
* @param {number} [options.windowId] - The ID of the parent window, or windows.WINDOW_ID_CURRENT for the current window
* @param {string} [options.windowType] - The type of window the tabs are in (normal, popup, panel, app or devtools)
* @param {boolean} [options.active] - Whether the tabs are active in their windows
* @param {number} [options.index] - The position of the tabs within their windows
* @param {string} [options.title] - The title of the page
* @param {string|string[]} [options.url] - The URL of the page, can use chrome match patterns
* @param {boolean} [options.currentWindow] - Whether the tabs are in the current window
* @param {boolean} [options.highlighted] - Whether the tabs are highlighted
* @param {boolean} [options.pinned] - Whether the tabs are pinned
* @param {boolean} [options.audible] - Whether the tabs are audible
* @param {boolean} [options.muted] - Whether the tabs are muted
* @param {number|number[]} [options.tabId] - The IDs of the tabs
*/
runSelf(this: CrmAPIInstance, options: BrowserTabsQueryInfo & {
tabId?: MaybeArray<number>;
all?: boolean;
}): void {
if (!this.__privates._ensureBackground()) {
return;
}
return this.__privates._sendOptionalCallbackCrmMessage.call(this,
'crm.background.runSelf', null, {
options: options
});
},
/**
* Adds a listener for a keyboard event
*
* @param {string} key - The keyboard shortcut to listen for
* @param {function} callback - The function to call when a keyboard event occurs
*/
addKeyboardListener(this: CrmAPIInstance, key: string, callback: () => void): void {
if (!this.__privates._ensureBackground()) {
return;
}
return this.__privates._sendOptionalCallbackCrmMessage.call(this,
'crm.background.addKeyboardListener', callback, {
key: key
}, true);
}
}
/**
* The libraries API used to register libraries
*
* @type Object
*/
libraries = {
/**
* Registers a library with name "name"
*
* @permission crmWrite
* @param {string} name - The name to give the library
* @param {Object} options - The options related to the library
* @param {string} [options.url] - The url to fetch the code from, must end in .js
* @param {string} [options.code] - The code to use
* @param {boolean} [options.ts] - Whether the library uses the typescript language
* @param {function} [callback] - A callback with the library object as an argument
* @returns {Promise<CRM.Library>} A promise that resolves with the new library
*/
register(this: CrmAPIInstance, name: string, options: {
code: string;
url?: string
ts?: boolean;
}|{
url: string;
code?: string
ts?: boolean;
}|{
code: string;
url: string
ts?: boolean;
}, callback?: (lib: CRM.Library) => void): Promise<CRM.Library> {
return this.__privates._sendOptionalCallbackCrmMessage.call(this, 'crm.libraries.register', callback, {
name: name,
url: options.url,
code: options.code,
ts: options.ts
});
}
};
/**
* Calls the chrome API given in the "API" parameter. Due to some issues with the chrome message passing
* API it is not possible to pass messages and preserve scope. This could be fixed in other ways but
* unfortunately chrome.tabs.executeScript (what is used to execute scripts on the page) runs in a
* sandbox and does not allow you to access a lot. As a solution to this there are a few types of
* functions you can chain-call on the crmAPI.chrome(API) object:
* a or args or (): uses given arguments as arguments for the API in order specified. When passing a function,
* it will be converted to a placeholder function that will be called on return with the
* arguments chrome passed to it. This means the function is never executed on the background
* page and is always executed here to preserve scope. The arguments are however passed on as they should.
* You can call this function by calling .args or by just using the parentheses as below.
* Keep in mind that this function will not work after it has been called once, meaning that
* if your API calls callbacks multiple times (like chrome.tabs.onCreated) you should use
* persistent callbacks (see below).
* r or return: a function that is called with the value that the chrome API returned. This can
* be used for APIs that don't use callbacks and instead just return values such as
* chrome.runtime.getURL().
* p or persistent: a function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
* s or send: executes the request
* Examples:
* - For a function that uses a callback:
* crmAPI.chrome('alarms.get')('name', function(alarm) {
* //Do something with the result here
* }).send();
* -
* - For a function that returns a value:
* crmAPI.chrome('runtime.getUrl')(path).return(function(result) {
* //Do something with the result
* }).send();
* -
* - For a function that uses neither:
* crmAPI.chrome('alarms.create')('name', {}).send();
* -
* - For a function that uses a persistent callback
* crmAPI.chrome('tabs.onCreated.addListener').persistent(function(tab) {
* //Do something with the tab
* }).send();
* -
* - A compacter version:
* crmAPI.chrome('runtime.getUrl')(path).r(function(result) {
* //Do something with the result
* }).s();
* -
* Requires permission "chrome" and the permission of the the API, so chrome.bookmarks requires
* permission "bookmarks", chrome.alarms requires "alarms"
*
* @permission chrome
* @param {string} api - The API to use
* @returns {Object} - An object on which you can call .args, .fn, .return and .send
* (and their first-letter-only versions)
*/
chrome(api: string) {
return new this.__privates._chromeRequest(this, api);
};
/**
* Calls the browser API given in the "API" parameter. Due to some issues with the browser message passing
* API it is not possible to pass messages and preserve scope. This could be fixed in other ways but
* unfortunately browser.tabs.executeScript (what is used to execute scripts on the page) runs in a
* sandbox and does not allow you to access a lot. As a solution to this there are a few types of
* functions you can chain-call on the crmAPI.browser(API) object:
* a or args or (): uses given arguments as arguments for the API in order specified. When passing a function,
* it will be converted to a placeholder function that will be called on return with the
* arguments chrome passed to it. This means the function is never executed on the background
* page and is always executed here to preserve scope. The arguments are however passed on as they should.
* You can call this function by calling .args or by just using the parentheses as below.
* Keep in mind that this function will not work after it has been called once, meaning that
* if your API calls callbacks multiple times (like chrome.tabs.onCreated) you should use
* persistent callbacks (see below).
* p or persistent: a function that is a persistent callback that will not be removed when called.
* This can be used on APIs like chrome.tabs.onCreated where multiple calls can occurring
* contrary to chrome.tabs.get where only one callback will occur.
* s or send: executes the request
* Examples:
* - For a function that returns a promise:
* crmAPI.browser('alarms.get')('name').send().then((alarm) => {
* //Do something with the result here
* });
* -
* - Or the async version
* const alarm = await crmAPI.browser('alarms.get')('name').send();
* -
* - For a function that returns a value it works the same:
* crmAPI.chrome('runtime.getUrl')(path).send().then((result) => {
* //Do something with the result
* });
* -
* - For a function that uses neither:
* crmAPI.chrome('alarms.create')('name', {}).send();
* -
* - Or you can still await it to know when it's done executing
* crmAPI.chrome('alarms.create')('name', {}).send();
* -
* - For a function that uses a persistent callback
* crmAPI.chrome('tabs.onCreated.addListener').persistent(function(tab) {
* //Do something with the tab
* }).send();
* -
* - A compacter version:
* const url = await crmAPI.chrome('alarms.get')('name').s();
* -
* Requires permission "chrome" (or "browser", they're the same) and the permission
* of the the API, so chrome.bookmarks requires permission "bookmarks",
* chrome.alarms requires "alarms"
*
* @permission chrome
* @permission browser
* @param {string} api - The API to use
* @returns {Object} - An object on which you can call .args, .fn and .send
* (and their first-letter-only versions)
*/
browser: any = null;
/**
* The GM API that fills in any APIs that GreaseMonkey uses and points them to their
* CRM counterparts
* Documentation can be found here http://wiki.greasespot.net/Greasemonkey_Manual:API
* and here http://tampermonkey.net/documentation.php
*
* @type Object
*/
GM = {
/**
* Returns any info about the script
*
* @see {@link https://tampermonkey.net/documentation.php#GM_info}
* @returns {Object} - Data about the script
*/
GM_info(this: CrmAPIInstance): GreaseMonkeyDataInfo {
return this.__privates._greasemonkeyData.info;
},
/**
* This method retrieves a value that was set with GM_setValue. See GM_setValue
* for details on the storage of these values.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getValue}
* @param {String} name - The property name to get
* @param {any} [defaultValue] - Any value to be returned, when no value has previously been set
* @returns {any} - Returns the value if the value is defined, if it's undefined, returns defaultValue
* if defaultValue is also undefined, returns undefined
*/
GM_getValue: <T, U>(name: string, defaultValue?: T): T | U => {
const result = (this.storage as any).get(name);
return (result !== undefined ? result : defaultValue);
},
/**
* This method allows user script authors to persist simple values across page-loads.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_setValue}
* @param {String} name - The unique (within this script) name for this value. Should be restricted to valid Javascript identifier characters.
* @param {any} value - The value to store
*/
GM_setValue(this: CrmAPIInstance, name: string, value: any): void {
(this.storage as any).set(name, (typeof value === 'object' ?
JSON.parse(JSON.stringify(value)) : value));
},
/**
* This method deletes an existing name / value pair from storage.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_deleteValue}
* @param {String} name - Property name to delete.
*/
GM_deleteValue(this: CrmAPIInstance, name: string): void {
(this.storage as any).remove(name);
},
/**
* This method retrieves an array of storage keys that this script has stored.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_listValues}
* @returns {String[]} All keys of the storage
*/
GM_listValues(this: CrmAPIInstance): string[] {
const keys = [];
for (const key in this.__privates._nodeStorage) {
if (this.__privates._nodeStorage.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
},
/**
* Gets the resource URL for given resource name
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getResourceURL}
* @param {String} name - The name of the resource
* @returns {String} - A URL that can be used to get the resource value
*/
GM_getResourceURL(this: CrmAPIInstance, name: string): string {
if (this.__privates._greasemonkeyData.resources[name]) {
return this.__privates._greasemonkeyData.resources[name].crmUrl;
}
return undefined;
},
/**
* Gets the resource string for given resource name
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getResourceString}
* @param {String} name - The name of the resource
* @returns {String} - The resource value
*/
GM_getResourceString(this: CrmAPIInstance, name: string): string {
if (this.__privates._greasemonkeyData.resources[name]) {
return this.__privates._greasemonkeyData.resources[name].dataString;
}
return undefined;
},
/**
* This method adds a string of CSS to the document. It creates a new <style> element,
* adds the given CSS to it, and inserts it into the <head>.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_addStyle}
* @param {String} css - The CSS to put on the page
*/
GM_addStyle(this: CrmAPIInstance, css: string): void {
const style = document.createElement('style');
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
},
/**
* Logs to the console
*
* @see {@link https://tampermonkey.net/documentation.php#GM_log}
* @param {any} any - The data to log
*/
GM_log: console.log.bind(console),
/**
* Open specified URL in a new tab, open_in_background is not available here since that
* not possible in chrome
*
* @see {@link https://tampermonkey.net/documentation.php#GM_openInTab}
* @param {String} url - The url to open
*/
GM_openInTab(this: CrmAPIInstance, url: string): void {
window.open(url, '_blank');
},
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_registerMenuCommand}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_registerMenuCommand: CrmAPIInstance._helpers.emptyFn,
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_unregisterMenuCommand}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_unregisterMenuCommand: CrmAPIInstance._helpers.emptyFn,
/**
* This is only here to prevent errors from occurring when calling any of these functions,
* this function does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_setClipboard}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_setClipboard: CrmAPIInstance._helpers.emptyFn,
/**
* Sends an xmlhttpRequest with given parameters
*
* @see {@link https://tampermonkey.net/documentation.php#GM_xmlhttpRequest}
* @param {Object} options - The options
* @param {string} [options.method] - The method to use (GET, HEAD or POST)
* @param {string} [options.url] - The url to request
* @param {Object} [options.headers] - The headers for the request
* @param {Object} [options.data] - The data to send along
* @param {boolean} [options.binary] - Whether the data should be sent in binary mode
* @param {number} [options.timeout] - The time to wait in ms
* @param {Object} [options.context] - A property which will be applied to the response object
* @param {string} [options.responseType] - The type of response, arraybuffer, blob or json
* @param {string} [options.overrideMimeType] - The MIME type to use
* @param {boolean} [options.anonymous] - If true, sends no cookies along with the request
* @param {boolean} [options.fetch] - Use a fetch instead of an xhr
* @param {string} [options.username] - A username for authentication
* @param {string} [options.password] - A password for authentication
* @param {function} [options.onload] - A callback on that event
* @param {function} [options.onerror] - A callback on that event
* @param {function} [options.onreadystatechange] - A callback on that event
* @param {function} [options.onprogress] - A callback on that event
* @param {function} [options.onloadstart] - A callback on that event
* @param {function} [options.ontimeout] - A callback on that event
* @returns {XMLHttpRequest} The XHR
*/
GM_xmlhttpRequest(this: CrmAPIInstance, options: {
method?: string,
url?: string,
headers?: { [headerKey: string]: string },
data?: any,
binary?: boolean,
timeout?: number,
context?: any,
responseType?: string,
overrideMimeType?: string,
anonymous?: boolean,
fetch?: boolean,
username?: string,
password?: string,
onload?: (e: Event) => void,
onerror?: (e: Event) => void,
onreadystatechange?: (e: Event) => void,
onprogress?: (e: Event) => void,
onloadstart?: (e: Event) => void,
ontimeout?: (e: Event) => void
}): void {
//There is no point in enforcing the @connect metaTag since
//you can construct you own XHR without the API anyway
const req = new XMLHttpRequest();
this.__privates._setupRequestEvent(options, req, 'abort');
this.__privates._setupRequestEvent(options, req, 'error');
this.__privates._setupRequestEvent(options, req, 'load');
this.__privates._setupRequestEvent(options, req, 'progress');
this.__privates._setupRequestEvent(options, req, 'readystatechange');
req.open(options.method, options.url, true, options.username || '', options.password || '');
if (options.overrideMimeType) {
req.overrideMimeType(options.overrideMimeType);
}
if (options.headers) {
for (const prop in options.headers) {
if (Object.prototype.hasOwnProperty.call(options.headers, prop)) {
req.setRequestHeader(prop, options.headers[prop]);
}
}
}
const body = options.data ? options.data : null;
return req.send(body);
},
/**
* Adds a change listener to the storage and returns the listener ID.
* 'name' is the name of the observed variable. The 'remote' argument
* of the callback function shows whether this value was modified
* from the instance of another tab (true) or within this script
* instance (false). Therefore this functionality can be used by
* scripts of different browser tabs to communicate with each other.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_addValueChangeListener}
* @param {string} name - The name of the observed variable
* @param {function} callback - A callback in which the first argument is
* the name of the observed, variable, the second one is the old value,
* the third one is the new value and the fourth one is a boolean that
* indicates whether the change was from a remote tab
* @returns {number} - The id of the listener, used for removing it
*/
GM_addValueChangeListener(this: CrmAPIInstance, name: string, callback: (name: string, oldValue: any, newValue: any, remote: boolean) => void): number {
return this.__privates._storageListeners.add({
key: name,
type: STORAGE_TYPE.LOCAL,
callback: callback
});
},
/**
* Removes a change listener by its ID.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_removeValueChangeListener}
* @param {number} listenerId - The id of the listener
*/
GM_removeValueChangeListener(this: CrmAPIInstance, listenerId: number): void {
this.__privates._storageListeners.remove(listenerId);
},
/**
* Downloads the file at given URL
*
* @see {@link https://tampermonkey.net/documentation.php#GM_GM_download}
* @param {string|Object} detailsOrUrl - The URL or a details object containing any data
* @param {string} [detailsOrUrl.url] - The url of the download
* @param {string} [detailsOrUrl.name] - The name of the file after download
* @param {Object} [detailsOrUrl.headers] - The headers for the request
* @param {function} [detailsOrUrl.onload] - Called when the request loads
* @param {function} [detailsOrUrl.onerror] - Called on error, gets called with an object
* containing an error attribute that specifies the reason for the error
* and a details attribute that gives a more detailed description of the error
* @param {string} [name] - The name of the file after download
*/
GM_download(this: CrmAPIInstance, detailsOrUrl: DownloadSettings|string, name?: string): void {
let details: DownloadSettings = {};
const detailsOrUrlString = detailsOrUrl;
if (typeof detailsOrUrlString === 'string') {
details.url = detailsOrUrlString;
details.name = name;
}
else {
details = detailsOrUrl as DownloadSettings;
}
const options = {
url: details.url,
fileName: details.name,
saveAs: name,
headers: details.headers
};
const request = this.__privates._specialRequest('downloads.download', 'GM_download').args(options);
request.send().then((result: any) => {
const downloadId = result.APIArgs[0];
if (downloadId === undefined) {
CrmAPIInstance._helpers.isFn(details.onerror) && details.onerror({
error: 'not_succeeded',
details: 'request didn\'t complete'
});
} else {
CrmAPIInstance._helpers.isFn(details.onload) && details.onload();
}
}).catch((err) => {
CrmAPIInstance._helpers.isFn(details.onerror) && details.onerror({
error: 'not_permitted',
details: err.error
});
});
},
/**
* Please use the comms API instead of this one
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getTab}
* @param {function} callback - A callback that is immediately called
*/
GM_getTab: CrmAPIInstance._helpers.instantCb,
/**
* Please use the comms API instead of this one
*
* @see {@link https://tampermonkey.net/documentation.php#GM_getTabs}
* @param {function} callback - A callback that is immediately called
*/
GM_getTabs: CrmAPIInstance._helpers.instantCb,
/**
* Please use the comms API instead of this one, this one does nothing
*
* @see {@link https://tampermonkey.net/documentation.php#GM_saveTab}
* @param {function} callback - A callback that is immediately called
*/
GM_saveTab: CrmAPIInstance._helpers.instantCb,
/**
* The unsafeWindow object provides full access to the pages javascript functions and variables.
*
* @see {@link https://tampermonkey.net/documentation.php#unsafeWindow}
* @type Window
*/
unsafeWindow: typeof window === 'undefined' ? self : window,
//This seems to be deprecated from the tampermonkey documentation page, removed somewhere between january 1st 2016
// and january 24th 2016 waiting for any update
/**
* THIS FUNCTION DOES NOT WORK AND IS DEPRECATED
*
* @see {@link https://tampermonkey.net/documentation.php#GM_installScript}
* @param {any} ignoredArguments - An argument that is ignored
*/
GM_installScript: CrmAPIInstance._helpers.emptyFn,
/**
* Shows a HTML5 Desktop notification and/or highlight the current tab.
*
* @see {@link https://tampermonkey.net/documentation.php#GM_notification}
* @param {string|Object} textOrOptions - The message of the notification
* @param {string} [textOrOptions.text] - The message of the notification
* @param {string} [textOrOptions.imageUrl] - The URL of the image to use
* @param {string} [textOrOptions.title] - The title of the notification
* @param {function} [textOrOptions.onclick] - A function to call on clicking
* @param {boolean} [textOrOptions.isClickable] - Whether the notification is clickable
* @param {function} [textOrOptions.ondone] - A function to call when the notification
* disappears or is closed by the user.
* @param {string} [title] - The title of the notification
* @param {string} [image] - A url to the image to use for the notification
* @param {function} [onclick] - A function to run on clicking the notification
*/
GM_notification(this: CrmAPIInstance, textOrOptions: NotificationOptions|string, title?: string, image?: string, onclick?: () => void): void {
let details: {
message: string;
title: string;
iconUrl: string;
isClickable: boolean;
onclick(e: Event): void;
ondone?(e: Event): void;
type?: string;
};
if (typeof textOrOptions === 'object' && textOrOptions) {
details = {
message: textOrOptions.text,
title: textOrOptions.title,
iconUrl: textOrOptions.imageUrl,
isClickable: !!textOrOptions.onclick,
onclick: textOrOptions.onclick,
ondone: textOrOptions.ondone
};
} else {
details = {
message: textOrOptions as string,
title: title,
iconUrl: image,
isClickable: !!onclick,
onclick: onclick
};
}
details.type = 'basic';
details.iconUrl = details.iconUrl || runtimeGetURL('icon-large.png');
const onclickRef = details.onclick && this.__privates._createCallbackFunction(details.onclick, new Error(), {
maxCalls: 1
});
const ondoneRef = details.ondone && this.__privates._createCallbackFunction(details.ondone, new Error(), {
maxCalls: 1
});
delete details.onclick;
delete details.ondone;
this.__privates._specialRequest('notifications.create', 'GM_notification').args(details).s().then((notificationId: number) => {
this.__privates._addNotificationListener(notificationId, onclickRef, ondoneRef);
}).catch((err) => {
if (console.warn) {
console.warn(err);
} else {
console.log(err);
}
});
}
};
/**
* Fetches resource at given url. If this keeps failing with
* a CORB error, try crmAPI.fetchBackground
*
* @param {string} url - The url to fetch the data from
* @returns {Promise<string>} A promise that resolves to the content
*/
fetch(url: string): Promise<string> {
if ('fetch' in window && window.fetch !== undefined) {
return fetch(url).then(r => r.text()) as unknown as Promise<string>;
}
return new Promise<string>((resolve, reject) => {
const xhr = new window.XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.responseText);
} else {
reject(new Error(`Failed xhr with status ${xhr.status}`));
}
}
}
xhr.send();
});
}
/**
* Fetches resource at given url through the background-page, bypassing
* any CORS or CORB-like blocking
*
* @param {string} url - The url to fetch the data from
* @returns {Promise<string>} A promise that resolves to the content
*/
fetchBackground(url: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
this.__privates._sendMessage({
id: this.__privates._id,
type: 'fetch',
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
data: {
url: url,
onFinish: this.__privates._createCallbackFunction((err: boolean, data: string) => {
if (err) {
reject(data);
} else {
resolve(data);
}
}, new Error(), {
maxCalls: 1
}),
id: this.__privates._id,
tabIndex: this.__privates._tabIndex,
tabId: this.__privates._tabData.id
}
})
});
}
/**
* Returns the elements matching given selector within given context
*
* @param {string} selector - A css selector string to find elements with
* @param {Object} [context] - The context of the search (the node from which to start, default is document)
* @returns {Element[]} An array of the matching HTML elements
*/
$(selector: string, context: HTMLElement = (document as any)): HTMLElement|Element {
return Array.prototype.slice.apply(context.querySelectorAll(selector));
};
$crmAPI = this.$;
/**
* Logs given arguments to the background page and logger page
*
* @param {any} argument - An argument to pass (can be as many as you want)
* in the form of crmAPI.log(a,b,c,d);
*/
log(...args: any[]): void {
let err = (new Error()).stack.split('\n')[2];
if (err.indexOf('eval') > -1) {
err = (new Error()).stack.split('\n')[3];
}
const errSplit = err.split('at');
const lineNumber = errSplit
.slice(1, errSplit.length)
.join('at')
.replace(/anonymous/, 'script');
const { data, logId } = this.__privates._saveLogValues(args);
this.__privates._sendMessage({
id: this.__privates._id,
type: 'logCrmAPIValue',
tabId: this.__privates._tabData.id,
tabIndex: this.__privates._tabIndex,
data: {
type: 'log',
data: JSON.stringify(data),
id: this.__privates._id,
logId: logId,
tabIndex: this.__privates._tabIndex,
lineNumber: lineNumber,
tabId: this.__privates._tabData.id
}
});
};
}
window._crmAPIRegistry = window._crmAPIRegistry || [];
window._crmAPIRegistry.push(CrmAPIInstance);
}(typeof window === 'undefined' ? self : window)); | the_stack |
import useSWR from "swr";
import _find from "lodash/find";
import _sortBy from "lodash/sortBy";
import _get from "lodash/get";
import _isEmpty from "lodash/isEmpty";
import { useSnackbar } from "notistack";
import { DialogContentText, Stack, Typography } from "@mui/material";
import { FormDialog, FormFields } from "@rowy/form-builder";
import { tableSettings } from "./form";
import TableName from "./TableName";
import TableId from "./TableId";
import SuggestedRules from "./SuggestedRules";
import SteppedAccordion from "@src/components/SteppedAccordion";
import ActionsMenu from "./ActionsMenu";
import DeleteMenu from "./DeleteMenu";
import { useProjectContext, Table } from "@src/contexts/ProjectContext";
import useRouter from "@src/hooks/useRouter";
import { useConfirmation } from "@src/components/ConfirmationDialog";
import { useSnackLogContext } from "@src/contexts/SnackLogContext";
import { runRoutes } from "@src/constants/runRoutes";
import { analytics } from "@src/analytics";
import {
CONFIG,
TABLE_GROUP_SCHEMAS,
TABLE_SCHEMAS,
} from "@src/config/dbPaths";
import { Controller } from "react-hook-form";
export enum TableSettingsDialogModes {
create,
update,
}
const customComponents = {
tableName: {
component: TableName,
defaultValue: "",
validation: [["string"]],
},
tableId: {
component: TableId,
defaultValue: "",
validation: [["string"]],
},
suggestedRules: {
component: SuggestedRules,
defaultValue: "",
validation: [["string"]],
},
};
export interface ITableSettingsProps {
mode: TableSettingsDialogModes | null;
clearDialog: () => void;
data: Table | null;
}
export default function TableSettings({
mode,
clearDialog,
data,
}: ITableSettingsProps) {
const { settingsActions, roles, tables, rowyRun } = useProjectContext();
const sectionNames = Array.from(
new Set((tables ?? []).map((t) => t.section))
);
const router = useRouter();
const { requestConfirmation } = useConfirmation();
const snackLogContext = useSnackLogContext();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const { data: collections } = useSWR(
"firebaseCollections",
() => rowyRun?.({ route: runRoutes.listCollections }),
{
revalidateOnMount: true,
revalidateOnFocus: false,
revalidateOnReconnect: false,
dedupingInterval: 60_000 * 60,
}
);
const open = mode !== null;
if (!open) return null;
const handleSubmit = async (v) => {
const { _suggestedRules, ...values } = v;
const data = { ...values };
if (values.schemaSource)
data.schemaSource = _find(tables, { id: values.schemaSource });
const hasExtensions = !_isEmpty(_get(data, "_schema.extensionObjects"));
const hasWebhooks = !_isEmpty(_get(data, "_schema.webhooks"));
const deployExtensionsWebhooks = (onComplete?: () => void) => {
if (rowyRun && (hasExtensions || hasWebhooks)) {
requestConfirmation({
title: `Deploy ${[
hasExtensions && "extensions",
hasWebhooks && "webhooks",
]
.filter(Boolean)
.join(" and ")}?`,
body: "You can also deploy later from the table page",
confirm: "Deploy",
cancel: "Later",
handleConfirm: async () => {
const tablePath = data.collection;
const tableConfigPath = `${
data.tableType !== "collectionGroup"
? TABLE_SCHEMAS
: TABLE_GROUP_SCHEMAS
}/${data.id}`;
if (hasExtensions) {
// find derivative, default value
snackLogContext.requestSnackLog();
rowyRun({
route: runRoutes.buildFunction,
body: {
tablePath,
pathname: `/${
data.tableType === "collectionGroup"
? "tableGroup"
: "table"
}/${data.id}`,
tableConfigPath,
},
});
analytics.logEvent("deployed_extensions");
}
if (hasWebhooks) {
const resp = await rowyRun({
service: "hooks",
route: runRoutes.publishWebhooks,
body: {
tableConfigPath,
tablePath,
},
});
enqueueSnackbar(resp.message, {
variant: resp.success ? "success" : "error",
});
analytics.logEvent("published_webhooks");
}
if (onComplete) onComplete();
},
handleCancel: async () => {
let _schema: Record<string, any> = {};
if (hasExtensions) {
_schema.extensionObjects = _get(
data,
"_schema.extensionObjects"
)!.map((x) => ({
...x,
active: false,
}));
}
if (hasWebhooks) {
_schema.webhooks = _get(data, "_schema.webhooks")!.map((x) => ({
...x,
active: false,
}));
}
await settingsActions?.updateTable({
id: data.id,
tableType: data.tableType,
_schema,
});
if (onComplete) onComplete();
},
});
} else {
if (onComplete) onComplete();
}
};
if (mode === TableSettingsDialogModes.update) {
await settingsActions?.updateTable(data);
deployExtensionsWebhooks();
clearDialog();
analytics.logEvent("update_table", { type: values.tableType });
enqueueSnackbar("Updated table");
} else {
const creatingSnackbar = enqueueSnackbar("Creating table…", {
persist: true,
});
await settingsActions?.createTable(data);
await analytics.logEvent("create_table", { type: values.tableType });
deployExtensionsWebhooks(() => {
if (router.location.pathname === "/") {
router.history.push(
`${
values.tableType === "collectionGroup" ? "tableGroup" : "table"
}/${values.id}`
);
} else {
router.history.push(values.id);
}
clearDialog();
closeSnackbar(creatingSnackbar);
});
}
};
const fields = tableSettings(
mode,
roles,
sectionNames,
_sortBy(
tables?.map((table) => ({
label: table.name,
value: table.id,
section: table.section,
collection: table.collection,
})),
["section", "label"]
),
Array.isArray(collections) ? collections.filter((x) => x !== CONFIG) : null
);
return (
<FormDialog
onClose={clearDialog}
title={
mode === TableSettingsDialogModes.create
? "Create table"
: "Table settings"
}
fields={fields}
customBody={(formFieldsProps) => {
const { errors } = formFieldsProps.useFormMethods.formState;
const groupedErrors: Record<string, string> = Object.entries(
errors
).reduce((acc, [name, err]) => {
const match = _find(fields, ["name", name])?.step;
if (!match) return acc;
acc[match] = err.message;
return acc;
}, {});
return (
<>
<Controller
control={formFieldsProps.control}
name="_schema"
defaultValue={{}}
render={() => <></>}
/>
<Stack
direction="row"
spacing={1}
sx={{
display: "flex",
height: "var(--dialog-title-height)",
alignItems: "center",
position: "absolute",
top: 0,
right: 40 + 12 + 8,
}}
>
<ActionsMenu
mode={mode}
control={formFieldsProps.control}
useFormMethods={formFieldsProps.useFormMethods}
/>
{mode === TableSettingsDialogModes.update && (
<DeleteMenu clearDialog={clearDialog} data={data} />
)}
</Stack>
<SteppedAccordion
disableUnmount
steps={
[
{
id: "collection",
title: "Collection",
content: (
<>
<DialogContentText paragraph>
Connect this table to a new or existing Firestore
collection
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter((f) => f.step === "collection")}
/>
</>
),
optional: false,
error: Boolean(groupedErrors.collection),
subtitle: groupedErrors.collection && (
<Typography variant="caption" color="error">
{groupedErrors.collection}
</Typography>
),
},
{
id: "display",
title: "Display",
content: (
<>
<DialogContentText paragraph>
Set how this table is displayed to users
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter((f) => f.step === "display")}
customComponents={customComponents}
/>
</>
),
optional: false,
error: Boolean(groupedErrors.display),
subtitle: groupedErrors.display && (
<Typography variant="caption" color="error">
{groupedErrors.display}
</Typography>
),
},
{
id: "accessControls",
title: "Access controls",
content: (
<>
<DialogContentText paragraph>
Set who can view and edit this table. Only ADMIN users
can edit table settings or add, edit, and delete
columns.
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter(
(f) => f.step === "accessControls"
)}
customComponents={customComponents}
/>
</>
),
optional: false,
error: Boolean(groupedErrors.accessControls),
subtitle: groupedErrors.accessControls && (
<Typography variant="caption" color="error">
{groupedErrors.accessControls}
</Typography>
),
},
{
id: "auditing",
title: "Auditing",
content: (
<>
<DialogContentText paragraph>
Track when users create or update rows
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter((f) => f.step === "auditing")}
/>
</>
),
optional: true,
error: Boolean(groupedErrors.auditing),
subtitle: groupedErrors.auditing && (
<Typography variant="caption" color="error">
{groupedErrors.auditing}
</Typography>
),
},
/**
* TODO: Figure out where to store this settings
{
id: "function",
title: "Cloud Function",
content: (
<>
<DialogContentText paragraph>
Configure cloud function settings, this setting is shared across all tables connected to the same collection
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter((f) => f.step === "function")}
/>
</>
),
optional: true,
error: Boolean(groupedErrors.function),
subtitle: groupedErrors.auditing && (
<Typography variant="caption" color="error">
{groupedErrors.function}
</Typography>
),
},
*/
mode === TableSettingsDialogModes.create
? {
id: "columns",
title: "Columns",
content: (
<>
<DialogContentText paragraph>
Initialize table with columns
</DialogContentText>
<FormFields
{...formFieldsProps}
fields={fields.filter(
(f) => f.step === "columns"
)}
/>
</>
),
optional: true,
error: Boolean(groupedErrors.columns),
subtitle: groupedErrors.columns && (
<Typography variant="caption" color="error">
{groupedErrors.columns}
</Typography>
),
}
: null,
].filter(Boolean) as any
}
/>
</>
);
}}
customComponents={customComponents}
values={{ ...data }}
onSubmit={handleSubmit}
SubmitButtonProps={{
children:
mode === TableSettingsDialogModes.create ? "Create" : "Update",
}}
/>
);
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreSyncBaseProvider, CoreSyncBlockedError } from '@classes/base-sync';
import { CoreNetworkError } from '@classes/errors/network-error';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreApp } from '@services/app';
import { CoreGroups } from '@services/groups';
import { CoreSites } from '@services/sites';
import { CoreSync } from '@services/sync';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import { AddonModWikiPageDBRecord } from './database/wiki';
import { AddonModWiki, AddonModWikiProvider } from './wiki';
import { AddonModWikiOffline } from './wiki-offline';
/**
* Service to sync wikis.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWikiSyncProvider extends CoreSyncBaseProvider<AddonModWikiSyncSubwikiResult> {
static readonly AUTO_SYNCED = 'addon_mod_wiki_autom_synced';
static readonly MANUAL_SYNCED = 'addon_mod_wiki_manual_synced';
protected componentTranslatableString = 'wiki';
constructor() {
super('AddonModWikiSyncProvider');
}
/**
* Get a string to identify a subwiki. If it doesn't have a subwiki ID it will be identified by wiki ID, user ID and group ID.
*
* @param subwikiId Subwiki ID. If not defined, wikiId, userId and groupId should be defined.
* @param wikiId Wiki ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param userId User ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param groupId Group ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @return Identifier.
*/
getSubwikiBlockId(subwikiId?: number, wikiId?: number, userId?: number, groupId?: number): string {
subwikiId = AddonModWikiOffline.convertToPositiveNumber(subwikiId);
if (subwikiId && subwikiId > 0) {
return String(subwikiId);
}
wikiId = AddonModWikiOffline.convertToPositiveNumber(wikiId);
userId = AddonModWikiOffline.convertToPositiveNumber(userId);
groupId = AddonModWikiOffline.convertToPositiveNumber(groupId);
return `${wikiId}:${userId}:${groupId}`;
}
/**
* Try to synchronize all the wikis in a certain site or in all sites.
*
* @param siteId Site ID to sync. If not defined, sync all sites.
* @param force Wether to force sync not depending on last execution.
* @return Promise resolved if sync is successful, rejected if sync fails.
*/
syncAllWikis(siteId?: string, force?: boolean): Promise<void> {
return this.syncOnSites('all wikis', this.syncAllWikisFunc.bind(this, !!force), siteId);
}
/**
* Sync all wikis on a site.
*
* @param force Wether to force sync not depending on last execution.
* @param siteId Site ID to sync.
* @param Promise resolved if sync is successful, rejected if sync fails.
*/
protected async syncAllWikisFunc(force: boolean, siteId: string): Promise<void> {
// Get all the pages created in offline.
const pages = await AddonModWikiOffline.getAllNewPages(siteId);
const subwikis: Record<string, boolean> = {};
// Sync all subwikis.
await Promise.all(pages.map(async (page) => {
const index = this.getSubwikiBlockId(page.subwikiid, page.wikiid, page.userid, page.groupid);
if (subwikis[index]) {
// Already synced.
return;
}
subwikis[index] = true;
const result = force ?
await this.syncSubwiki(page.subwikiid, page.wikiid, page.userid, page.groupid, siteId) :
await this.syncSubwikiIfNeeded(page.subwikiid, page.wikiid, page.userid, page.groupid, siteId);
if (result?.updated) {
// Sync successful, send event.
CoreEvents.trigger(AddonModWikiSyncProvider.AUTO_SYNCED, {
siteId: siteId,
subwikiId: page.subwikiid,
wikiId: page.wikiid,
userId: page.userid,
groupId: page.groupid,
created: result.created,
discarded: result.discarded,
warnings: result.warnings,
});
}
}));
}
/**
* Sync a subwiki only if a certain time has passed since the last time.
*
* @param subwikiId Subwiki ID. If not defined, wikiId, userId and groupId should be defined.
* @param wikiId Wiki ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param userId User ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param groupId Group ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when subwiki is synced or doesn't need to be synced.
*/
async syncSubwikiIfNeeded(
subwikiId: number,
wikiId?: number,
userId?: number,
groupId?: number,
siteId?: string,
): Promise<AddonModWikiSyncSubwikiResult | undefined> {
const blockId = this.getSubwikiBlockId(subwikiId, wikiId, userId, groupId);
const needed = await this.isSyncNeeded(blockId, siteId);
if (needed) {
return this.syncSubwiki(subwikiId, wikiId, userId, groupId, siteId);
}
}
/**
* Synchronize a subwiki.
*
* @param subwikiId Subwiki ID. If not defined, wikiId, userId and groupId should be defined.
* @param wikiId Wiki ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param userId User ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param groupId Group ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
syncSubwiki(
subwikiId: number,
wikiId?: number,
userId?: number,
groupId?: number,
siteId?: string,
): Promise<AddonModWikiSyncSubwikiResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
const subwikiBlockId = this.getSubwikiBlockId(subwikiId, wikiId, userId, groupId);
if (this.isSyncing(subwikiBlockId, siteId)) {
// There's already a sync ongoing for this subwiki, return the promise.
return this.getOngoingSync(subwikiBlockId, siteId)!;
}
// Verify that subwiki isn't blocked.
if (CoreSync.isBlocked(AddonModWikiProvider.COMPONENT, subwikiBlockId, siteId)) {
this.logger.debug(`Cannot sync subwiki ${subwikiBlockId} because it is blocked.`);
throw new CoreSyncBlockedError(Translate.instant('core.errorsyncblocked', { $a: this.componentTranslate }));
}
this.logger.debug(`Try to sync subwiki ${subwikiBlockId}`);
return this.addOngoingSync(subwikiBlockId, this.performSyncSubwiki(subwikiId, wikiId, userId, groupId, siteId), siteId);
}
/**
* Synchronize a subwiki.
*
* @param subwikiId Subwiki ID. If not defined, wikiId, userId and groupId should be defined.
* @param wikiId Wiki ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param userId User ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param groupId Group ID. Optional, will be used to create the subwiki if subwiki ID not provided.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
protected async performSyncSubwiki(
subwikiId: number,
wikiId?: number,
userId?: number,
groupId?: number,
siteId?: string,
): Promise<AddonModWikiSyncSubwikiResult> {
const result: AddonModWikiSyncSubwikiResult = {
warnings: [],
updated: false,
created: [],
discarded: [],
};
const subwikiBlockId = this.getSubwikiBlockId(subwikiId, wikiId, userId, groupId);
// Get offline pages to be sent.
const pages = await CoreUtils.ignoreErrors(
AddonModWikiOffline.getSubwikiNewPages(subwikiId, wikiId, userId, groupId, siteId),
<AddonModWikiPageDBRecord[]> [],
);
if (!pages || !pages.length) {
// Nothing to sync.
await CoreUtils.ignoreErrors(this.setSyncTime(subwikiBlockId, siteId));
return result;
}
if (!CoreApp.isOnline()) {
// Cannot sync in offline.
throw new CoreNetworkError();
}
// Send the pages.
await Promise.all(pages.map(async (page) => {
try {
const pageId = await AddonModWiki.newPageOnline(page.title, page.cachedcontent, {
subwikiId,
wikiId,
userId,
groupId,
siteId,
});
result.updated = true;
result.created.push({
pageId: pageId,
title: page.title,
});
// Delete the local page.
await AddonModWikiOffline.deleteNewPage(page.title, subwikiId, wikiId, userId, groupId, siteId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, reject.
throw error;
}
// The WebService has thrown an error, this means that the page cannot be submitted. Delete it.
await AddonModWikiOffline.deleteNewPage(page.title, subwikiId, wikiId, userId, groupId, siteId);
result.updated = true;
// Page deleted, add the page to discarded pages and add a warning.
const warning = this.getOfflineDataDeletedWarning(page.title, error);
result.discarded.push({
title: page.title,
warning: warning,
});
result.warnings.push(warning);
}
}));
// Sync finished, set sync time.
await CoreUtils.ignoreErrors(this.setSyncTime(subwikiBlockId, siteId));
return result;
}
/**
* Tries to synchronize a wiki.
*
* @param wikiId Wiki ID.
* @param courseId Course ID.
* @param cmId Wiki course module ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved if sync is successful, rejected otherwise.
*/
async syncWiki(wikiId: number, courseId?: number, cmId?: number, siteId?: string): Promise<AddonModWikiSyncWikiResult> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Sync offline logs.
await CoreUtils.ignoreErrors(CoreCourseLogHelper.syncActivity(AddonModWikiProvider.COMPONENT, wikiId, siteId));
// Sync is done at subwiki level, get all the subwikis.
const subwikis = await AddonModWiki.getSubwikis(wikiId, { cmId, siteId });
const result: AddonModWikiSyncWikiResult = {
warnings: [],
updated: false,
subwikis: {},
siteId: siteId,
};
await Promise.all(subwikis.map(async (subwiki) => {
const data = await this.syncSubwiki(subwiki.id, subwiki.wikiid, subwiki.userid, subwiki.groupid, siteId);
if (data && data.updated) {
result.warnings = result.warnings.concat(data.warnings);
result.updated = true;
result.subwikis[subwiki.id] = {
created: data.created,
discarded: data.discarded,
};
}
}));
if (result.updated) {
const promises: Promise<void>[] = [];
// Something has changed, invalidate data.
if (wikiId) {
promises.push(AddonModWiki.invalidateSubwikis(wikiId));
promises.push(AddonModWiki.invalidateSubwikiPages(wikiId));
promises.push(AddonModWiki.invalidateSubwikiFiles(wikiId));
}
if (courseId) {
promises.push(AddonModWiki.invalidateWikiData(courseId));
}
if (cmId) {
promises.push(CoreGroups.invalidateActivityAllowedGroups(cmId));
promises.push(CoreGroups.invalidateActivityGroupMode(cmId));
}
await CoreUtils.ignoreErrors(Promise.all(promises));
}
return result;
}
}
export const AddonModWikiSync = makeSingleton(AddonModWikiSyncProvider);
/**
* Data returned by a subwiki sync.
*/
export type AddonModWikiSyncSubwikiResult = {
warnings: string[]; // List of warnings.
updated: boolean; // Whether data was updated in the site.
created: AddonModWikiCreatedPage[]; // List of created pages.
discarded: AddonModWikiDiscardedPage[]; // List of discarded pages.
};
/**
* Data returned by a wiki sync.
*/
export type AddonModWikiSyncWikiResult = {
warnings: string[]; // List of warnings.
updated: boolean; // Whether data was updated in the site.
subwikis: {
[subwikiId: number]: { // List of subwikis.
created: AddonModWikiCreatedPage[];
discarded: AddonModWikiDiscardedPage[];
};
};
siteId: string; // Site ID.
};
/**
* Data returned by a wiki sync for each subwiki synced.
*/
export type AddonModWikiSyncWikiSubwiki = {
created: AddonModWikiCreatedPage[];
discarded: AddonModWikiDiscardedPage[];
};
/**
* Data to identify a page created in sync.
*/
export type AddonModWikiCreatedPage = {
pageId: number;
title: string;
};
/**
* Data to identify a page discarded in sync.
*/
export type AddonModWikiDiscardedPage = {
title: string;
warning: string;
};
/**
* Data passed to AUTO_SYNCED event.
*/
export type AddonModWikiAutoSyncData = {
siteId: string;
subwikiId: number;
wikiId: number;
userId: number;
groupId: number;
created: AddonModWikiCreatedPage[];
discarded: AddonModWikiDiscardedPage[];
warnings: string[];
};
/**
* Data passed to MANUAL_SYNCED event.
*/
export type AddonModWikiManualSyncData = AddonModWikiSyncWikiResult & {
wikiId: number;
}; | the_stack |
var tl = require('vso-task-lib');
import events = require('events');
import cm = require('../../common');
import utilm = require('../../utilities');
import Q = require('q');
import os = require("os");
var shell = require('shelljs');
var path = require('path');
var xmlReader = require('xmlreader');
import fs = require('fs');
export var administrativeDirectoryName = ".svn";
export interface SvnMappingDetails {
serverPath: string;
localPath: string;
revision: string;
depth: string;
ignoreExternals: boolean;
}
export interface SvnWorkspace {
mappings: SvnMappingDetails[];
}
export interface ISvnMappingDictionary { [path: string]: SvnMappingDetails }
export interface ISvnConnectionEndpoint {
username: string;
password: string;
realmName: string;
acceptUntrusted: boolean;
url: string;
}
export interface ISvnExecOptions {
cwd: string;
env: { [key: string]: string };
silent: boolean;
outStream: NodeJS.WritableStream;
errStream: NodeJS.WritableStream;
failOnStdErr: boolean;
ignoreReturnCode: boolean;
}
export class SvnWrapper extends events.EventEmitter {
constructor(ctx: cm.IExecutionContext) {
super();
this.svnPath = shell.which('svn', false);
this.endpoint = <ISvnConnectionEndpoint>{};
this.ctx = ctx;
}
public svnPath: string;
public endpoint: ISvnConnectionEndpoint;
public ctx: cm.IExecutionContext;
public setSvnConnectionEndpoint(endpoint: ISvnConnectionEndpoint) {
if (endpoint) {
this.endpoint = endpoint;
}
}
public getOldMappings(rootPath: string): Q.Promise<cm.IStringDictionary> {
if (shell.test("-f", rootPath)) {
throw new Error("The file " + rootPath + " already exists.");
}
if (shell.test("-d", rootPath)) {
return this._getSvnWorkingCopyPaths(rootPath)
.then((workingDirectoryPaths: string[]) => {
var mappingsPromise: Q.Promise<cm.IStringDictionary> = Q(<cm.IStringDictionary>{});
if (workingDirectoryPaths) {
var mappings: cm.IStringDictionary = <cm.IStringDictionary>{};
workingDirectoryPaths.forEach((workingDirectoryPath: string) => {
mappingsPromise = mappingsPromise
.then((v) => {
return this._getTargetUrl(workingDirectoryPath)
})
.then((url) => {
if (url) {
mappings[workingDirectoryPath] = url;
}
return Q(mappings);
});
});
}
return mappingsPromise;
});
}
else {
return Q(<cm.IStringDictionary>{});
}
}
private _getSvnWorkingCopyPaths(rootPath: string): Q.Promise<string[]> {
var candidates: string[] = [];
var deferred: Q.Deferred<string[]> = Q.defer<string[]>();
if (shell.test("-d", path.join(rootPath, administrativeDirectoryName))) {
// The rootPath contains .svn subfolder and we treat it as
// a working copy candidate.
deferred.resolve([rootPath]);
}
else {
// Browse direct subfolder children of the rootPath
utilm.readDirectory(rootPath, false, true, utilm.SearchOption.TopDirectoryOnly)
.then((subFolders: string[]) => {
// The first element in the collection returned by the method is the rootPath,
// which we've already tested. Ignore it.
subFolders.shift();
var count = subFolders.length;
if (count > 0) {
subFolders.forEach((subFolder) => {
if (shell.test("-d", path.join(subFolder, administrativeDirectoryName))) {
// The subfolder contains .svn directory and we treat it as
// a working copy candidate.
candidates.push(subFolder);
if (--count == 0) {
deferred.resolve(candidates);
}
}
else {
// Merge working directory paths found in the subfolder into the common candidates collection.
this._getSvnWorkingCopyPaths(subFolder)
.then((moreCandidates) => {
candidates = candidates.concat(moreCandidates);
if (--count == 0) {
deferred.resolve(candidates);
}
})
}
});
}
else {
deferred.resolve(candidates);
}
});
}
return deferred.promise;
}
private _getTargetUrl(folder: string): Q.Promise<string> {
if (!shell.test("-d", folder)) {
throw new Error("Folder " + folder + " does not exists");
}
var deferred = Q.defer<string>();
this._shellExec('info', [folder, "--depth", "empty", "--xml"])
.then((ret) => {
if (!this.isSuccess(ret)) {
deferred.resolve(null);
}
else if (ret.output) {
xmlReader.read(ret.output, (err, res) => {
if (err) {
deferred.reject(err);
}
else {
try {
return deferred.resolve(res.info.entry.url.text());
}
catch (e) {
deferred.reject(e);
}
}
});
}
else {
deferred.resolve(null);
}
});
return deferred.promise;
}
public getLatestRevision(serverPath: string, sourceRevision: string): Q.Promise<string> {
return this._shellExec('info', [this.buildSvnUrl(serverPath),
"--depth", "empty",
"--revision", sourceRevision,
"--xml"])
.then((ret) => {
var defer = Q.defer<any>();
if (!this.isSuccess(ret)) {
defer.reject(ret.output);
}
else {
try {
xmlReader.read(ret.output, (err, res) => {
if (err) {
defer.reject(err);
}
else {
defer.resolve(res);
}
});
}
catch (e) {
defer.reject(e);
}
}
return defer.promise;
})
.then(
(res) => {
var rev: string = res.info.entry.commit.attributes()["revision"];
this.ctx.verbose("Latest revision: " + rev);
return rev;
},
(err) => {
this.ctx.verbose("Subversion call filed: " + err);
this.ctx.verbose("Using the original revision: " + sourceRevision);
return sourceRevision;
}
);
}
public update(svnModule: SvnMappingDetails): Q.Promise<number> {
this.ctx.info("Updating " + svnModule.localPath
+ " with depth: " + svnModule.depth
+ ", revision: " + svnModule.revision
+ ", ignore externals: " + svnModule.ignoreExternals);
var args: string[] = [svnModule.localPath,
'--revision', svnModule.revision,
'--depth', this._toSvnDepth(svnModule.depth)];
if (svnModule.ignoreExternals) {
args.push('--ignore-externals');
}
return this._exec('update', args);
}
public switch(svnModule: SvnMappingDetails): Q.Promise<number> {
this.ctx.info("Switching " + svnModule.localPath
+ " to ^" + svnModule.serverPath
+ " with depth: " + svnModule.depth
+ ", revision: " + svnModule.revision
+ ", ignore externals: " + svnModule.ignoreExternals);
var args: string[] = [svnModule.serverPath,
svnModule.localPath,
'--revision', svnModule.revision,
'--depth', this._toSvnDepth(svnModule.depth)];
if (svnModule.ignoreExternals) {
args.push('--ignore-externals');
}
return this._exec('switch', args);
}
public checkout(svnModule: SvnMappingDetails): Q.Promise<number> {
this.ctx.info("Checking out " + svnModule.localPath
+ " with depth: " + svnModule.depth
+ ", revision: " + svnModule.revision
+ ", ignore externals: " + svnModule.ignoreExternals);
var args: string[] = [svnModule.serverPath,
svnModule.localPath,
'--revision', svnModule.revision,
'--depth', this._toSvnDepth(svnModule.depth)];
if (svnModule.ignoreExternals) {
args.push('--ignore-externals');
}
return this._exec('checkout', args);
}
public buildSvnUrl(serverPath?: string): string {
var url: string = this.endpoint.url;
if ((url == null) || (url.length == 0)) {
throw new Error("Connection endpoint URL cannot be empty.")
}
url = url.replace('\\', '/');
if (serverPath) {
url = this.appendPath(url, serverPath);
}
return url;
}
public appendPath(base: string, path: string): string {
var url = base.replace('\\', '/');
if (path && (path.length > 0)) {
if (!url.endsWith('/')) {
url = url + '/';
}
url = url + path;
}
return url;
}
private _getQuotedArgsWithDefaults(args: string[]): string[] {
// default connection related args
var usernameArg = '--username';
var passwordArg = '--password';
var trustArg = "--trust-server-cert";
var defaults: string[] = [];
if (this.endpoint.username && this.endpoint.username.length > 0) {
defaults.push(usernameArg, this.endpoint.username);
}
if (this.endpoint.password && this.endpoint.password.length > 0) {
defaults.push(passwordArg, this.endpoint.password);
}
if (this.endpoint.acceptUntrusted) {
defaults.push(trustArg);
}
var quotedArg = function(arg) {
var quote = '"';
if (arg.indexOf('"') > -1) {
quote = '\'';
}
return quote + arg + quote;
}
return args.concat(defaults).map((a) => quotedArg(a));
}
private _scrubCredential(msg: string): string {
if (msg && typeof msg.replace === 'function'
&& this.endpoint.password) {
return msg.replace(this.endpoint.password, cm.MASK_REPLACEMENT);
}
return msg;
}
private _exec(cmd: string, args: string[], options?: ISvnExecOptions): Q.Promise<number> {
if (this.svnPath === null) {
return this._getSvnNotInstalled();
}
var svn = new tl.ToolRunner(this.svnPath);
svn.silent = !this.isDebugMode();
svn.on('debug', (message) => {
this.emit('stdout', '[debug]' + this._scrubCredential(message));
})
svn.on('stdout', (data) => {
this.emit('stdout', this._scrubCredential(data));
})
svn.on('stderr', (data) => {
this.emit('stderr', this._scrubCredential(data));
})
// cmd
svn.arg(cmd, true);
var quotedArgs = this._getQuotedArgsWithDefaults(args);
// args
quotedArgs.map((arg: string) => {
svn.arg(arg, true); // raw arg
});
options = options || <ISvnExecOptions>{};
var ops: any = {
cwd: options.cwd || process.cwd(),
env: options.env || process.env,
silent: !this.isDebugMode(),
outStream: options.outStream || process.stdout,
errStream: options.errStream || process.stderr,
failOnStdErr: options.failOnStdErr || false,
ignoreReturnCode: options.ignoreReturnCode || false
};
return svn.exec(ops);
}
private _shellExec(cmd, args: string[]): Q.Promise<any> {
if (this.svnPath === null) {
return this._getSvnNotInstalled();
}
var cmdline = this.svnPath + ' ' + cmd + ' ' + this._getQuotedArgsWithDefaults(args).join(' ');
return utilm.exec(cmdline)
.then ((v) => {
this.ctx.verbose(this._scrubCredential(cmdline));
this.ctx.verbose(JSON.stringify(v));
return v;
});
}
private _getSvnNotInstalled(): Q.Promise<number>{
return Q.reject<number>(new Error("'svn' was not found. Please install the Subversion command-line client and add 'svn' to the path."));
}
private _toSvnDepth(depth): string {
return depth == "0" ? 'empty' :
depth == "1" ? 'files' :
depth == "2" ? 'immediates' :
depth == "3" ? 'infinity' :
depth || 'infinity';
}
public isSuccess(ret): boolean {
return ret && ret.code === 0;
}
public isDebugMode(): boolean {
var environment = this.ctx.jobInfo.jobMessage.environment;
var debugMode: string = environment.variables["system.debug"] || 'false';
return debugMode === 'true';
}
} | the_stack |
import { DebugProtocol } from 'vscode-debugprotocol';
import { Handles } from 'vscode-debugadapter';
import { IStackTraceResponseBody,
IInternalStackTraceResponseBody } from '../debugAdapterInterfaces';
import { Protocol as Crdp } from 'devtools-protocol';
import { Transformers } from './chromeDebugAdapter';
import { ScriptContainer } from './scripts';
import { SmartStepper } from './smartStep';
import { ScriptSkipper } from './scriptSkipping';
import * as ChromeUtils from './chromeUtils';
import * as utils from '../utils';
import * as path from 'path';
import * as nls from 'vscode-nls';
import * as errors from '../errors';
import { VariablesManager } from './variablesManager';
import { ScopeContainer, ExceptionContainer } from './variables';
let localize = nls.loadMessageBundle();
export class StackFrames {
private _frameHandles = new Handles<Crdp.Debugger.CallFrame>();
constructor() {}
/**
* Clear the currently stored stack frames
*/
reset() {
this._frameHandles.reset();
}
/**
* Get a stack frame by its id
*/
getFrame(frameId: number) {
return this._frameHandles.get(frameId);
}
public async getStackTrace({ args, scripts, originProvider, scriptSkipper, smartStepper, transformers, pauseEvent }:
{ args: DebugProtocol.StackTraceArguments;
scripts: ScriptContainer;
originProvider: (url: string) => string;
scriptSkipper: ScriptSkipper;
smartStepper: SmartStepper;
transformers: Transformers;
pauseEvent: Crdp.Debugger.PausedEvent; }): Promise<IStackTraceResponseBody> {
let stackFrames = pauseEvent.callFrames.map(frame => this.callFrameToStackFrame(frame, scripts, originProvider))
.concat(this.asyncFrames(pauseEvent.asyncStackTrace, scripts, originProvider));
const totalFrames = stackFrames.length;
if (typeof args.startFrame === 'number') {
stackFrames = stackFrames.slice(args.startFrame);
}
if (typeof args.levels === 'number') {
stackFrames = stackFrames.slice(0, args.levels);
}
const stackTraceResponse: IInternalStackTraceResponseBody = {
stackFrames,
totalFrames
};
await transformers.pathTransformer.stackTraceResponse(stackTraceResponse);
await transformers.sourceMapTransformer.stackTraceResponse(stackTraceResponse);
await Promise.all(stackTraceResponse.stackFrames.map(async (frame) => {
// Remove isSourceMapped to convert back to DebugProtocol.StackFrame
const isSourceMapped = frame.isSourceMapped;
delete frame.isSourceMapped;
if (!frame.source) {
return;
}
// Apply hints to skipped frames
const getSkipReason = reason => localize('skipReason', "(skipped by '{0}')", reason);
if (frame.source.path && scriptSkipper.shouldSkipSource(frame.source.path)) {
frame.source.origin = (frame.source.origin ? frame.source.origin + ' ' : '') + getSkipReason('skipFiles');
frame.source.presentationHint = 'deemphasize';
} else if (!isSourceMapped && await smartStepper.shouldSmartStep(frame, transformers.pathTransformer, transformers.sourceMapTransformer)) {
// TODO !isSourceMapped is a bit of a hack here
frame.source.origin = (frame.source.origin ? frame.source.origin + ' ' : '') + getSkipReason('smartStep');
(<any>frame).presentationHint = 'deemphasize';
}
// Allow consumer to adjust final path
if (frame.source.path && frame.source.sourceReference) {
frame.source.path = scripts.realPathToDisplayPath(frame.source.path);
}
// And finally, remove the fake eval path and fix the name, if it was never resolved to a real path
if (frame.source.path && ChromeUtils.isEvalScript(frame.source.path)) {
frame.source.path = undefined;
frame.source.name = scripts.displayNameForSourceReference(frame.source.sourceReference);
}
}));
transformers.lineColTransformer.stackTraceResponse(stackTraceResponse);
stackTraceResponse.stackFrames.forEach(frame => frame.name = this.formatStackFrameName(frame, args.format));
return stackTraceResponse;
}
getScopes({ args, scripts, transformers, variables, pauseEvent, currentException }:
{ args: DebugProtocol.ScopesArguments;
scripts: ScriptContainer;
transformers: Transformers;
variables: VariablesManager;
pauseEvent: Crdp.Debugger.PausedEvent;
currentException: any; }): { scopes: DebugProtocol.Scope[]; } {
const currentFrame = this._frameHandles.get(args.frameId);
if (!currentFrame || !currentFrame.location || !currentFrame.callFrameId) {
throw errors.stackFrameNotValid();
}
if (!currentFrame.callFrameId) {
return { scopes: [] };
}
const currentScript = scripts.getScriptById(currentFrame.location.scriptId);
const currentScriptUrl = currentScript && currentScript.url;
const currentScriptPath = (currentScriptUrl && transformers.pathTransformer.getClientPathFromTargetPath(currentScriptUrl)) || currentScriptUrl;
const scopes = currentFrame.scopeChain.map((scope: Crdp.Debugger.Scope, i: number) => {
// The first scope should include 'this'. Keep the RemoteObject reference for use by the variables request
const thisObj = i === 0 && currentFrame.this;
const returnValue = i === 0 && currentFrame.returnValue;
const variablesReference = variables.createHandle(
new ScopeContainer(currentFrame.callFrameId, i, scope.object.objectId, thisObj, returnValue));
const resultScope = <DebugProtocol.Scope>{
name: scope.type.substr(0, 1).toUpperCase() + scope.type.substr(1), // Take Chrome's scope, uppercase the first letter
variablesReference,
expensive: scope.type === 'global'
};
if (scope.startLocation && scope.endLocation) {
resultScope.column = scope.startLocation.columnNumber;
resultScope.line = scope.startLocation.lineNumber;
resultScope.endColumn = scope.endLocation.columnNumber;
resultScope.endLine = scope.endLocation.lineNumber;
}
return resultScope;
});
if (currentException && this.lookupFrameIndex(args.frameId, pauseEvent) === 0) {
scopes.unshift(<DebugProtocol.Scope>{
name: localize('scope.exception', 'Exception'),
variablesReference: variables.createHandle(ExceptionContainer.create(currentException))
});
}
const scopesResponse = { scopes };
if (currentScriptPath) {
transformers.sourceMapTransformer.scopesResponse(currentScriptPath, scopesResponse);
transformers.lineColTransformer.scopeResponse(scopesResponse);
}
return scopesResponse;
}
public async mapCallFrame(frame: Crdp.Runtime.CallFrame, transformers: Transformers, scripts: ScriptContainer, originProvider: (url: string) => string ): Promise<DebugProtocol.StackFrame> {
const debuggerCF = this.runtimeCFToDebuggerCF(frame);
const stackFrame = this.callFrameToStackFrame(debuggerCF, scripts, originProvider);
await transformers.pathTransformer.fixSource(stackFrame.source);
await transformers.sourceMapTransformer.fixSourceLocation(stackFrame);
transformers.lineColTransformer.convertDebuggerLocationToClient(stackFrame);
return stackFrame;
}
// We parse stack trace from `formattedException`, source map it and return a new string
public async mapFormattedException(formattedException: string, transformers: Transformers): Promise<string> {
const exceptionLines = formattedException.split(/\r?\n/);
for (let i = 0, len = exceptionLines.length; i < len; ++i) {
const line = exceptionLines[i];
const matches = line.match(/^\s+at (.*?)\s*\(?([^ ]+):(\d+):(\d+)\)?$/);
if (!matches) continue;
const linePath = matches[2];
const lineNum = parseInt(matches[3], 10);
const adjustedLineNum = lineNum - 1;
const columnNum = parseInt(matches[4], 10);
const clientPath = transformers.pathTransformer.getClientPathFromTargetPath(linePath);
const mapped = await transformers.sourceMapTransformer.mapToAuthored(clientPath || linePath, adjustedLineNum, columnNum);
if (mapped && mapped.source && utils.isNumber(mapped.line) && utils.isNumber(mapped.column) && utils.existsSync(mapped.source)) {
transformers.lineColTransformer.mappedExceptionStack(mapped);
exceptionLines[i] = exceptionLines[i].replace(
`${linePath}:${lineNum}:${columnNum}`,
`${mapped.source}:${mapped.line}:${mapped.column}`);
} else if (clientPath && clientPath !== linePath) {
const location = { line: adjustedLineNum, column: columnNum };
transformers.lineColTransformer.mappedExceptionStack(location);
exceptionLines[i] = exceptionLines[i].replace(
`${linePath}:${lineNum}:${columnNum}`,
`${clientPath}:${location.line}:${location.column}`);
}
}
return exceptionLines.join('\n');
}
private asyncFrames(stackTrace: Crdp.Runtime.StackTrace, scripts: ScriptContainer, originProvider: (url: string) => string): DebugProtocol.StackFrame[] {
if (stackTrace) {
const frames = stackTrace.callFrames
.map(frame => this.runtimeCFToDebuggerCF(frame))
.map(frame => this.callFrameToStackFrame(frame, scripts, originProvider));
frames.unshift({
id: this._frameHandles.create(null),
name: `[ ${stackTrace.description} ]`,
source: undefined,
line: undefined,
column: undefined,
presentationHint: 'label'
});
return frames.concat(this.asyncFrames(stackTrace.parent, scripts, originProvider));
} else {
return [];
}
}
private runtimeCFToDebuggerCF(frame: Crdp.Runtime.CallFrame): Crdp.Debugger.CallFrame {
return {
callFrameId: undefined,
scopeChain: undefined,
this: undefined,
location: {
lineNumber: frame.lineNumber,
columnNumber: frame.columnNumber,
scriptId: frame.scriptId
},
url: frame.url,
functionName: frame.functionName
};
}
private formatStackFrameName(frame: DebugProtocol.StackFrame, formatArgs?: DebugProtocol.StackFrameFormat): string {
let formattedName = frame.name;
if (frame.source && formatArgs) {
if (formatArgs.module) {
formattedName += ` [${frame.source.name}]`;
}
if (formatArgs.line) {
formattedName += ` Line ${frame.line}`;
}
}
return formattedName;
}
public callFrameToStackFrame(frame: Crdp.Debugger.CallFrame, scripts: ScriptContainer, originProvider: (url: string) => string): DebugProtocol.StackFrame {
const { location, functionName } = frame;
const line = location.lineNumber;
const column = location.columnNumber;
const script = scripts.getScriptById(location.scriptId);
try {
// When the script has a url and isn't one we're ignoring, send the name and path fields. PathTransformer will
// attempt to resolve it to a script in the workspace. Otherwise, send the name and sourceReference fields.
const sourceReference = scripts.getSourceReferenceForScriptId(script.scriptId);
const source: DebugProtocol.Source = {
name: path.basename(script.url),
path: script.url,
sourceReference,
origin: originProvider(script.url)
};
// If the frame doesn't have a function name, it's either an anonymous function
// or eval script. If its source has a name, it's probably an anonymous function.
const frameName = functionName || (script.url ? '(anonymous function)' : '(eval code)');
return {
id: this._frameHandles.create(frame),
name: frameName,
source,
line,
column
};
} catch (e) {
// Some targets such as the iOS simulator behave badly and return nonsense callFrames.
// In these cases, return a dummy stack frame
const evalUnknown = `${ChromeUtils.EVAL_NAME_PREFIX}_Unknown`;
return {
id: this._frameHandles.create(<any>{ }),
name: evalUnknown,
source: { name: evalUnknown, path: evalUnknown },
line,
column
};
}
}
/**
* Try to lookup the index of the frame with given ID. Returns -1 for async frames and unknown frames.
*/
public lookupFrameIndex(frameId: number, pauseEvent: Crdp.Debugger.PausedEvent): number {
const currentFrame = this._frameHandles.get(frameId);
if (!currentFrame || !currentFrame.callFrameId || !pauseEvent) {
return -1;
}
return pauseEvent.callFrames.findIndex(frame => frame.callFrameId === currentFrame.callFrameId);
}
} | the_stack |
import WebSocket from 'isomorphic-ws';
import {Tree} from './tree';
export function MakeTree(): Tree {
return new Tree();
}
export class Connection {
// how long between retries
backoff: number;
maximum_backoff: number;
// the websocket address
url: string;
// are we connected?
connected: boolean;
// are we dead? if we are dead, then we will stop retrying
dead: boolean;
// has a retry been scheduled?
scheduled: boolean;
// the socket
socket: WebSocket | null;
// the callbacks for the various inflight operations
callbacks: Map<number, (result: object) => void>;
// the unique id for this connection
rpcid: number;
// event: the status of connection has changed. true => connected & auth, false => not connected
onstatuschange: (status: boolean) => void;
// event: a ping from the client
onping: (seconds: number, latency: number) => void;
// event: we can connect, but we need auth credentials to make progress
onauthneeded: (tryagain: () => void) => void;
connectId: number;
onreconnect: Map<number, object>;
sessionId : string;
sendId : number;
constructor(url: string) {
var self = this;
this.backoff = 1;
this.url = url;
this.connected = false;
this.dead = false;
this.maximum_backoff = 2500;
this.socket = null;
this.onstatuschange = function (status: boolean) {
};
this.onping = function (seconds: number, latency: number) {
};
this.onauthneeded = function (tryagain: () => void) {
};
this.scheduled = false;
this.callbacks = new Map<number, (result: object) => void>();
this.connectId = 1;
this.onreconnect = new Map<number, object>();
this.rpcid = 1;
this.sessionId = "";
this.sendId = 0;
}
/** stop the connection */
stop() {
this.dead = true;
if (this.socket !== null) {
this.socket.close();
}
}
/** private: retry the connection */
_retry() {
// null out the socket
this.socket = null;
// if we are connected, transition the status
if (this.connected) {
this.connected = false;
this.onstatuschange(false);
}
// fail all outstanding operations
this.callbacks.forEach(function (callback: (result: object) => void, id: number) {
callback({ failure: id, reason: 77 });
});
this.callbacks.clear();
// if we are dead, then don't actually retry
if (this.dead) {
return;
}
// make sure
if (!this.scheduled) {
// schedule a retry; first compute how long to take
// compute how long we need to wait
var halveAfterSchedule = false;
this.backoff += Math.random() * this.backoff;
if (this.backoff > this.maximum_backoff) {
this.backoff = this.maximum_backoff;
halveAfterSchedule = true;
}
// schedule it
this.scheduled = true;
var self = this;
setTimeout(function () { self.start(); }, this.backoff);
// we just scheduled it for the maximum backoff time, let's reduce the backoff so the next one will have some jitter
if (halveAfterSchedule) {
this.backoff /= 2.0;
}
}
}
/** start the connection */
start() {
// reset the state
var self = this;
this.scheduled = false;
this.dead = false;
// create the socket and bind event handlers
this.socket = new WebSocket(this.url);
this.socket.onmessage = function (event: WebSocket.MessageEvent) {
var result = JSON.parse(event.data);
// a message arrived, is it a connection signal
if ('ping' in result) {
self.onping(result.ping, result.latency);
result.pong = new Date().getTime() / 1000.0;
self.socket.send(JSON.stringify(result));
return;
}
if ('signal' in result) {
// hey, are we connected?
if (result.status != 'connected') {
// nope, OK, let's make this a dead socket
self.dead = true;
self.socket.close();
self.socket = null;
// inform the client to try again
self.onauthneeded(function () {
self.start();
});
return;
}
// tell the client that we are good!
self.backoff = 1;
self.connected = true;
self.sessionId = result.session_id;
self.onstatuschange(true);
self._reconnect();
return;
}
// the result was a failure..
if ('failure' in result) {
// find the callback, then invoke it (and clean up)
if (self.callbacks.has(result.failure)) {
var cb = self.callbacks.get(result.failure);
if (cb) {
self.callbacks.delete(result.failure);
cb(result);
}
}
} else if ('deliver' in result) {
// otherwise, we have a success, so let's find the callback, and if need be clean up
if (self.callbacks.has(result.deliver)) {
var cb = self.callbacks.get(result.deliver);
if (cb) {
if (result.done) {
self.callbacks.delete(result.deliver);
}
cb(result.response);
}
}
}
};
this.socket.onclose = function (event: WebSocket.CloseEvent) {
// let's retry... or should we not
self._retry();
};
this.socket.onerror = function (event: WebSocket.ErrorEvent) {
// something bad happened, let's retry
self._retry();
};
}
/** private: send a raw message */
_send(request: { [k: string]: any }, callback: (result: object) => void) {
if (!this.connected) {
callback({ failure: 600, reason: 9999 });
return;
}
var id = this.rpcid;
this.rpcid++;
request['id'] = id;
this.callbacks.set(id, callback);
this.socket.send(JSON.stringify(request));
}
/** api: wait for a connection */
async wait_connected() {
if (this.connected) {
return;
}
var self = this;
var prior = this.onstatuschange;
return new Promise(function (good) {
self.onstatuschange = function (status) {
prior(status);
if (status) {
good();
self.onstatuschange = prior;
}
};
});
}
/** api: generate a new game */
async generate(gs: string) {
var request = { method: "reserve", space: gs };
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response.key);
}
});
});
}
/** api: get the schema for the gamepsace */
async reflect(gs: string) {
var request = { method: "reflect", space: gs, key:'0' };
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
async load_code(gs: string) {
var request = { method: "load_code", space: gs };
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
async save_code(gs: string, code: string) {
var request = { method: "save_code", space: gs, code: code};
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
async deploy(gs: string) {
var request = { method: "deploy", space: gs};
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
/** api: generate a new game */
async create(gs: string, id: string, arg: object) {
var request = { method: "create", space: gs, key: id, arg: arg };
var self = this;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
/** api: connect to a game */
async connect(gs: string, id: string, handler: (data: object) => void) {
var request = { method: "connect", space: gs, key: id };
var self = this;
var first = true;
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if (first) {
first = false;
if ('failure' in response) {
bad(response.reason)
} else {
handler(response);
good(true);
}
} else {
handler(response);
}
});
});
}
/** api: send a message */
async send(gs: string, id: string, channel: string, msg: any, hack: (request: any) => void) {
var self = this;
var request = {method: "send", marker: self.sessionId = "/" + self.sendId, space: gs, key: id, channel: channel, message: msg};
self.sendId ++;
if (hack) {
hack(request);
}
// TODO: queue this up? with retry?
return new Promise(function (good, bad) {
self._send(request, function (response: { [k: string]: any }) {
if ('failure' in response) {
bad(response.reason)
} else {
good(response);
}
});
});
}
/** api: connect tree */
async connectTree(gs: string, id: string, tree: Tree, hack: (request: any) => void) {
var keyId = this.connectId;
this.connectId++;
let sm = {
request: {method: "connect", space: gs, key: id},
first: true,
handler: function (r: any) {
tree.mergeUpdate(r);
}
};
if (hack) {
hack(sm.request);
}
this.onreconnect.set(keyId, sm);
return this._execute(sm);
}
_reconnect() {
var self = this;
this.onreconnect.forEach(function (sm: object, id: number) {
self._execute(sm);
});
}
async _execute(sm: any) {
var self = this;
return new Promise(function (good, bad) {
self._send(sm.request, function (response: { [k: string]: any }) {
if (sm.first) {
sm.first = false;
if ('failure' in response) {
bad(response.reason)
} else {
sm.handler(response);
good(true);
}
} else {
sm.handler(response);
}
});
});
}
} | the_stack |
import { Transaction } from "./Transaction";
import { Set } from "typescript-collections";
let totalRegistrations : number = 0;
export function getTotalRegistrations() : number {
return totalRegistrations;
}
export class Source {
// Note:
// When register_ == null, a rank-independent source is constructed (a vertex which is just kept alive for the
// lifetime of vertex that contains this source).
// When register_ != null it is likely to be a rank-dependent source, but this will depend on the code inside register_.
//
// rank-independent souces DO NOT bump up the rank of the vertex containing those sources.
// rank-depdendent sources DO bump up the rank of the vertex containing thoses sources when required.
constructor(
origin : Vertex,
register_ : () => () => void
) {
if (origin === null)
throw new Error("null origin!");
this.origin = origin;
this.register_ = register_;
}
origin : Vertex;
private register_ : () => () => void;
private registered : boolean = false;
private deregister_ : () => void = null;
register(target : Vertex) : void {
if (!this.registered) {
this.registered = true;
if (this.register_ !== null)
this.deregister_ = this.register_();
else {
// Note: The use of Vertex.NULL here instead of "target" is not a bug, this is done to create a
// rank-independent source. (see note at constructor for more details.). The origin vertex still gets
// added target vertex's children for the memory management algorithm.
this.origin.increment(Vertex.NULL);
target.childrn.push(this.origin);
this.deregister_ = () => {
this.origin.decrement(Vertex.NULL);
for (let i = target.childrn.length-1; i >= 0; --i) {
if (target.childrn[i] === this.origin) {
target.childrn.splice(i, 1);
break;
}
}
}
}
}
}
deregister(target : Vertex) : void {
if (this.registered) {
this.registered = false;
if (this.deregister_ !== null)
this.deregister_();
}
}
}
export enum Color { black, gray, white, purple };
let roots : Vertex[] = [];
let nextID : number = 0;
let verbose : boolean = false;
export function setVerbose(v : boolean) : void { verbose = v; }
export function describeAll(v : Vertex, visited : Set<number>)
{
if (visited.contains(v.id)) return;
console.log(v.descr());
visited.add(v.id);
let chs = v.children();
for (let i = 0; i < chs.length; i++)
describeAll(chs[i], visited);
}
export class Vertex {
static NULL : Vertex = new Vertex("user", 1e12, []);
static collectingCycles : boolean = false;
static toBeFreedList : Vertex[] = [];
id : number;
constructor(name : string, rank : number, sources : Source[]) {
this.name = name;
this.rank = rank;
this.sources = sources;
this.id = nextID++;
}
name : string;
rank : number;
sources : Source[];
targets : Vertex[] = [];
childrn : Vertex[] = [];
refCount() : number { return this.targets.length; };
visited : boolean = false;
register(target : Vertex) : boolean {
return this.increment(target);
}
deregister(target : Vertex) : void {
if (verbose)
console.log("deregister "+this.descr()+" => "+target.descr());
this.decrement(target);
Transaction._collectCyclesAtEnd();
}
private incRefCount(target : Vertex) : boolean {
let anyChanged : boolean = false;
if (this.refCount() == 0) {
for (let i = 0; i < this.sources.length; i++)
this.sources[i].register(this);
}
this.targets.push(target);
target.childrn.push(this);
if (target.ensureBiggerThan(this.rank))
anyChanged = true;
totalRegistrations++;
return anyChanged;
}
private decRefCount(target : Vertex) : void {
if (verbose)
console.log("DEC "+this.descr());
let matched = false;
for (let i = target.childrn.length-1; i >= 0; i--)
if (target.childrn[i] === this) {
target.childrn.splice(i, 1);
break;
}
for (let i = 0; i < this.targets.length; i++)
if (this.targets[i] === target) {
this.targets.splice(i, 1);
matched = true;
break;
}
if (matched) {
if (this.refCount() == 0) {
for (let i = 0; i < this.sources.length; i++)
this.sources[i].deregister(this);
}
totalRegistrations--;
}
}
addSource(src : Source) : void {
this.sources.push(src);
if (this.refCount() > 0)
src.register(this);
}
private ensureBiggerThan(limit : number) : boolean {
if (this.visited) {
// Undoing cycle detection for now until TimerSystem.ts ranks are checked.
//throw new Error("Vertex cycle detected.");
return false;
}
if (this.rank > limit)
return false;
this.visited = true;
this.rank = limit + 1;
for (let i = 0; i < this.targets.length; i++)
this.targets[i].ensureBiggerThan(this.rank);
this.visited = false;
return true;
}
descr() : string {
let colStr : string = null;
switch (this.color) {
case Color.black: colStr = "black"; break;
case Color.gray: colStr = "gray"; break;
case Color.white: colStr = "white"; break;
case Color.purple: colStr = "purple"; break;
}
let str = this.id+" "+this.name+" ["+this.refCount()+"/"+this.refCountAdj+"] "+colStr+" ->";
let chs = this.children();
for (let i = 0; i < chs.length; i++) {
str = str + " " + chs[i].id;
}
return str;
}
// --------------------------------------------------------
// Synchronous Cycle Collection algorithm presented in "Concurrent
// Cycle Collection in Reference Counted Systems" by David F. Bacon
// and V.T. Rajan.
color : Color = Color.black;
buffered : boolean = false;
refCountAdj : number = 0;
children() : Vertex[] { return this.childrn; }
increment(referrer : Vertex) : boolean {
return this.incRefCount(referrer);
}
decrement(referrer : Vertex) : void {
this.decRefCount(referrer);
if (this.refCount() == 0)
this.release();
else
this.possibleRoots();
}
release() : void {
this.color = Color.black;
if (!this.buffered)
this.free();
}
free() : void {
while (this.targets.length > 0)
this.decRefCount(this.targets[0]);
}
possibleRoots() : void {
if (this.color != Color.purple) {
this.color = Color.purple;
if (!this.buffered) {
this.buffered = true;
roots.push(this);
}
}
}
static collectCycles() : void {
if (Vertex.collectingCycles) {
return;
}
try {
Vertex.collectingCycles = true;
Vertex.markRoots();
Vertex.scanRoots();
Vertex.collectRoots();
for (let i = Vertex.toBeFreedList.length-1; i >= 0; --i) {
let vertex = Vertex.toBeFreedList.splice(i, 1)[0];
vertex.free();
}
} finally {
Vertex.collectingCycles = false;
}
}
static markRoots() : void {
const newRoots : Vertex[] = [];
// check refCountAdj was restored to zero before mark roots
if (verbose) {
let stack: Vertex[] = roots.slice(0);
let visited: Set<number> = new Set();
while (stack.length != 0) {
let vertex = stack.pop();
if (visited.contains(vertex.id)) {
continue;
}
visited.add(vertex.id);
if (vertex.refCountAdj != 0) {
console.log("markRoots(): reachable refCountAdj was not reset to zero: " + vertex.descr());
}
for (let i = 0; i < vertex.childrn.length; ++i) {
let child = vertex.childrn[i];
stack.push(child);
}
}
}
//
for (let i = 0; i < roots.length; i++) {
if (verbose)
console.log("markRoots "+roots[i].descr()); // ###
if (roots[i].color == Color.purple) {
roots[i].markGray();
newRoots.push(roots[i]);
}
else {
roots[i].buffered = false;
if (roots[i].color == Color.black && roots[i].refCount() == 0)
Vertex.toBeFreedList.push(roots[i]);
}
}
roots = newRoots;
}
static scanRoots() : void {
for (let i = 0; i < roots.length; i++)
roots[i].scan();
}
static collectRoots() : void {
for (let i = 0; i < roots.length; i++) {
roots[i].buffered = false;
roots[i].collectWhite();
}
if (verbose) { // double check adjRefCount is zero for all vertices reachable by roots
let stack: Vertex[] = roots.slice(0);
let visited: Set<number> = new Set();
while (stack.length != 0) {
let vertex = stack.pop();
if (visited.contains(vertex.id)) {
continue;
}
visited.add(vertex.id);
if (vertex.refCountAdj != 0) {
console.log("collectRoots(): reachable refCountAdj was not reset to zero: " + vertex.descr());
}
for (let i = 0; i < vertex.childrn.length; ++i) {
let child = vertex.childrn[i];
stack.push(child);
}
}
}
roots = [];
}
markGray() : void {
if (this.color != Color.gray) {
this.color = Color.gray;
let chs = this.children();
for (let i = 0; i < chs.length; i++) {
chs[i].refCountAdj--;
if (verbose)
console.log("markGray "+this.descr());
chs[i].markGray();
}
}
}
scan() : void {
if (verbose)
console.log("scan "+this.descr());
if (this.color == Color.gray) {
if (this.refCount()+this.refCountAdj > 0)
this.scanBlack();
else {
this.color = Color.white;
if (verbose)
console.log("scan WHITE "+this.descr());
let chs = this.children();
for (let i = 0; i < chs.length; i++)
chs[i].scan();
}
}
}
scanBlack() : void {
this.refCountAdj = 0;
this.color = Color.black;
let chs = this.children();
for (let i = 0; i < chs.length; i++) {
if (verbose)
console.log("scanBlack "+this.descr());
if (chs[i].color != Color.black)
chs[i].scanBlack();
}
}
collectWhite() : void {
if (this.color == Color.white && !this.buffered) {
if (verbose)
console.log("collectWhite "+this.descr());
this.color = Color.black;
this.refCountAdj = 0;
let chs = this.children();
for (let i = 0; i < chs.length; i++)
chs[i].collectWhite();
Vertex.toBeFreedList.push(this);
}
}
} | the_stack |
// Additional WinRT type definitions can be found at
// https://github.com/borisyankov/DefinitelyTyped/blob/master/winrt/winrt.d.ts
export declare module Windows {
export module Foundation {
export interface Point {
x: number;
y: number;
}
export interface Rect {
x: number;
y: number;
width: number;
height: number;
}
}
}
export declare module Windows {
export module Foundation {
export module Collections {
export enum CollectionChange {
reset,
itemInserted,
itemRemoved,
itemChanged,
}
export interface IVectorChangedEventArgs {
collectionChange: Windows.Foundation.Collections.CollectionChange;
index: number;
}
export interface IPropertySet extends Windows.Foundation.Collections.IObservableMap<string, any>, Windows.Foundation.Collections.IMap<string, any>, Windows.Foundation.Collections.IIterable<Windows.Foundation.Collections.IKeyValuePair<string, any>> {
}
export class PropertySet implements Windows.Foundation.Collections.IPropertySet, Windows.Foundation.Collections.IObservableMap<string, any>, Windows.Foundation.Collections.IMap<string, any>, Windows.Foundation.Collections.IIterable<Windows.Foundation.Collections.IKeyValuePair<string, any>> {
size: number;
onmapchanged: any/* TODO */;
lookup(key: string): any;
hasKey(key: string): boolean;
getView(): Windows.Foundation.Collections.IMapView<string, any>;
insert(key: string, value: any): boolean;
remove(key: string): void;
clear(): void;
first(): Windows.Foundation.Collections.IIterator<Windows.Foundation.Collections.IKeyValuePair<string, any>>;
}
export interface IIterable<T> {
first(): Windows.Foundation.Collections.IIterator<T>;
}
export interface IIterator<T> {
current: T;
hasCurrent: boolean;
moveNext(): boolean;
getMany(): { items: T[]; returnValue: number; };
}
export interface IVectorView<T> extends Windows.Foundation.Collections.IIterable<T> {
size: number;
getAt(index: number): T;
indexOf(value: T): { index: number; returnValue: boolean; };
getMany(startIndex: number): { items: T[]; returnValue: number; };
toString(): string;
toLocaleString(): string;
concat(...items: T[][]): T[];
join(seperator: string): string;
pop(): T;
push(...items: T[]): void;
reverse(): T[];
shift(): T;
slice(start: number): T[];
slice(start: number, end: number): T[];
sort(): T[];
sort(compareFn: (a: T, b: T) => number): T[];
splice(start: number): T[];
splice(start: number, deleteCount: number, ...items: T[]): T[];
unshift(...items: T[]): number;
lastIndexOf(searchElement: T): number;
lastIndexOf(searchElement: T, fromIndex: number): number;
every(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean;
every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean;
some(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean;
some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean;
forEach(callbackfn: (value: T, index: number, array: T[]) => void): void;
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg: any): void;
map(callbackfn: (value: T, index: number, array: T[]) => any): any[];
map(callbackfn: (value: T, index: number, array: T[]) => any, thisArg: any): any[];
filter(callbackfn: (value: T, index: number, array: T[]) => boolean): T[];
filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): T[];
reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any;
reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any;
reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any;
reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any;
length: number;
}
export interface IVector<T> extends Windows.Foundation.Collections.IIterable<T> {
size: number;
getAt(index: number): T;
getView(): Windows.Foundation.Collections.IVectorView<T>;
indexOf(value: T): { index: number; returnValue: boolean; };
setAt(index: number, value: T): void;
insertAt(index: number, value: T): void;
removeAt(index: number): void;
append(value: T): void;
removeAtEnd(): void;
clear(): void;
getMany(startIndex: number): { items: T[]; returnValue: number; };
replaceAll(items: T[]): void;
toString(): string;
toLocaleString(): string;
concat(...items: T[][]): T[];
join(seperator: string): string;
pop(): T;
push(...items: T[]): void;
reverse(): T[];
shift(): T;
slice(start: number): T[];
slice(start: number, end: number): T[];
sort(): T[];
sort(compareFn: (a: T, b: T) => number): T[];
splice(start: number): T[];
splice(start: number, deleteCount: number, ...items: T[]): T[];
unshift(...items: T[]): number;
lastIndexOf(searchElement: T): number;
lastIndexOf(searchElement: T, fromIndex: number): number;
every(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean;
every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean;
some(callbackfn: (value: T, index: number, array: T[]) => boolean): boolean;
some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): boolean;
forEach(callbackfn: (value: T, index: number, array: T[]) => void): void;
forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg: any): void;
map(callbackfn: (value: T, index: number, array: T[]) => any): any[];
map(callbackfn: (value: T, index: number, array: T[]) => any, thisArg: any): any[];
filter(callbackfn: (value: T, index: number, array: T[]) => boolean): T[];
filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg: any): T[];
reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any;
reduce(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any;
reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any): any;
reduceRight(callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: T[]) => any, initialValue: any): any;
length: number;
}
export interface IKeyValuePair<K, V> {
key: K;
value: V;
}
export interface IMap<K, V> extends Windows.Foundation.Collections.IIterable<Windows.Foundation.Collections.IKeyValuePair<K, V>> {
size: number;
lookup(key: K): V;
hasKey(key: K): boolean;
getView(): Windows.Foundation.Collections.IMapView<K, V>;
insert(key: K, value: V): boolean;
remove(key: K): void;
clear(): void;
}
export interface IMapView<K, V> extends Windows.Foundation.Collections.IIterable<Windows.Foundation.Collections.IKeyValuePair<K, V>> {
size: number;
lookup(key: K): V;
hasKey(key: K): boolean;
split(): { first: Windows.Foundation.Collections.IMapView<K, V>; second: Windows.Foundation.Collections.IMapView<K, V>; };
}
export interface VectorChangedEventHandler<T> {
(sender: Windows.Foundation.Collections.IObservableVector<T>, event: Windows.Foundation.Collections.IVectorChangedEventArgs): void;
}
export interface IObservableVector<T> extends Windows.Foundation.Collections.IVector<T>, Windows.Foundation.Collections.IIterable<T> {
onvectorchanged: any/* TODO */;
}
export interface IMapChangedEventArgs<K> {
collectionChange: Windows.Foundation.Collections.CollectionChange;
key: K;
}
export interface MapChangedEventHandler<K, V> {
(sender: Windows.Foundation.Collections.IObservableMap<K, V>, event: Windows.Foundation.Collections.IMapChangedEventArgs<K>): void;
}
export interface IObservableMap<K, V> extends Windows.Foundation.Collections.IMap<K, V>, Windows.Foundation.Collections.IIterable<Windows.Foundation.Collections.IKeyValuePair<K, V>> {
onmapchanged: any/* TODO */;
}
}
}
}
export declare module Windows {
export module UI {
export class Color {
a: number;
r: number;
g: number;
b: number;
}
export module ViewManagement {
export enum UIColorType {
background,
foreground,
accentDark3,
accentDark2,
accentDark1,
accent,
accentLight1,
accentLight2,
accentLight3,
complement
}
export class InputPaneVisibilityEventArgs {
ensuredFocusedElementInView: boolean;
occludedRect: Windows.Foundation.Rect;
}
export class InputPane {
occludedRect: Windows.Foundation.Rect;
onshowing: any/* TODO */;
onhiding: any/* TODO */;
addEventListener(type: string, listener: Function, capture?: boolean): void;
removeEventListener(type: string, listener: Function, capture?: boolean): void;
static getForCurrentView(): Windows.UI.ViewManagement.InputPane;
}
export class UISettings {
oncolorvalueschanged: Function;
addEventListener(type: string, listener: Function): void;
removeEventListener(type: string, listener: Function): void;
getColorValue(type: UIColorType): Color;
}
}
}
}
export declare module Windows {
export module UI {
export module Core {
export module AnimationMetrics {
export enum PropertyAnimationType {
scale,
translation,
opacity,
}
export interface IPropertyAnimation {
control1: Windows.Foundation.Point;
control2: Windows.Foundation.Point;
delay: number;
duration: number;
type: Windows.UI.Core.AnimationMetrics.PropertyAnimationType;
}
export interface IScaleAnimation extends Windows.UI.Core.AnimationMetrics.IPropertyAnimation {
finalScaleX: number;
finalScaleY: number;
initialScaleX: number;
initialScaleY: number;
normalizedOrigin: Windows.Foundation.Point;
}
export interface IOpacityAnimation extends Windows.UI.Core.AnimationMetrics.IPropertyAnimation {
finalOpacity: number;
initialOpacity: number;
}
export enum AnimationEffect {
expand,
collapse,
reposition,
fadeIn,
fadeOut,
addToList,
deleteFromList,
addToGrid,
deleteFromGrid,
addToSearchGrid,
deleteFromSearchGrid,
addToSearchList,
deleteFromSearchList,
showEdgeUI,
showPanel,
hideEdgeUI,
hidePanel,
showPopup,
hidePopup,
pointerDown,
pointerUp,
dragSourceStart,
dragSourceEnd,
transitionContent,
reveal,
hide,
dragBetweenEnter,
dragBetweenLeave,
swipeSelect,
swipeDeselect,
swipeReveal,
enterPage,
transitionPage,
crossFade,
peek,
updateBadge,
}
export enum AnimationEffectTarget {
primary,
added,
affected,
background,
content,
deleted,
deselected,
dragSource,
hidden,
incoming,
outgoing,
outline,
remaining,
revealed,
rowIn,
rowOut,
selected,
selection,
shown,
tapped,
}
export interface IAnimationDescription {
animations: Windows.Foundation.Collections.IVectorView<Windows.UI.Core.AnimationMetrics.IPropertyAnimation>;
delayLimit: number;
staggerDelay: number;
staggerDelayFactor: number;
zOrder: number;
}
export interface IAnimationDescriptionFactory {
createInstance(effect: Windows.UI.Core.AnimationMetrics.AnimationEffect, target: Windows.UI.Core.AnimationMetrics.AnimationEffectTarget): Windows.UI.Core.AnimationMetrics.AnimationDescription;
}
export class AnimationDescription implements Windows.UI.Core.AnimationMetrics.IAnimationDescription {
constructor(effect: Windows.UI.Core.AnimationMetrics.AnimationEffect, target: Windows.UI.Core.AnimationMetrics.AnimationEffectTarget);
animations: Windows.Foundation.Collections.IVectorView<Windows.UI.Core.AnimationMetrics.IPropertyAnimation>;
delayLimit: number;
staggerDelay: number;
staggerDelayFactor: number;
zOrder: number;
}
}
}
}
} | the_stack |
import {WebGLQuery} from '../WebGLQuery';
import {WebGLSampler} from '../WebGLSampler';
import {WebGLSync} from '../WebGLSync';
import {WebGLTransformFeedback} from '../WebGLTransformFeedback';
import {WebGLVertexArrayObject} from '../WebGLVertexArrayObject';
import {WebGLShader} from '../../WebGL/WebGLShader';
import {WebGLFramebuffer} from '../../WebGL/WebGLFramebuffer';
import {WebGLTexture} from '../../WebGL/WebGLTexture';
import {WebGLProgram} from '../../WebGL/WebGLProgram';
import {WebGLUniformLocation} from '../../WebGL/WebGLUniformLocation';
import {WebGLActiveInfo} from '../../WebGL/WebGLActiveInfo';
import {WebGLRenderbuffer} from '../../WebGL/WebGLRenderbuffer';
import {WebGLShaderPrecisionFormat} from '../../WebGL/WebGLShaderPrecisionFormat';
import {WebGLBuffer} from '../../WebGL/WebGLBuffer';
import {ImageAsset} from '../../ImageAsset';
import {ImageSource} from '@nativescript/core';
import {WebGL2RenderingContextBase} from "./common";
import {Canvas} from '../../Canvas';
import { ImageBitmap } from '../../ImageBitmap';
export class WebGL2RenderingContext extends WebGL2RenderingContextBase {
constructor(context) {
super(context);
}
native: org.nativescript.canvas.TNSWebGL2RenderingContext;
/* Transform feedback */
static toPrimitive(value): any {
if (value instanceof java.lang.Integer) {
return value.intValue();
} else if (value instanceof java.lang.Long) {
return value.longValue();
} else if (value instanceof java.lang.Short) {
return value.shortValue();
} else if (value instanceof java.lang.Byte) {
return value.byteValue();
} else if (value instanceof java.lang.Boolean) {
return value.booleanValue();
} else if (value instanceof java.lang.String) {
return value.toString();
} else if (value instanceof java.lang.Float) {
return value.floatValue();
} else if (value instanceof java.lang.Double) {
return value.doubleValue();
}
return value;
}
beginQuery(target: number, query: WebGLQuery): void {
this._glCheckError('beginQuery');
const value = query ? query.native : 0;
this.native.beginQuery(target, value);
}
beginTransformFeedback(primitiveMode: number): void {
this._glCheckError('beginTransformFeedback');
this.native.beginTransformFeedback(primitiveMode);
}
bindBufferBase(target: number, index: number, buffer: WebGLBuffer): void {
this._glCheckError('bindBufferBase');
const value = buffer ? buffer.native : 0;
this.native.bindBufferBase(target, index, value);
}
bindBufferRange(
target: number,
index: number,
buffer: WebGLBuffer,
offset: number,
size: number
): void {
this._glCheckError('bindBufferRange');
const value = buffer ? buffer.native : 0;
this.native.bindBufferRange(target, index, value, offset, size);
}
bindSampler(unit: number, sampler: WebGLSampler): void {
this._glCheckError('bindSampler');
const value = sampler ? sampler.native : 0;
this.native.bindSampler(unit, value);
}
bindTransformFeedback(
target: number,
transformFeedback: WebGLTransformFeedback
): void {
this._glCheckError('bindTransformFeedback');
const value = transformFeedback ? transformFeedback.native : 0;
this.native.bindTransformFeedback(target, value);
}
bindVertexArray(vertexArray: WebGLVertexArrayObject): void {
this._glCheckError('bindVertexArray');
const value = vertexArray ? vertexArray.native : 0;
this.native.bindVertexArray(value);
}
blitFramebuffer(
srcX0: number,
srcY0: number,
srcX1: number,
srcY1: number,
dstX0: number,
dstY0: number,
dstX1: number,
dstY1: number,
mask: number,
filter: number
): void {
this._glCheckError('blitFramebuffer');
this.native.blitFramebuffer(
srcX0,
srcY0,
srcX1,
srcY1,
dstX0,
dstY0,
dstX1,
dstY1,
mask,
filter
);
}
clearBufferfi(
buffer: WebGLBuffer,
drawbuffer: number,
depth: number,
stencil: number
): void {
this._glCheckError('clearBufferfi');
const value = buffer ? buffer.native : 0;
this.native.clearBufferfi(value, drawbuffer, depth, stencil);
}
clearBufferfv(
buffer: WebGLBuffer,
drawbuffer: number,
values: number[] | Float32Array
): void {
this._glCheckError('clearBufferfv');
const value = buffer ? buffer.native : 0;
if (values instanceof Float32Array) {
values = this.toNativeArray(values as any, 'float') as any;
}
this.native.clearBufferfv(value, drawbuffer, values as any);
}
clearBufferiv(
buffer: WebGLBuffer,
drawbuffer: number,
values: number[] | Int32Array
): void {
this._glCheckError('clearBufferiv');
const value = buffer ? buffer.native : 0;
if (values instanceof Int32Array) {
values = this.toNativeArray(values as any, 'int');
}
this.native.clearBufferiv(value, drawbuffer, values as any);
}
clearBufferuiv(
buffer: WebGLBuffer,
drawbuffer: number,
values: number[] | Uint32Array
): void {
this._glCheckError('clearBufferuiv');
const value = buffer ? buffer.native : 0;
if (values instanceof Uint32Array) {
values = this.toNativeArray(values as any, 'int');
}
this.native.clearBufferuiv(value, drawbuffer, values as any);
}
clientWaitSync(sync: WebGLSync, flags: number, timeout: number): number {
this._glCheckError('clientWaitSync');
const value = sync ? sync.native : 0;
return this.native.clientWaitSync(value, flags, timeout);
}
compressedTexSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
width: number,
height: number,
depth: number,
format: number,
imageSize: number,
offset: any
);
compressedTexSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
width: number,
height: number,
depth: number,
format: number,
srcData: any,
srcOffset: number = 0,
srcLengthOverride: number = 0
): void {
this._glCheckError('compressedTexSubImage3D');
if (typeof srcOffset === 'number') {
this.native.compressedTexSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
srcData,
srcOffset
);
} else if (srcData && srcData.buffer) {
if (srcData instanceof Uint8Array) {
this.native.compressedTexSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
this.toNativeArray(srcData as any, 'byte'),
srcOffset,
srcLengthOverride
);
}
}
}
/* Transform feedback */
/* Framebuffers and renderbuffers */
copyBufferSubData(
readTarget: number,
writeTarget: number,
readOffset: number,
writeOffset: number,
size: number
): void {
this._glCheckError('copyBufferSubData');
this.native.copyBufferSubData(
readTarget,
writeTarget,
readOffset,
writeOffset,
size
);
}
copyTexSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
x: number,
y: number,
width: number,
height: number
): void {
this._glCheckError('copyTexSubImage3D');
this.native.copyTexSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
x,
y,
width,
height
);
}
createQuery(): WebGLQuery {
this._glCheckError('createQuery');
return new WebGLQuery(this.native.createQuery());
}
createSampler(): WebGLSampler {
this._glCheckError('createSampler');
return new WebGLSampler(this.native.createSampler());
}
createTransformFeedback(): WebGLTransformFeedback {
this._glCheckError('createTransformFeedback');
return new WebGLTransformFeedback(this.native.createTransformFeedback());
}
createVertexArray(): WebGLVertexArrayObject {
this._glCheckError('createVertexArray');
return new WebGLVertexArrayObject(this.native.createVertexArray());
}
deleteQueryWithQuery(query: WebGLQuery): void {
this._glCheckError('deleteQueryWithQuery');
const value = query ? query.native : 0;
this.native.deleteQuery(value);
}
deleteSamplerWithSampler(sampler: WebGLSampler): void {
this._glCheckError('deleteSamplerWithSampler');
const value = sampler ? sampler.native : 0;
this.native.deleteSampler(value);
}
deleteSyncWithSync(sync: WebGLSync): void {
this._glCheckError('deleteSyncWithSync');
const value = sync ? sync.native : 0;
this.native.deleteSync(value);
}
deleteTransformFeedback(transformFeedback: WebGLTransformFeedback): void {
this._glCheckError('deleteTransformFeedback');
const value = transformFeedback ? transformFeedback.native : 0;
this.native.deleteTransformFeedback(value);
}
deleteVertexArray(vertexArray: WebGLVertexArrayObject): void {
this._glCheckError('deleteVertexArray');
const value = vertexArray ? vertexArray.native : 0;
this.native.deleteVertexArray(value);
}
drawArraysInstanced(
mode: number,
first: number,
count: number,
instanceCount: number
): void {
this._glCheckError('drawArraysInstanced');
this.native.drawArraysInstanced(mode, first, count, instanceCount);
}
drawBuffers(buffers: number[]): void {
this._glCheckError('drawBuffers');
this.native.drawBuffers(buffers);
}
drawElementsInstanced(
mode: number,
count: number,
type: number,
offset: number,
instanceCount: number
): void {
this._glCheckError('drawElementsInstanced');
this.native.drawElementsInstanced(mode, count, type, offset, instanceCount);
}
drawRangeElements(
mode: number,
start: number,
end: number,
count: number,
type: number,
offset: number
): void {
this._glCheckError('drawRangeElements');
this.native.drawRangeElements(mode, start, end, count, type, offset);
}
endQuery(target: number): void {
this._glCheckError('endQuery');
this.native.endQuery(target);
}
endTransformFeedback(): void {
this._glCheckError('endTransformFeedback');
this.native.endTransformFeedback();
}
fenceSync(condition: number, flags: number): void {
this._glCheckError('fenceSync');
this.native.fenceSync(condition, flags);
}
framebufferTextureLayer(
target: number,
attachment: number,
texture: WebGLTexture,
level: number,
layer: number
): void {
this._glCheckError('framebufferTextureLayer');
const value = texture ? texture.native : 0;
this.native.framebufferTextureLayer(
target,
attachment,
value,
level,
layer
);
}
/* Framebuffers and renderbuffers */
/* Uniforms */
getActiveUniformBlockName(
program: WebGLProgram,
uniformBlockIndex: number
): string {
this._glCheckError('getActiveUniformBlockName');
const value = program ? program.native : 0;
return this.native.getActiveUniformBlockName(
value,
uniformBlockIndex
);
}
getActiveUniformBlockParameter(
program: WebGLProgram,
uniformBlockIndex: number,
pname: number
): any {
this._glCheckError('getActiveUniformBlockParameter');
const value = program ? program.native : 0;
const param = this.native.getActiveUniformBlockParameter(
value,
uniformBlockIndex,
pname
);
if (pname === this.UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES) {
return new Uint32Array(this.getJSArray(param));
}
return WebGL2RenderingContext.toPrimitive(param);
}
getActiveUniforms(
program: WebGLProgram,
uniformIndices: number[],
pname: number
): any {
this._glCheckError('getActiveUniforms');
const value = program ? program.native : 0;
return this.getJSArray(
this.native.getActiveUniforms(value, uniformIndices, pname)
);
}
getBufferSubData(
target: number,
srcByteOffset: number,
dstData: ArrayBuffer,
dstOffset: number = 0,
length: number = 0
): void {
this._glCheckError('getBufferSubData');
this.native.getBufferSubData(
target,
srcByteOffset,
new Uint8Array(dstData.slice(0)) as any,
dstOffset,
length
);
}
getFragDataLocation(program: WebGLProgram, name: string): number {
this._glCheckError('getFragDataLocation');
const value = program ? program.native : 0;
const result = this.native.getFragDataLocation(value, name);
return result !== -1 ? result : null;
}
getIndexedParameter(target: number, index: number): any {
this._glCheckError('getIndexedParameter');
const param = this.native.getIndexedParameter(target, index);
if (
target === this.TRANSFORM_FEEDBACK_BUFFER_BINDING ||
target === this.UNIFORM_BUFFER_BINDING
) {
return new WebGLBuffer(param);
}
return WebGL2RenderingContext.toPrimitive(param);
}
getInternalformatParameter(
target: number,
internalformat: number,
pname: number
): any {
this._glCheckError('getInternalformatParameter');
const param = this.native.getInternalformatParameter(
target,
internalformat,
pname
);
if (pname === this.SAMPLES) {
return new Int32Array(this.getJSArray(param));
}
return WebGL2RenderingContext.toPrimitive(param);
}
getQueryParameter(query: WebGLQuery, pname: number): any {
this._glCheckError('getQueryParameter');
const value = query ? query.native : 0;
const result = this.native.getQueryParameter(value, pname);
if (result === 0) {
return null;
}
return WebGL2RenderingContext.toPrimitive(result);
}
//@ts-ignore
getParameter(pname: number): number[] | number | WebGLBuffer | WebGLProgram | WebGLFramebuffer | WebGLRenderbuffer | WebGLTexture | Uint32Array | Int32Array | Float32Array | string | null {
this._glCheckError('getParameter');
this._checkArgs('activeTexture', arguments);
const value = this.native.getParameter(pname);
switch (pname) {
case this.COPY_READ_BUFFER_BINDING:
case this.COPY_WRITE_BUFFER_BINDING:
if (value) {
new WebGLBuffer(WebGL2RenderingContext.toPrimitive(value));
}
return null;
case this.DRAW_FRAMEBUFFER_BINDING:
if (value) {
return new WebGLFramebuffer(WebGL2RenderingContext.toPrimitive(value));
}
return null;
default:
return super.getParameter(pname);
}
}
getQuery(target: number, pname: number): any {
this._glCheckError('getQuery');
const query = this.native.getQuery(target, pname);
if (query) {
return new WebGLQuery(query);
}
return null;
}
getSamplerParameter(sampler: WebGLSampler, pname: number): any {
this._glCheckError('getSamplerParameter');
const value = sampler ? sampler.native : 0;
return WebGL2RenderingContext.toPrimitive(this.native.getSamplerParameter(value, pname));
}
getSyncParameter(sync: WebGLSync, pname: number): any {
this._glCheckError('getSyncParameter');
const value = sync ? sync.native : 0;
return WebGL2RenderingContext.toPrimitive(this.native.getSyncParameter(value, pname));
}
getTransformFeedbackVarying(program: WebGLProgram, index: number): any {
this._glCheckError('getTransformFeedbackVarying');
const value = program ? program.native : 0;
const info = this.native.getTransformFeedbackVarying(value, index);
if (info) {
return new WebGLActiveInfo(info.name, info.size, info.size);
}
return null;
}
getUniformBlockIndex(
program: WebGLProgram,
uniformBlockName: string
): number {
this._glCheckError('getUniformBlockIndex');
const value = program ? program.native : 0;
return this.native.getUniformBlockIndex(value, uniformBlockName);
}
getUniformIndices(program: WebGLProgram, uniformNames: string[]): number[] {
this._glCheckError('getUniformIndices');
const value = program ? program.native : 0;
return this.getJSArray(
this.native.getUniformIndices(value, uniformNames)
);
}
invalidateFramebuffer(target: number, attachments: number[]): void {
this._glCheckError('invalidateFramebuffer');
this.native.invalidateFramebuffer(target, attachments);
}
invalidateSubFramebuffer(
target: number,
attachments: number[],
x: number,
y: number,
width: number,
height: number
): void {
this._glCheckError('invalidateSubFramebuffer');
this.native.invalidateSubFramebuffer(
target,
attachments,
x,
y,
width,
height
);
}
isQuery(query: WebGLQuery): boolean {
this._glCheckError('isQuery');
const value = query ? query.native : 0;
return this.native.isQuery(value);
}
isSampler(sampler: WebGLSampler): boolean {
this._glCheckError('isSampler');
const value = sampler ? sampler.native : 0;
return this.native.isSampler(value);
}
isSync(sync: WebGLSync): boolean {
this._glCheckError('isSync');
const value = sync ? sync.native : 0;
return this.native.isSync(value);
}
isTransformFeedback(transformFeedback: WebGLTransformFeedback): boolean {
this._glCheckError('isTransformFeedback');
const value = transformFeedback ? transformFeedback.native : 0;
return this.native.isTransformFeedback(value);
}
isVertexArray(vertexArray: WebGLVertexArrayObject): boolean {
this._glCheckError('isVertexArray');
const value = vertexArray ? vertexArray.native : 0;
return this.native.isVertexArray(value);
}
pauseTransformFeedback(): void {
this._glCheckError('pauseTransformFeedback');
this.native.pauseTransformFeedback();
}
readBuffer(src: number): void {
this._glCheckError('readBuffer');
this.native.readBuffer(src);
}
renderbufferStorageMultisample(
target: number,
samples: number,
internalFormat: number,
width: number,
height: number
): void {
this._glCheckError('renderbufferStorageMultisample');
this.native.renderbufferStorageMultisample(
target,
samples,
internalFormat,
width,
height
);
}
resumeTransformFeedback(): void {
this._glCheckError('resumeTransformFeedback');
this.native.resumeTransformFeedback();
}
samplerParameterf(sampler: WebGLSampler, pname: number, param: number): void {
this._glCheckError('samplerParameterf');
const value = sampler ? sampler.native : 0;
this.native.samplerParameterf(value, pname, param);
}
/* Uniforms */
/* Sync objects */
samplerParameteri(sampler: WebGLSampler, pname: number, param: number): void {
this._glCheckError('samplerParameteri');
const value = sampler ? sampler.native : 0;
this.native.samplerParameteri(value, pname, param);
}
texImage3D(
target: number,
level: number,
internalformat: number,
width: number,
height: number,
depth: number,
border: number,
format: number,
type: number,
offset: any
);
texImage3D(
target: number,
level: number,
internalformat: number,
width: number,
height: number,
depth: number,
border: number,
format: number,
type: number,
source: any
): void {
this._glCheckError('texImage3D');
if (typeof source === 'number') {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source
);
} else if (source && source.buffer) {
if (source && source.buffer) {
if (source instanceof Uint8Array || source instanceof Uint8ClampedArray) {
this.native.texImage3DByte(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(source)
);
} else if (source instanceof Uint16Array || source instanceof Int16Array) {
this.native.texImage3DShort(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(source)
);
} else if (source instanceof Uint32Array || source instanceof Int32Array) {
this.native.texImage3DInt(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(source)
);
} else if (source instanceof Float32Array) {
this.native.texImage3DFloat(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(source)
);
} else if (source instanceof Float64Array) {
this.native.texImage3DDouble(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(source)
);
}
} else if (source instanceof ArrayBuffer) {
// @ts-ignore
if(source.nativeObject){
// @ts-ignore
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
// @ts-ignore
source.nativeObject
);
}else {
this.native.texImage3DByte(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
Array.from(new Uint8Array(source))
);
}
}
} else if (source instanceof android.graphics.Bitmap) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source
);
} else if (source instanceof ImageSource) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source.android
);
} else if (source instanceof ImageAsset) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source.native
);
} else if (source instanceof ImageBitmap || source?.native instanceof org.nativescript.canvas.TNSImageBitmap) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source.native
);
} else if (
source &&
typeof source.tagName === 'string' &&
(source.tagName === 'IMG' || source.tagName === 'IMAGE')
) {
if (source._imageSource instanceof ImageSource) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source._imageSource.android
);
} else if (source._image instanceof android.graphics.Bitmap) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source._image
);
} else if (source._asset instanceof ImageAsset) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source._asset.native
);
} else if (typeof source.src === 'string') {
const result = ImageSource.fromFileSync(source.src);
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
result ? result.android : null
);
}
} else if (source &&
typeof source.tagName === 'string' &&
source.tagName === 'CANVAS' && source._canvas instanceof Canvas) {
this.native.texImage3D(
target,
level,
internalformat,
width,
height,
depth,
border,
format,
type,
source._canvas.android
);
}
}
texStorage2D(
target: number,
levels: number,
internalformat: number,
width: number,
height: number
): void {
this._glCheckError('texStorage2D');
this.native.texStorage2D(target, levels, internalformat, width, height);
}
texStorage3D(
target: number,
levels: number,
internalformat: number,
width: number,
height: number,
depth: number
): void {
this._glCheckError('texStorage3D');
this.native.texStorage3D(
target,
levels,
internalformat,
width,
height,
depth
);
}
texSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
width: number,
height: number,
depth: number,
format: number,
type: number,
offset: any
);
texSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
width: number,
height: number,
depth: number,
format: number,
type: number,
srcData: any
);
texSubImage3D(
target: number,
level: number,
xoffset: number,
yoffset: number,
zoffset: number,
width: number,
height: number,
depth: number,
format: number,
type: number,
srcData: any,
srcOffset: number = 0
): void {
this._glCheckError('texSubImage3D');
if (typeof srcData === 'number') {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData
);
} else if (srcData && srcData.buffer) {
if (srcData instanceof Uint8Array) {
if (srcOffset) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
this.toNativeArray(srcData as any, 'byte'),
srcOffset
);
} else {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
this.toNativeArray(srcData as any, 'byte')
);
}
}
if (srcData && srcData.buffer) {
if (srcData instanceof Uint8Array || srcData instanceof Uint8ClampedArray) {
this.native.texSubImage3DByte(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(srcData),
srcOffset
);
} else if (srcData instanceof Uint16Array || srcData instanceof Int16Array) {
this.native.texSubImage3DShort(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(srcData),
srcOffset
);
} else if (srcData instanceof Uint32Array || srcData instanceof Int32Array) {
this.native.texSubImage3DInt(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(srcData),
srcOffset
);
} else if (srcData instanceof Float32Array) {
this.native.texSubImage3DFloat(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(srcData),
srcOffset
);
} else if (srcData instanceof Float64Array) {
this.native.texSubImage3DDouble(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(srcData),
srcOffset
);
}
} else if (srcData instanceof ArrayBuffer) {
// @ts-ignore
if(source.nativeObject){
this.native.texSubImage3DByte(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
// @ts-ignore
source.nativeObject,
srcOffset
);
}else {
this.native.texSubImage3DDouble(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
Array.from(new Uint8Array(srcData)),
srcOffset
);
}
}
} else if (srcData instanceof android.graphics.Bitmap) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData
);
} else if (srcData instanceof ImageSource) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData.android
);
} else if (srcData instanceof ImageAsset) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData.native
);
} else if (srcData instanceof ImageBitmap || srcData?.native instanceof org.nativescript.canvas.TNSImageBitmap) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData.native
);
} else if (
srcData &&
typeof srcData.tagName === 'string' &&
(srcData.tagName === 'IMG' || srcData.tagName === 'IMAGE')
) {
if (srcData._imageSource instanceof ImageSource) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData._imageSource.android
);
} else if (srcData._image instanceof android.graphics.Bitmap) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData._image
);
} else if (srcData._asset instanceof ImageAsset) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData._asset.native
);
} else if (typeof srcData.src === 'string') {
const result = ImageSource.fromFileSync(srcData.src);
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
result ? result.android : null
);
}
} else if (srcData &&
typeof srcData.tagName === 'string' &&
srcData.tagName === 'CANVAS' && srcData._canvas instanceof TNSCanvas) {
this.native.texSubImage3D(
target,
level,
xoffset,
yoffset,
zoffset,
width,
height,
depth,
format,
type,
srcData._canvas.android
);
}
}
transformFeedbackVaryings(
program: WebGLProgram,
varyings: string[],
bufferMode: number
): void {
this._glCheckError('transformFeedbackVaryings');
const value = program ? program.native : 0;
this.native.transformFeedbackVaryings(value, varyings, bufferMode);
}
uniform1ui(location: WebGLUniformLocation, v0: number): void {
this._glCheckError('uniform1ui');
const value = location ? location.native : 0;
this.native.uniform1ui(value, v0);
}
uniform1uiv(location: WebGLUniformLocation, data: Uint32Array): void {
this._glCheckError('uniform1uiv');
const value = location ? location.native : 0;
this.native.uniform1uiv(value, Array.from(data as any));
}
uniform2ui(location: WebGLUniformLocation, v0: number, v1: number): void {
this._glCheckError('uniform2ui');
const value = location ? location.native : 0;
this.native.uniform2ui(value, v0, v1);
}
uniform2uiv(location: WebGLUniformLocation, data: Uint32Array): void {
this._glCheckError('uniform2uiv');
const value = location ? location.native : 0;
this.native.uniform2uiv(value, Array.from(data as any));
}
/* Sync objects */
/* Miscellaneous constants */
uniform3ui(location: WebGLUniformLocation, v0: number, v1: number, v2: number): void {
this._glCheckError('uniform3ui');
const value = location ? location.native : 0;
this.native.uniform3ui(value, v0, v1, v2);
}
uniform3uiv(location: WebGLUniformLocation, data: Uint32Array): void {
this._glCheckError('uniform3uiv');
const value = location ? location.native : 0;
this.native.uniform3uiv(value, Array.from(data as any));
}
uniform4ui(
location: WebGLUniformLocation,
v0: number,
v1: number,
v2: number,
v3: number
): void {
this._glCheckError('uniform4ui');
const value = location ? location.native : 0;
this.native.uniform4ui(value, v0, v1, v2, v3);
}
uniform4uiv(location: WebGLUniformLocation, data: Uint32Array): void {
this._glCheckError('uniform4uiv');
const value = location ? location.native : 0;
this.native.uniform4uiv(value, Array.from(data as any));
}
uniformBlockBinding(
program: WebGLProgram,
uniformBlockIndex: number,
uniformBlockBinding: number
): void {
this._glCheckError('uniformBlockBinding');
const value = program ? program.native : 0;
this.native.uniformBlockBinding(
value,
uniformBlockIndex,
uniformBlockBinding
);
}
uniformMatrix2x3fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix2x3fv');
const value = location ? location.native : 0;
this.native.uniformMatrix2x3fv(value, transpose, data as any);
}
uniformMatrix2x4fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix2x4fv');
const value = location ? location.native : 0;
this.native.uniformMatrix2x4fv(value, transpose, data as any);
}
uniformMatrix3x2fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix3x2fv');
const value = location ? location.native : 0;
this.native.uniformMatrix3x2fv(value, transpose, data as any);
}
uniformMatrix3x4fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix3x4fv');
const value = location ? location.native : 0;
this.native.uniformMatrix3x4fv(value, transpose, data as any);
}
uniformMatrix4x2fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix4x2fv');
const value = location ? location.native : 0;
this.native.uniformMatrix4x2fv(value, transpose, data as any);
}
uniformMatrix4x3fv(
location: WebGLUniformLocation,
transpose: boolean,
data: Float32Array
): void {
if (data instanceof Float32Array) {
data = Array.from(data as any) as any; //this.toNativeArray(data as any, 'float');
}
this._glCheckError('uniformMatrix4x3fv');
const value = location ? location.native : 0;
this.native.uniformMatrix4x3fv(value, transpose, data as any);
}
vertexAttribDivisor(index: number, divisor: number): void {
this._glCheckError('vertexAttribDivisor');
this.native.vertexAttribDivisor(index, divisor);
}
vertexAttribI4i(
index: number,
v0: number,
v1: number,
v2: number,
v3: number
): void {
this._glCheckError('vertexAttribI4i');
this.native.vertexAttribI4i(index, v0, v1, v2, v3);
}
vertexAttribI4iv(index: number, value: number[] | Int32Array): void {
if (value instanceof Int32Array) {
value = Array.from(value) as any; //this.toNativeArray(value as any, 'int');
}
this._glCheckError('vertexAttribI4iv');
this.native.vertexAttribI4uiv(index, value as any);
}
vertexAttribI4ui(
index: number,
v0: number,
v1: number,
v2: number,
v3: number
): void {
this._glCheckError('vertexAttribI4ui');
this.native.vertexAttribI4ui(index, v0, v1, v2, v3);
}
vertexAttribI4uiv(index: number, value: number[] | Uint32Array): void {
if (value instanceof Uint32Array) {
value = Array.from(value) as any; //this.toNativeArray(value as any, 'int');
}
this._glCheckError('vertexAttribI4uiv');
this.native.vertexAttribI4uiv(index, value as any);
}
/* Miscellaneous constants */
} | the_stack |
import * as fs from "fs";
import * as path from "path";
import { expect } from "chai";
import * as Sinon from "sinon";
import * as Nock from "nock";
import * as pfs from "../../../src/util/misc/promisfied-fs";
import CodePushReleaseElectronCommand from "../../../src/commands/codepush/release-electron";
import { CommandArgs } from "../../../src/util/commandline/command";
import * as mkdirp from "mkdirp";
import * as ElectronTools from "../../../src/commands/codepush/lib/electron-utils";
import * as fileUtils from "../../../src/commands/codepush/lib/file-utils";
import { CommandFailedResult, CommandResult } from "../../../src/util/commandline";
import * as updateContentsTasks from "../../../src/commands/codepush/lib/update-contents-tasks";
describe("codepush release-electron command", function () {
const app = "bogus/app";
const deployment = "bogus-deployment";
let sandbox: Sinon.SinonSandbox;
beforeEach(() => {
sandbox = Sinon.createSandbox();
sandbox.stub(updateContentsTasks, "sign");
});
afterEach(() => {
sandbox.restore();
});
const goldenPathArgs: CommandArgs = {
// prettier-ignore
args: [
"--extra-bundler-option", "bogusElectronBundle",
"--target-binary-version", "1.0.0",
"--output-dir", "fake/out/dir",
"--sourcemap-output-dir", "fake/sourcemap/output",
"--sourcemap-output", "sourceMapOutput.txt",
"--entry-file", "entry.js",
"--config", "webpack.config.js",
"--development",
"--bundle-name", "bundle",
"--rollout", "100",
"--disable-duplicate-release-error",
"--private-key-path", "fake/private-key-path",
"--mandatory",
"--disabled",
"--description", "app description",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
command: ["codepush", "release-electron"],
commandPath: "fake/path",
};
it("succeed if all parameters are passed", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "16.13.1"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "Windows",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.true;
});
it("npm package should have name defined check", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
// Act
const result = command.execute();
// Assert
return expect(result).to.eventually.be.rejectedWith('The "package.json" file in the CWD does not have the "name" field set.');
});
context("electron dependency", function () {
it("throws error if no electron in dependencies and devDependencies", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"some-package": "6.3.0"
}
}
`);
// Act
const result = (await command.execute()) as CommandFailedResult;
// Assert
expect(result.succeeded).to.be.false;
expect(result.errorMessage).to.equal("The project in the CWD is not a Electron project.");
});
it("finishes to end if electron specified in dependencies ", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "Windows",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.true;
});
it("finishes to end if electron specified in devDependencies ", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"some-package": "6.3.0"
},
"devDependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "MacOS",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.true;
});
});
it("shows user friendly error when incorrect deployment specified", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(404, {});
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
// Act
const result = (await command.execute()) as CommandFailedResult;
// Assert
expect(result.succeeded).to.be.false;
expect(result.errorMessage).to.be.equal(`Deployment "${deployment}" does not exist.`);
});
context("when no output dir parameter specified, then temporarily directory is created", function () {
it("creates CodePush directory, so that it was compatible with SDK", async function () {
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--bundle-name", "bundle",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "Windows",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
const mkTempDirStub = sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
sandbox.assert.calledWithExactly(mkTempDirStub, "code-push");
});
it("temporary directory is get removed once command finishes", async function () {
// Arrange
const fakePath = "fake/path/code-push";
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--bundle-name", "bundle",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "Windows",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves(fakePath);
const rmDirSpy = sandbox.spy(pfs, "rmDir");
// Act
await command.execute();
// Assert
sandbox.assert.calledOnceWithExactly(rmDirSpy, path.join(fakePath, "CodePush"));
});
});
["Linux", "MacOS", "Windows"].forEach((os: string) => {
it(`only Linux, MacOS and Windows OSes are allowed (check the API response) - check ${os}`, async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.true;
});
});
it("throws an error if non electron platform specified", async function () {
// Arrange
const command = new CodePushReleaseElectronCommand(goldenPathArgs);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "MacOS",
platform: "objective-c",
});
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.false;
});
it("bundle name defaults", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
const rnBundleStub = sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
expect(rnBundleStub.getCalls()[0].args[0]).to.be.equal(`index.electron.bundle`);
});
context("entry file", function () {
context("if not specified", function () {
it("then defaults to webpack.config.js", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
const rnBundleStub = sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
expect(rnBundleStub.getCalls()[0].args[3]).to.be.equal(`index.windows.js`);
});
it("and fallback to index.js", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
const firstAttemptEntryFileName = `index.${os.toLowerCase()}.js`;
sandbox.replace(fileUtils, "fileDoesNotExistOrIsDirectory", (path) => path === firstAttemptEntryFileName);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
const rnBundleStub = sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
expect(rnBundleStub.getCalls()[0].args[3]).to.be.equal("index.js");
});
it("fails command if no file found", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
const firstAttemptEntryFileName = `index.${os.toLowerCase()}.js`;
const secondAttemptEntryFileName = "index.js";
sandbox.replace(fileUtils, "fileDoesNotExistOrIsDirectory", (path) => {
return path === firstAttemptEntryFileName || path === secondAttemptEntryFileName;
});
// Act
const result = await command.execute();
// Assert
expect(result.succeeded).to.be.false;
});
});
it("fails the command if entry file specified is not found", async function () {
// Arrange
const entryFile = "bogusEntryFile";
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
"--entry-file", entryFile
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os: "Windows",
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
const fileNotExistStub = sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(true);
// Act
const result = await command.execute();
// Assert
expect(fileNotExistStub.calledWithExactly(entryFile)).to.be.true;
expect(result.succeeded).to.be.false;
});
});
it("composes sourcemapOutput when --sourcemap-output parameter is not provided", async function () {
const os = "Windows";
const bundleName = "bogus.bundle";
const sourcemapOutputDir = "/fake/dir";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--sourcemap-output-dir", sourcemapOutputDir,
"--bundle-name", bundleName,
"--target-binary-version", "1.0.0",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
const rnBundleStub = sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
expect(rnBundleStub.getCalls()[0].args[5]).to.be.equal(path.join(sourcemapOutputDir, `${bundleName}.map`));
});
context("targetBinaryVersion", function () {
it("fails if targetBinaryVersion is not in valid range", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--target-binary-version", "invalid-range",
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
// Act
const result = (await command.execute()) as CommandFailedResult;
// Assert
expect(result.errorMessage).to.be.equal("Invalid binary version(s) for a release.");
expect(result.succeeded).to.be.false;
});
it("sets targetBinaryVersion from project settings if not specified", async function () {
const os = "Windows";
// Arrange
const args = {
...goldenPathArgs,
// prettier-ignore
args: [
"--deployment-name", deployment,
"--app", app,
"--token", "c1o3d3e7",
],
};
const command = new CodePushReleaseElectronCommand(args);
sandbox.stub(fs, "readFileSync").returns(`
{
"name": "electron-bogus-app",
"version": "0.0.1",
"dependencies": {
"electron": "10.1.5"
}
}
`);
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}/deployments/${deployment}`).reply(200, {});
Nock("https://api.appcenter.ms/").get(`/v0.1/apps/${app}`).reply(200, {
os,
platform: "electron",
});
sandbox.stub(mkdirp, "sync");
sandbox.stub(fileUtils, "fileDoesNotExistOrIsDirectory").returns(false);
sandbox.stub(fileUtils, "createEmptyTmpReleaseFolder");
const fallback = sandbox.stub(ElectronTools, "getElectronProjectAppVersion");
sandbox.stub(ElectronTools, "runWebPackBundleCommand");
sandbox.stub(command, "release" as any).resolves(<CommandResult>{ succeeded: true });
sandbox.stub(pfs, "mkTempDir").resolves("fake/path/code-push");
// Act
await command.execute();
// Assert
Sinon.assert.called(fallback);
});
});
}); | the_stack |
import { shell } from "electron";
import { readdir, pathExists, mkdir, writeFile, stat, readFile, move } from "fs-extra";
import { join, extname, normalize, basename } from "path";
import Glob from "glob";
import { Undefinable } from "../../../shared/types";
import * as React from "react";
import { ButtonGroup, Button, Classes, Breadcrumbs, Boundary, IBreadcrumbProps, Divider, ContextMenu, Menu, MenuItem, MenuDivider, Tag, Intent } from "@blueprintjs/core";
import { Scene, Node } from "babylonjs";
import { WorkSpace } from "../project/workspace";
import { ProjectExporter } from "../project/project-exporter";
import { Icon } from "../gui/icon";
import { Alert } from "../gui/alert";
import { Dialog } from "../gui/dialog";
import { Tools } from "../tools/tools";
import { Assets } from "../components/assets";
import { AbstractAssets, IAssetComponentItem } from "./abstract-assets";
export class ScriptAssets extends AbstractAssets {
/**
* Defines the size of assets to be drawn in the panel. Default is 100x100 pixels.
* @override
*/
protected size: number = 50;
/**
* Defines the type of the data transfer data when drag'n'dropping asset.
* @override
*/
public readonly dragAndDropType: string = "application/script-asset";
private _refreshing: boolean = false;
private static _Path: string = "";
/**
* Registers the component.
*/
public static Register(): void {
Assets.addAssetComponent({
title: "Scripts",
identifier: "scripts",
ctor: ScriptAssets,
});
}
/**
* Returns the list of all available scripts.
*/
public static GetAllScripts(): Promise<string[]> {
return new Promise<string[]>((resolve, reject) => {
if (!WorkSpace.DirPath) {
return resolve([]);
}
Glob(join(WorkSpace.DirPath, "src", "scenes", "**", "*.ts"), { }, (err, files) => {
if (err) { return reject(err); }
const excluded = [
"src/scenes/decorators.ts",
"src/scenes/scripts-map.ts",
"src/scenes/tools.ts",
];
const result = files.filter((f) => f.indexOf("index.ts") === -1)
.map((f) => f.replace(/\\/g, "/").replace(WorkSpace.DirPath!.replace(/\\/g, "/"), ""))
.filter((f) => excluded.indexOf(f) === -1);
resolve(result);
});
});
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
const node = super.render();
return (
<>
<div className={Classes.FILL} key="scripts-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px" }}>
<ButtonGroup>
<Button key="refresh-folder" icon="refresh" small={true} onClick={() => this.refresh()} />
<Divider />
<Button key="add-script" icon={<Icon src="plus.svg" />} small={true} text="Add Script..." onClick={() => this._addScript()} />
</ButtonGroup>
</div>
<Breadcrumbs
overflowListProps={{
style: { marginLeft: "4px" }
}}
collapseFrom={Boundary.START}
items={this._getPathBrowser()}
></Breadcrumbs>
{node}
</>
);
}
/**
* Refreshes the component.
* @override
*/
public async refresh(): Promise<void> {
this.items = [];
if (!WorkSpace.HasWorkspace()) { return super.refresh(); }
if (this._refreshing) { return; }
this._refreshing = true;
try {
const path = this._getCurrentPath();
if (!(await pathExists(path))) {
await mkdir(path);
}
const files = await readdir(path);
for (const f of files) {
if (ScriptAssets._Path === "" && f === "index.ts") { continue; }
const key = join(ScriptAssets._Path, f);
const infos = await stat(join(path, f));
if (infos.isDirectory()) {
this.items.push({ id: f, key, base64: "../css/svg/folder-open.svg" });
continue;
}
const extension = extname(f).toLowerCase();
if (extension !== ".ts") { continue; }
this.items.push({ id: f, key, base64: "../css/images/ts.png", extraData: {
scriptPath: join("src", "scenes", key),
}, style: {
borderColor: "#2FA1D6",
borderStyle: "solid",
borderWidth: this._isScriptAttached(key) ? "2px" : "0px",
} });
}
} catch (e) {
console.error(e);
} finally {
this._refreshing = false;
return super.refresh();
}
}
/**
* Called on the user double clicks an item.
* @param item the item being double clicked.
* @param img the double-clicked image element.
*/
public async onDoubleClick(item: IAssetComponentItem, img: HTMLImageElement): Promise<void> {
super.onDoubleClick(item, img);
return this.openItem(item);
}
/**
* Called on an asset item has been drag'n'dropped on graph component.
* @param data defines the data of the asset component item being drag'n'dropped.
* @param nodes defines the array of nodes having the given item being drag'n'dropped.
*/
public onGraphDropAsset(data: IAssetComponentItem, nodes: (Scene | Node)[]): boolean {
super.onGraphDropAsset(data, nodes);
if (!data.extraData?.scriptPath) { return false; }
nodes.forEach((n) => {
n.metadata ??= { };
n.metadata.script ??= { };
n.metadata.script.name = data.extraData!.scriptPath as string;
});
return true;
}
/**
* Opens the given item.
* @param item defines the item to open.
*/
public async openItem(item: IAssetComponentItem): Promise<void> {
const path = normalize(join(WorkSpace.DirPath!, "src", "scenes", item.key));
const infos = await stat(path);
if (infos.isDirectory()) {
ScriptAssets._Path = item.key;
return this.refresh();
}
const extension = extname(path).toLowerCase();
if (extension === ".ts") {
const task = this.editor.addTaskFeedback(0, `Opening "${basename(path)}"`);
const success = shell.openItem(path);
this.editor.updateTaskFeedback(task, 100, success ? "Done" : "Failed");
return this.editor.closeTaskFeedback(task, 500);
}
}
/**
* Called on the user right-clicks on the component's main div.
* @param event the original mouse event.
*/
public onComponentContextMenu(event: React.MouseEvent<HTMLDivElement, MouseEvent>): void {
ContextMenu.show(
<Menu className={Classes.DARK}>
<MenuItem text="New Script..." icon={<Icon src="plus.svg" />} onClick={() => this._addScript()} />
<MenuDivider />
<MenuItem text="Add Folder..." icon={<Icon src="plus.svg" />} onClick={() => this._addNewFolder()} />
</Menu>,
{ left: event.clientX, top: event.clientY }
);
}
/**
* Called on the currently dragged item is over the given item.
* @param item the item having the currently dragged item over.
*/
protected dragEnter(item: IAssetComponentItem): void {
super.dragEnter(item);
const extension = extname(item.key);
if (extension) { return; }
if (item.ref) {
item.ref.style.backgroundColor = "#222222";
}
}
/**
* Called on the currently dragged item is out the given item.
* @param item the item having the currently dragged item out.
*/
protected dragLeave(item: IAssetComponentItem): void {
super.dragLeave(item);
const extension = extname(item.key);
if (extension) { return; }
if (item.ref) {
item.ref.style.backgroundColor = "";
}
}
/**
* Called on the currently dragged item has been dropped.
* @param item the item having the currently dragged item dropped over.
* @param droppedItem the item that has been dropped.
*/
protected async dropOver(item: IAssetComponentItem, droppedItem: IAssetComponentItem): Promise<void> {
super.dropOver(item, droppedItem);
if (item === droppedItem) { return; }
if (item.ref) { item.ref.style.backgroundColor = ""; }
const root = join(WorkSpace.DirPath!, "src", "scenes");
const target = join(root, item.key);
const isDirectory = (await stat(target)).isDirectory();
if (!isDirectory) { return; }
const src = join(root, droppedItem.key);
const dest = join(target, basename(droppedItem.key));
await move(src, dest);
this._updateAttachedElements(src, dest);
this.refresh();
}
/**
* Returns the content of the item's tooltip on the pointer is over the given item.
* @param item defines the reference to the item having the pointer over.
*/
protected getItemTooltipContent(item: IAssetComponentItem): Undefinable<JSX.Element> {
const path = join("src/scenes", item.key);
const attached: Node[] = [];
const all = (this.editor.scene!.meshes as Node[])
.concat(this.editor.scene!.lights)
.concat(this.editor.scene!.cameras)
.concat(this.editor.scene!.transformNodes);
all.forEach((n) => {
if (!n.metadata?.script) { return; }
if (n.metadata.script.name !== path) { return; }
attached.push(n);
});
if (!attached.length) { return undefined; }
const fullPath = join(WorkSpace.DirPath!, path);
return (
<>
<Tag fill={true} interactive={true} intent={Intent.PRIMARY} onClick={() => shell.showItemInFolder(Tools.NormalizePathForCurrentPlatform(fullPath))}>{fullPath}</Tag>
<Divider />
<Tag fill={true} interactive={true} intent={Intent.PRIMARY} onClick={() => this.openItem(item)}>Open...</Tag>
<Divider />
<b>Attached to:</b><br />
<ul>
{attached.map((b) => <li key={`${b.id}-li`}><Tag interactive={true} key={`${b.id}-tag`} fill={true} intent={Intent.PRIMARY} onClick={() => {
this.editor.selectedNodeObservable.notifyObservers(b);
this.editor.preview.focusSelectedNode(false);
}}>{b.name}</Tag></li>)}
</ul>
<Divider />
<img
src={item.base64}
style={{
width: "256px",
height: "256px",
objectFit: "contain",
backgroundColor: "#222222",
transform: "translate(50%)",
}}
></img>
</>
);
}
/**
* Adds a new folder.
*/
private async _addNewFolder(): Promise<void> {
const name = await Dialog.Show("New Folder Name", "Please provide a name for the new folder");
const path = join(this._getCurrentPath(), name);
const exists = await pathExists(path);
if (exists) {
return Alert.Show("Can't Create Folder", `A folder named "${name}" already exists.`);
}
// Craete folder
await mkdir(path);
this.refresh();
}
/**
* Returns the navbar properties.
*/
private _getPathBrowser(): IBreadcrumbProps[] {
const result: IBreadcrumbProps[] = [{ text: this._getBreadCumpText("Scene", "./"), icon: "folder-close", onClick: () => {
ScriptAssets._Path = "";
this.refresh();
} }];
if (ScriptAssets._Path === "") {
return result;
}
const split = ScriptAssets._Path.replace(/\\/, "/").split("/");
let previous = "";
split.forEach((s) => {
previous = join(previous, s);
const path = previous;
result.push({ text: this._getBreadCumpText(s, path), icon: "folder-close", onClick: () => {
ScriptAssets._Path = normalize(path);
this.refresh();
} });
});
return result;
}
/**
* Returns the breadcump text.
*/
private _getBreadCumpText(text: string, path: string): React.ReactNode {
return (
<span
onDragEnter={(ev) => {
if (!this.itemBeingDragged) { return; }
(ev.target as HTMLSpanElement).style.background = "#222222";
}}
onDragLeave={(ev) => {
if (!this.itemBeingDragged) { return; }
(ev.target as HTMLSpanElement).style.background = "";
}}
onDrop={async (ev) => {
if (!this.itemBeingDragged) { return; }
(ev.target as HTMLSpanElement).style.background = "";
const root = join(WorkSpace.DirPath!, "src", "scenes");
const target = join(root, path);
const src = join(root, this.itemBeingDragged.key);
const dest = join(target, basename(this.itemBeingDragged.key));
if (src === dest) { return; }
await move(src, dest);
this._updateAttachedElements(src, dest);
this.refresh();
}}
>
{text}
</span>
);
}
/**
* Updates the attached elements that can have attached scripts.
*/
private _updateAttachedElements(from: string, to: string): void {
from = from.replace(/\\/g, "/").replace(WorkSpace.DirPath!.replace(/\\/g, "/"), "");
to = to.replace(/\\/g, "/").replace(WorkSpace.DirPath!.replace(/\\/g, "/"), "");
const all = (this.editor.scene!.meshes as Node[])
.concat(this.editor.scene!.lights)
.concat(this.editor.scene!.cameras)
.concat(this.editor.scene!.transformNodes);
all.forEach((n) => {
if (!n.metadata?.script) { return; }
if (n.metadata.script.name !== from) { return; }
n.metadata.script.name = to;
});
}
/**
* Returns the current path being browsed by the assets component.
*/
private _getCurrentPath(): string {
return join(WorkSpace.DirPath!, "src", "scenes", ScriptAssets._Path);
}
/**
* Adds a new script.
*/
private async _addScript(): Promise<void> {
const name = await Dialog.Show("Script name?", "Please provide a name for the new script");
const path = join(this._getCurrentPath(), `${name}.ts`);
const exists = await pathExists(path);
if (exists) {
return Alert.Show("Can't Create Script", `A script named "${name}" already exists.`);
}
const skeleton = await readFile(join(Tools.GetAppPath(), `assets/scripts/script.ts`), { encoding: "utf-8" });
await writeFile(path, skeleton);
await ProjectExporter.GenerateScripts(this.editor);
return this.refresh();
}
/**
* Returns wether or not the given script asset item is attached to a node or not.
*/
private _isScriptAttached(key: string): boolean {
const nodes: (Node | Scene)[] = [
this.editor.scene!,
...this.editor.scene!.meshes,
...this.editor.scene!.cameras,
...this.editor.scene!.lights,
...this.editor.scene!.transformNodes,
];
const path = join("src", "scenes", key);
for (const n of nodes) {
if (n.metadata?.script?.name === path) {
return true;
}
}
return false;
}
} | the_stack |
import {repeat} from 'lit-html/directives/repeat.js';
import {render, html} from 'lit-html';
import {queryParams} from '../../utils/query-params.js';
const defaults = {
// Which repeat method to use ('repeat' or 'map')
method: (queryParams.method ?? 'repeat') as keyof typeof methods,
// Item template to use ('li' or 'input')
itemType: (queryParams.itemType ?? 'li') as keyof typeof itemTemplates,
// Delay (when itemType=ce)
delay: (queryParams.delay ?? 0) as number,
// Initial count of items to create
initialCount: 1000,
// Replace items with newly created items (also specify 'from' and 'to')
replaceCount: 0,
// Remove items (also specify 'from')
removeCount: 0,
// Move items (also specify 'from' and 'to')
moveCount: 0,
// Add items (also specify 'to')
addCount: 0,
// Add items equally spaced through list
addStripeCount: 0,
// Remove items equally spaced through list
removeStripeCount: 0,
// Replace items with newly created items equally spaced through list
replaceStripeCount: 0,
// Swap items (also specify 'from' and 'to)
swapCount: 0,
// Reverse the order of items (also specify 'from' and 'to)
reverseCount: 0,
// Shuffle items (also specify 'from' and 'to)
shuffleCount: 0,
// 'from' item index used in operations (remove, move, swap)
from: 0,
// 'to' item index used in operations (add, move, swap)
to: 1000,
// When true, supported operations are mirrored symetrically on the other side
// of the list
mirror: false,
// Number of times to loop, repeating the same operation on the list
loopCount: 10,
};
const preset: {[index: string]: Partial<typeof defaults>} = {
render: {initialCount: 1000},
nop: {},
add: {addCount: 10, to: 100, loopCount: 50},
remove: {removeCount: 10, from: 100, loopCount: 50},
addEdges: {addCount: 100, to: 0, mirror: true, loopCount: 10},
removeEdges: {removeCount: 100, from: 0, mirror: true, loopCount: 10},
addMirror: {addCount: 100, to: 100, mirror: true, loopCount: 10},
removeMirror: {removeCount: 100, from: 100, mirror: true, loopCount: 10},
addStripe: {addStripeCount: 50, loopCount: 10},
removeStripe: {removeStripeCount: 50, loopCount: 10},
swapOne: {swapCount: 1, from: 100, to: 800, loopCount: 100},
swapMany: {swapCount: 100, from: 100, to: 800, loopCount: 4},
swapEdges: {swapCount: 1, from: 0, to: 999, loopCount: 100},
moveForwardOne: {moveCount: 1, from: 100, to: 800, loopCount: 100},
moveForwardMany: {moveCount: 100, from: 100, to: 800, loopCount: 4},
moveBackwardOne: {moveCount: 1, from: 800, to: 100, loopCount: 100},
moveBackwardMany: {moveCount: 100, from: 800, to: 100, loopCount: 4},
reverse: {reverseCount: 1000, loopCount: 4},
shuffle: {shuffleCount: 1000, loopCount: 5},
replace: {replaceCount: 1000, loopCount: 2},
replaceStripe: {replaceStripeCount: 100, loopCount: 10},
removeAll: {removeCount: 1000, from: 0, loopCount: 1},
};
// `method` and `itemType` are special and override defaults
const customParams = ['method', 'itemType', 'delay'].reduce(
(n, k) => (k in queryParams ? n - 1 : n),
Object.keys(queryParams).length
);
// If query params are provided, put that operation in a `custom` step
const routine =
customParams === 0
? preset
: {
render: {...queryParams},
custom: {...queryParams},
};
let gid = 0;
const container = document.getElementById('container')!;
type Item = {
id: number;
text: string;
};
const createItem = () => ({id: gid, text: `item ${gid++}`});
const createItems = (count: number): Item[] =>
new Array(count).fill(0).map(createItem);
const itemTemplates = {
li: (item: Item) => html`<li>${item.text}</li>`,
input: (item: Item) =>
html`<div>${item.text}: <input value="${item.text}" /></div>`,
ce: (item: Item) => html`<c-e .text=${item.text}></c-e>`,
};
if (defaults.itemType === 'ce') {
customElements.define(
'c-e',
class extends HTMLElement {
set text(s: string) {
this.textContent = s;
if (defaults.delay > 0) {
const end = performance.now() + defaults.delay;
while (performance.now() < end) {
/* spin loop */
}
}
}
get item() {
return this.textContent;
}
}
);
}
const methods = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
repeat(items: Item[], renderItem: (item: Item) => any) {
return html`<ul>
${repeat(items, (item) => item.id, renderItem)}
</ul>`;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
map(items: Item[], renderItem: (item: Item) => any) {
return html`<ul>
${items.map(renderItem)}
</ul>`;
},
};
let items: Item[] = [];
for (const [step, values] of Object.entries(routine)) {
const s = {...defaults, ...values};
const renderTemplate = methods[s.method];
const renderItem = itemTemplates[s.itemType];
if (step === 'render') {
items = createItems(s.initialCount);
performance.mark('render-start');
render(renderTemplate(items, renderItem), container);
performance.measure('render', 'render-start');
performance.mark('update-start');
} else {
// TODO(kschaaf): Accumulate measurements around just the render
// once/if https://github.com/Polymer/tachometer/issues/196 is resolved
performance.mark(`${step}-start`);
for (let i = 0; i < s.loopCount; i++) {
if (s.replaceCount) {
items = [
...items.slice(0, s.from),
...createItems(s.replaceCount),
...items.slice(s.to),
];
}
if (s.removeCount) {
items = items.filter(
(_, i) => i < s.from || i >= s.from + s.removeCount
);
if (s.mirror) {
items = items.filter(
(_, i) =>
i < items.length - s.from - s.removeCount ||
i >= items.length - s.from
);
}
}
if (s.addCount) {
items = [
...items.slice(0, s.to),
...createItems(s.addCount),
...items.slice(s.to),
];
if (s.mirror) {
items = [
...items.slice(0, items.length - s.to),
...createItems(s.addCount),
...items.slice(items.length - s.to),
];
}
}
if (s.addStripeCount) {
const step = (items.length + s.addStripeCount) / s.addStripeCount;
for (let i = 0; i < s.addStripeCount; i++) {
items.splice(i * step, 0, createItem());
}
}
if (s.removeStripeCount) {
const step = (items.length - s.removeStripeCount) / s.removeStripeCount;
for (let i = 0; i < s.removeStripeCount; i++) {
items.splice(i * step, 1);
}
}
if (s.replaceStripeCount) {
const step = items.length / s.replaceStripeCount;
for (let i = 0; i < s.replaceStripeCount; i++) {
items[i * step] = createItem();
}
}
if (s.swapCount) {
items = [
...items.slice(0, s.from),
...items.slice(s.to, s.to + s.swapCount),
...items.slice(s.from + s.swapCount, s.to),
...items.slice(s.from, s.from + s.swapCount),
...items.slice(s.to + s.swapCount),
];
}
if (s.moveCount) {
if (s.from < s.to) {
items = [
...items.slice(0, s.from),
...items.slice(s.from + s.moveCount, s.to),
...items.slice(s.from, s.from + s.moveCount),
...items.slice(s.to),
];
} else {
items = [
...items.slice(0, s.to),
...items.slice(s.from, s.from + s.moveCount),
...items.slice(s.to, s.from),
...items.slice(s.from + s.moveCount),
];
}
if (s.mirror) {
const mfrom = items.length - s.from - s.moveCount;
const mto = items.length - s.to;
if (mfrom < mto) {
items = [
...items.slice(0, mfrom),
...items.slice(mfrom + s.moveCount, mto),
...items.slice(mfrom, mfrom + s.moveCount),
...items.slice(mto),
];
} else {
items = [
...items.slice(0, mto),
...items.slice(mfrom, mfrom + s.moveCount),
...items.slice(mto, mfrom),
...items.slice(mfrom + s.moveCount),
];
}
}
}
if (s.reverseCount) {
items = [
...items.slice(0, s.from),
...items.slice(s.from, s.to).reverse(),
...items.slice(s.to),
];
}
if (s.shuffleCount) {
const shuffled = items.slice(s.from, s.to);
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
items = [...items.slice(0, s.from), ...shuffled, ...items.slice(s.to)];
}
// TODO(kschaaf): Accumulate measurements around just the render
// once/if https://github.com/Polymer/tachometer/issues/196 is resolved
// performance.mark(`${step}-start`);
render(renderTemplate(items, renderItem), container);
// performance.measure(step, `${step}-start`);
}
performance.measure(step, `${step}-start`);
}
}
performance.measure('update', `update-start`);
performance.measure('total', 'render-start');
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).tachometerResult =
performance.getEntriesByName('total')[0].duration;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
document.title = (window as any).tachometerResult.toFixed(2) + 'ms';
console.table({
...Object.keys(routine).reduce(
(p: {[index: string]: number}, n) => (
(p[n] = performance
.getEntriesByName(n)
.reduce((p, n) => p + n.duration, 0)),
p
),
{}
),
update: performance
.getEntriesByName('update')
.reduce((p, n) => p + n.duration, 0),
total: performance.getEntriesByName('total')[0].duration,
'items.length (at end)': items.length,
});
// Put items & render on window for debugging
Object.assign(window, {
items,
render: (step = 'render') => {
const t = methods[routine[step].method || defaults.method];
const i = itemTemplates[routine[step].itemType || defaults.itemType];
render(t(items, i), container);
},
});
// Debug helper
const error = (msg: string) => {
console.log(items.map((i) => i.id));
console.error(msg);
const div = document.createElement('div');
div.innerHTML = `<span style="color:red;font-size:2em;">${msg}</span>`;
document.body.insertBefore(div, document.body.firstChild);
};
// Assert items were rendered in correct order
if (container.firstElementChild!.children.length !== items.length) {
error(`Length mismatch!`);
} else {
for (
let e = container.firstElementChild!.firstElementChild!, i = 0;
e;
e = e.nextElementSibling!, i++
) {
if (!items[i] || !e.textContent!.includes(items[i].text)) {
error(`Mismatch at ${i}`);
break;
}
}
} | the_stack |
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
HostBinding,
HostListener,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
SimpleChanges,
SkipSelf,
TemplateRef,
ViewChild,
ViewChildren,
} from '@angular/core';
import { arrayClear, arrayHasItem, arrayRemoveItem, eachPair, empty, first, indexOf, isArray, isNumber } from '@deepkit/core';
import Hammer from 'hammerjs';
import { isObservable, Observable } from 'rxjs';
import { CdkVirtualScrollViewport } from '@angular/cdk/scrolling';
import { DropdownComponent } from '../button';
import { detectChangesNextFrame } from '../app/utils';
import { findParentWithClass } from '../../core/utils';
/**
* Directive to allow dynamic content in a cell.
*
* ```html
* <dui-table-column>
* <ng-container *duiTableCell="let item">
* {{item.fieldName | date}}
* </ng-container>
* </dui-table-column>
* ```
*/
@Directive({
selector: '[duiTableCell]',
})
export class TableCellDirective {
constructor(public template: TemplateRef<any>) {
}
}
/**
* Can be used to define own dropdown items once the user opens the header context menu.
*/
@Directive({
selector: 'dui-dropdown[duiTableCustomHeaderContextMenu]',
})
export class TableCustomHeaderContextMenuDirective {
constructor(public readonly dropdown: DropdownComponent) {
}
}
/**
* Can be used to define own dropdown items once the user opens the row context menu.
*/
@Directive({
selector: 'dui-dropdown[duiTableCustomRowContextMenu]',
})
export class TableCustomRowContextMenuDirective {
constructor(public readonly dropdown: DropdownComponent) {
}
}
/**
* Directive to allow dynamic content in a column header.
*
* ```html
* <dui-table-column name="fieldName">
* <ng-container *duiTableHead>
* <strong>Header</strong>
* </ng-container>
* </dui-table-column>
* ```
*/
@Directive({
selector: '[duiTableHeader]',
})
export class TableHeaderDirective {
constructor(public template: TemplateRef<any>) {
}
}
/**
* Defines a new column.
*/
@Directive({
selector: 'dui-table-column'
})
export class TableColumnDirective {
/**
* The name of the column. Needs to be unique. If no renderer (*duiTableCell) is specified, this
* name is used to render the content T[name].
*/
@Input('name') name: string = '';
/**
* A different header name. Use dui-table-header to render HTML there.
*/
@Input('header') header?: string;
/**
* Default width.
*/
@Input('width') width?: number | string = 100;
/**
* Adds additional class to the columns cells.
*/
@Input('class') class: string = '';
/**
* Whether this column is start hidden. User can unhide it using the context menu on the header.
*/
@Input('hidden') hidden: boolean | '' = false;
@Input('sortable') sortable: boolean = true;
@Input('hideable') hideable: boolean = true;
/**
* At which position this column will be placed.
*/
@Input('position') position?: number;
/**
* This is the new position when the user moved it manually.
* @hidden
*/
overwrittenPosition?: number;
@ContentChild(TableCellDirective, { static: false }) cell?: TableCellDirective;
@ContentChild(TableHeaderDirective, { static: false }) headerDirective?: TableHeaderDirective;
isHidden() {
return this.hidden !== false;
}
toggleHidden() {
this.hidden = !this.isHidden();
}
/**
* @hidden
*/
getWidth(): string | undefined {
if (!this.width) return undefined;
if (isNumber(this.width)) {
return this.width + 'px';
}
return this.width;
}
/**
* @hidden
*/
public getPosition() {
if (this.overwrittenPosition !== undefined) {
return this.overwrittenPosition;
}
return this.position;
}
}
@Component({
selector: 'dui-table',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<dui-dropdown #headerDropdown>
<dui-dropdown-item
*ngFor="let column of sortedColumnDefs; trackBy: trackByColumn"
[selected]="!column.isHidden()"
(mousedown)="column.toggleHidden(); storePreference(); sortColumnDefs(); headerDropdown.close()"
>
<div *ngIf="column.hideable">
<ng-container *ngIf="column.name !== undefined && !column.headerDirective">
{{column.header || column.name}}
</ng-container>
<ng-container
*ngIf="column.name !== undefined && column.headerDirective"
[ngTemplateOutlet]="column.headerDirective.template"
[ngTemplateOutletContext]="{$implicit: column}"></ng-container>
</div>
</dui-dropdown-item>
<dui-dropdown-separator></dui-dropdown-separator>
<dui-dropdown-item (click)="resetAll()">Reset all</dui-dropdown-item>
</dui-dropdown>
<div [style.height]="autoHeight !== false ? height + 'px' : '100%'" [style.minHeight.px]="itemHeight">
<div class="header" *ngIf="showHeader" #header
[contextDropdown]="customHeaderDropdown ? customHeaderDropdown.dropdown : headerDropdown">
<div class="th"
*ngFor="let column of visibleColumns(sortedColumnDefs); trackBy: trackByColumn"
[style.width]="column.getWidth()"
(mousedown)="sortBy(column.name || '', $event)"
[attr.name]="column.name"
[style.top]="scrollTop + 'px'"
#th>
<ng-container
*ngIf="column.headerDirective"
[ngTemplateOutlet]="column.headerDirective.template"
[ngTemplateOutletContext]="{$implicit: column}"></ng-container>
<ng-container *ngIf="column.name !== undefined && !column.headerDirective">
{{column.header || column.name}}
</ng-container>
<ng-container *ngIf="sort[column.name]">
<dui-icon *ngIf="sort[column.name] === 'desc'" [size]="12" name="arrow_down"></dui-icon>
<dui-icon *ngIf="sort[column.name] === 'asc'" [size]="12" name="arrow_up"></dui-icon>
</ng-container>
<dui-splitter (modelChange)="setColumnWidth(column, $event)"
indicator position="right"></dui-splitter>
</div>
</div>
<div class="body" [class.with-header]="showHeader" (click)="clickCell($event)"
(dblclick)="dblClickCell($event)">
<cdk-virtual-scroll-viewport #viewportElement
class="overlay-scrollbar-small"
[itemSize]="itemHeight"
>
<ng-container
*cdkVirtualFor="let row of filterSorted(sorted); trackBy: trackByFn; let i = index; odd as isOdd">
<div class="table-row {{rowClass ? rowClass(row) : ''}}"
[contextDropdown]="customRowDropdown ? customRowDropdown.dropdown : undefined"
[class.selected]="selectedMap.has(row)"
[class.odd]="isOdd"
[style.height.px]="itemHeight"
(mousedown)="select(row, $event)"
(contextmenu)="select(row, $event)"
(dblclick)="dbclick.emit(row)"
>
<div class="table-cell"
*ngFor="let column of visibleColumns(sortedColumnDefs); trackBy: trackByColumn"
[class]="column.class + (cellClass ? ' ' + cellClass(row, column.name) : '')"
[attr.row-column]="column.name"
[attr.row-i]="i"
[style.width]="column.getWidth()"
>
<ng-container *ngIf="column.cell">
<ng-container [ngTemplateOutlet]="column.cell!.template"
[ngTemplateOutletContext]="{ $implicit: row }"></ng-container>
</ng-container>
<ng-container *ngIf="!column.cell">
{{ column.name ? valueFetcher(row, column.name) : '' }}
</ng-container>
</div>
</div>
</ng-container>
</cdk-virtual-scroll-viewport>
</div>
</div>
`,
styleUrls: ['./table.component.scss'],
host: {
'[class.no-focus-outline]': 'noFocusOutline !== false',
'[class.borderless]': 'borderless !== false',
'[class.overlay-scrollbar]': 'true',
'[class.auto-height]': 'autoHeight !== false',
},
})
export class TableComponent<T> implements AfterViewInit, OnInit, OnChanges, OnDestroy {
/**
* @hidden
*/
@HostBinding() tabindex = 0;
@Input() borderless: boolean | '' = false;
/**
* Array of items that should be used for each row.
*/
@Input() public items!: T[] | Observable<T[]>;
/**
* Since dui-table has virtual-scroll active per default, it's required to define the itemHeight to
* make scrolling actually workable correctly.
*/
@Input() public itemHeight: number = 25;
/**
* Whether the table height is calculated based on current item count and [itemHeight].
*/
@Input() public autoHeight: boolean = false;
/**
* Current calculated height, used only when autoHeight is given.
*/
public height: number = 23;
/**
* Whether the header should be shown.
*/
@Input() public showHeader: boolean = true;
/**
* Default field of T for sorting.
*/
@Input() public defaultSort: string = '';
/**
* Default sorting order.
*/
@Input() public defaultSortDirection: 'asc' | 'desc' = 'asc';
/**
* Whether rows are selectable.
*/
@Input() public selectable: boolean | '' = false;
/**
* Whether multiple rows are selectable at the same time.
*/
@Input() public multiSelect: boolean | '' = false;
/**
* TrackFn for ngFor to improve performance. Default is order by index.
*/
@Input() public trackFn?: (index: number, item: T) => any;
/**
* Not used yet.
*/
@Input() public displayInitial: number = 20;
/**
* Not used yet.
*/
@Input() public increaseBy: number = 10;
/**
* Filter function.
*/
@Input() public filter?: (item: T) => boolean;
@Input() public rowClass?: (item: T) => string | undefined;
@Input() public cellClass?: (item: T, column: string) => string | undefined;
/**
* When the user changes the order or width of the columns, the information is stored
* in localStorage using this key, prefixed with `@dui/table/`.
*/
@Input() public preferenceKey: string = 'root';
/**
* Filter query.
*/
@Input() public filterQuery?: string;
@Input() public columnState: { name: string, position: number, visible: boolean }[] = [];
/**
* Against which fields filterQuery should run.
*/
@Input() public filterFields?: string[];
/**
* Alternate object value fetcher, important for sorting and filtering.
*/
@Input() public valueFetcher = (object: any, path: string): any => {
const dot = path.indexOf('.');
if (dot === -1) return object[path];
return object[path.substr(0, dot)][path.substr(dot + 1)];
};
/**
* A hook to provide custom sorting behavior for certain columns.
*/
@Input() public sortFunction?: (sort: { [name: string]: 'asc' | 'desc' }) => (((a: T, b: T) => number) | undefined);
/**
* Whether sorting is enabled (clicking headers trigger sort).
*/
@Input() public sorting: boolean = true;
@Input() noFocusOutline: boolean | '' = false;
@Input() public sort: { [column: string]: 'asc' | 'desc' } = {};
public rawItems: T[] = [];
public sorted: T[] = [];
public selectedMap = new Map<T, boolean>();
/**
* Elements that are selected, by reference.
*/
@Input() public selected: T[] = [];
protected selectedHistory: T[] = [];
/**
* Elements that are selected, by reference.
*/
@Output() public selectedChange: EventEmitter<T[]> = new EventEmitter();
@Output() public sortedChange: EventEmitter<T[]> = new EventEmitter();
/**
* When a row gets double clicked.
*/
@Output() public dbclick: EventEmitter<T> = new EventEmitter();
@Output() public customSort: EventEmitter<{ [column: string]: 'asc' | 'desc' }> = new EventEmitter();
@Output() public cellDblClick: EventEmitter<{ item: T, column: string }> = new EventEmitter();
@Output() public cellClick: EventEmitter<{ item: T, column: string }> = new EventEmitter();
@ViewChild('header', { static: false }) header?: ElementRef;
@ViewChildren('th') ths?: QueryList<ElementRef<HTMLElement>>;
@ContentChildren(TableColumnDirective, { descendants: true }) columnDefs?: QueryList<TableColumnDirective>;
@ContentChild(TableCustomHeaderContextMenuDirective, { static: false }) customHeaderDropdown?: TableCustomHeaderContextMenuDirective;
@ContentChild(TableCustomRowContextMenuDirective, { static: false }) customRowDropdown?: TableCustomRowContextMenuDirective;
@ViewChild(CdkVirtualScrollViewport, { static: true }) viewport!: CdkVirtualScrollViewport;
@ViewChild('viewportElement', { static: true, read: ElementRef }) viewportElement!: ElementRef;
public sortedColumnDefs: TableColumnDirective[] = [];
columnMap: { [name: string]: TableColumnDirective } = {};
public displayedColumns?: string[] = [];
protected ignoreThisSort = false;
public scrollTop = 0;
constructor(
protected element: ElementRef,
protected cd: ChangeDetectorRef,
@SkipSelf() protected parentCd: ChangeDetectorRef,
protected zone: NgZone,
) {
}
public setColumnWidth(column: TableColumnDirective, width: number) {
column.width = width;
detectChangesNextFrame(this.cd, () => {
this.storePreference();
});
}
ngOnInit() {
if (this.defaultSort) {
this.sort[this.defaultSort] = this.defaultSortDirection;
}
}
ngOnDestroy(): void {
}
@HostListener('window:resize')
onResize() {
requestAnimationFrame(() => {
this.viewport.checkViewportSize();
});
}
resetAll() {
localStorage.removeItem('@dui/table/preferences-' + this.preferenceKey);
if (!this.columnDefs) return;
for (const column of this.columnDefs.toArray()) {
column.width = 100;
column.hidden = false;
column.overwrittenPosition = undefined;
}
}
storePreference() {
const preferences: { [name: string]: { hidden: boolean | '', width?: number | string, order?: number } } = {};
if (!this.columnDefs) return;
for (const column of this.columnDefs.toArray()) {
preferences[column.name] = {
width: column.width,
order: column.overwrittenPosition,
hidden: column.hidden
};
}
localStorage.setItem('@dui/table/preferences-' + this.preferenceKey, JSON.stringify(preferences));
}
loadPreference() {
const preferencesJSON = localStorage.getItem('@dui/table/preferences-' + this.preferenceKey);
if (!preferencesJSON) return;
const preferences = JSON.parse(preferencesJSON);
for (const i in preferences) {
if (!preferences.hasOwnProperty(i)) continue;
if (!this.columnMap[i]) continue;
if (preferences[i].width !== undefined) this.columnMap[i].width = preferences[i].width;
if (preferences[i].order !== undefined) this.columnMap[i].overwrittenPosition = preferences[i].order;
if (preferences[i].hidden !== undefined) this.columnMap[i].hidden = preferences[i].hidden;
}
}
dblClickCell(event: MouseEvent) {
if (!this.cellDblClick.observers.length) return;
if (!event.target) return;
const cell = findParentWithClass(event.target as HTMLElement, 'table-cell');
if (!cell) return;
const i = parseInt(cell.getAttribute('row-i') || '', 10);
const column = cell.getAttribute('row-column') || '';
this.cellDblClick.emit({ item: this.sorted[i], column });
}
clickCell(event: MouseEvent) {
if (!this.cellClick.observers.length) return;
if (!event.target) return;
const cell = findParentWithClass(event.target as HTMLElement, 'table-cell');
if (!cell) return;
const i = parseInt(cell.getAttribute('row-i') || '', 10);
const column = cell.getAttribute('row-column') || '';
this.cellClick.emit({ item: this.sorted[i], column });
}
/**
* Toggles the sort by the given column name.
*/
public sortBy(name: string, $event?: MouseEvent) {
if (!this.sorting) return;
if (this.ignoreThisSort) {
this.ignoreThisSort = false;
return;
}
if ($event && $event.button === 2) return;
//only when shift is pressed do we activate multi-column sort
if (!$event || ! $event.shiftKey) {
for (const member in this.sort) if (member !== name) delete this.sort[member];
}
if (this.columnMap[name]) {
const headerDef = this.columnMap[name];
if (!headerDef.sortable) {
return;
}
}
if (!this.sort[name]) {
this.sort[name] = 'asc';
} else {
if (this.sort[name] === 'asc') this.sort[name] = 'desc';
else if (this.sort[name] === 'desc') delete this.sort[name];
}
if (this.customSort.observers.length) {
this.customSort.emit(this.sort);
} else {
this.doSort();
}
}
/**
* @hidden
*/
trackByFn = (index: number, item: any) => {
return this.trackFn ? this.trackFn(index, item) : index;
};
/**
* @hidden
*/
trackByColumn(index: number, column: TableColumnDirective) {
return column.name;
}
/**
* @hidden
*/
filterSorted(items: T[]): T[] {
//apply filter
if (this.filter || (this.filterQuery && this.filterFields)) {
return items.filter((v) => this.filterFn(v));
}
return items;
}
protected initHeaderMovement() {
if (this.header && this.ths) {
const mc = new Hammer(this.header!.nativeElement);
mc.add(new Hammer.Pan({ direction: Hammer.DIRECTION_ALL, threshold: 1 }));
interface Box {
left: number;
width: number;
element: HTMLElement;
directive: TableColumnDirective;
}
const THsBoxes: Box[] = [];
let element: HTMLElement | undefined;
let elementCells: HTMLElement[] = [];
let originalPosition = -1;
let foundBox: Box | undefined;
let rowCells: { cells: HTMLElement[] }[] = [];
let startOffsetLeft = 0;
let offsetLeft = 0;
let startOffsetWidth = 0;
let animationFrame: any;
mc.on('panstart', (event: HammerInput) => {
foundBox = undefined;
if (this.ths && event.target.classList.contains('th')) {
element = event.target as HTMLElement;
element.style.zIndex = '1000000';
element.style.opacity = '0.8';
startOffsetLeft = element.offsetLeft;
offsetLeft = element.offsetLeft;
startOffsetWidth = element.offsetWidth;
arrayClear(THsBoxes);
rowCells = [];
for (const th of this.ths.toArray()) {
const directive: TableColumnDirective = this.sortedColumnDefs.find((v) => v.name === th.nativeElement.getAttribute('name')!)!;
const cells = [...this.element.nativeElement.querySelectorAll('div[row-column="' + directive.name + '"]')] as any as HTMLElement[];
if (th.nativeElement === element) {
originalPosition = this.sortedColumnDefs.indexOf(directive);
elementCells = cells;
for (const cell of elementCells) {
cell.classList.add('active-drop');
}
} else {
for (const cell of cells) {
cell.classList.add('other-cell');
}
th.nativeElement.classList.add('other-cell');
}
THsBoxes.push({
left: th.nativeElement.offsetLeft,
width: th.nativeElement.offsetWidth,
element: th.nativeElement,
directive: directive,
});
rowCells.push({ cells: cells });
}
}
});
mc.on('panend', (event: HammerInput) => {
if (animationFrame) {
cancelAnimationFrame(animationFrame);
}
if (element) {
element.style.left = '0px';
element.style.zIndex = '1';
element.style.opacity = '1';
for (const t of rowCells) {
for (const cell of t.cells) {
cell.classList.remove('active-drop');
cell.classList.remove('other-cell');
cell.style.left = '0px';
}
}
this.ignoreThisSort = true;
for (const box of THsBoxes) {
box.element.style.left = '0px';
box.element.classList.remove('other-cell');
}
if (foundBox) {
const newPosition = this.sortedColumnDefs.indexOf(foundBox.directive);
if (originalPosition !== newPosition) {
const directive = this.sortedColumnDefs[originalPosition];
this.sortedColumnDefs.splice(originalPosition, 1);
this.sortedColumnDefs.splice(newPosition, 0, directive);
for (let [i, v] of eachPair(this.sortedColumnDefs)) {
v.overwrittenPosition = i;
}
this.sortColumnDefs();
}
}
this.storePreference();
element = undefined;
}
});
mc.on('pan', (event: HammerInput) => {
if (animationFrame) {
cancelAnimationFrame(animationFrame);
}
animationFrame = requestAnimationFrame(() => {
if (element) {
element!.style.left = (event.deltaX) + 'px';
const offsetLeft = startOffsetLeft + event.deltaX;
for (const cell of elementCells) {
cell.style.left = (event.deltaX) + 'px';
}
let afterElement = false;
foundBox = undefined;
for (const [i, box] of eachPair(THsBoxes)) {
if (box.element === element) {
afterElement = true;
continue;
}
box.element.style.left = '0px';
for (const cell of rowCells[i].cells) {
cell.style.left = '0px';
}
if (!afterElement && box.left + (box.width / 2) > offsetLeft) {
//the dragged element is before the current
box.element.style.left = startOffsetWidth + 'px';
for (const cell of rowCells[i].cells) {
cell.style.left = startOffsetWidth + 'px';
}
if (foundBox && box.left > foundBox.left) {
//we found already a box that fits and that is more left
continue;
}
foundBox = box;
} else if (afterElement && box.left + (box.width / 2) < offsetLeft + startOffsetWidth) {
//the dragged element is after the current
box.element.style.left = -startOffsetWidth + 'px';
for (const cell of rowCells[i].cells) {
cell.style.left = -startOffsetWidth + 'px';
}
foundBox = box;
}
}
}
});
});
}
}
ngAfterViewInit(): void {
this.viewport.renderedRangeStream.subscribe(() => {
this.cd.detectChanges();
});
this.zone.runOutsideAngular(() => {
this.viewportElement.nativeElement.addEventListener('scroll', () => {
const scrollLeft = this.viewportElement.nativeElement.scrollLeft;
this.header!.nativeElement.scrollLeft = scrollLeft;
});
});
this.initHeaderMovement();
if (this.columnDefs) {
setTimeout(() => {
this.columnDefs!.changes.subscribe(() => {
this.updateDisplayColumns();
this.loadPreference();
this.sortColumnDefs();
});
this.updateDisplayColumns();
this.loadPreference();
this.sortColumnDefs();
});
}
}
public sortColumnDefs() {
if (this.columnDefs) {
const originalDefs = this.columnDefs.toArray();
this.sortedColumnDefs = this.columnDefs.toArray().slice(0);
this.sortedColumnDefs = this.sortedColumnDefs.sort((a: TableColumnDirective, b: TableColumnDirective) => {
const aPosition = a.getPosition() === undefined ? originalDefs.indexOf(a) : a.getPosition()!;
const bPosition = b.getPosition() === undefined ? originalDefs.indexOf(b) : b.getPosition()!;
if (aPosition > bPosition) return 1;
if (aPosition < bPosition) return -1;
return 0;
});
detectChangesNextFrame(this.cd);
}
}
visibleColumns(t: TableColumnDirective[]): TableColumnDirective[] {
return t.filter(v => !v.isHidden());
}
filterFn(item: T) {
if (this.filter) {
return this.filter(item);
}
if (this.filterQuery && this.filterFields) {
const q = this.filterQuery!.toLowerCase();
for (const field of this.filterFields) {
if (-1 !== String((item as any)[field]).toLowerCase().indexOf(q)) {
return true;
}
}
return false;
}
return true;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.preferenceKey) {
this.loadPreference();
}
if (changes.items) {
if (isObservable(this.items)) {
this.items.subscribe((items: T[]) => {
this.rawItems = items;
this.sorted = items;
this.doSort();
this.viewport.checkViewportSize();
});
} else if (isArray(this.items)) {
this.rawItems = this.items;
this.sorted = this.items;
this.doSort();
this.viewport.checkViewportSize();
} else {
this.rawItems = [];
this.sorted = [];
this.doSort();
this.viewport.checkViewportSize();
}
}
if (changes.selected) {
this.selectedMap.clear();
if (this.selected) {
for (const v of this.selected) {
this.selectedMap.set(v, true);
}
}
}
}
private updateDisplayColumns() {
this.displayedColumns = [];
this.columnMap = {};
if (this.columnDefs) {
for (const column of this.columnDefs.toArray()) {
this.displayedColumns.push(column.name!);
this.columnMap[column.name!] = column;
}
this.doSort();
}
}
private doSort() {
if (this.customSort.observers.length) return;
if (empty(this.sorted)) {
this.sorted = this.rawItems;
}
if (this.sortFunction) {
this.sorted.sort(this.sortFunction(this.sort));
} else {
const sort = Object.entries(this.sort);
sort.reverse(); //we start from bottom
let sortRoot = (a: any, b: any) => 0;
for (const [name, dir] of sort) {
sortRoot = this.createSortFunction(name, dir, sortRoot);
}
this.sorted.sort(sortRoot);
}
this.sortedChange.emit(this.sorted);
this.height = (this.sorted.length * this.itemHeight) + (this.showHeader ? 23 : 0) + 10; //10 is scrollbar padding
this.sorted = this.sorted.slice(0);
detectChangesNextFrame(this.parentCd);
}
protected createSortFunction(sortField: string, dir: 'asc' | 'desc', next?: (a: any, b: any) => number) {
return (a: T, b: T) => {
const aV = this.valueFetcher(a, sortField);
const bV = this.valueFetcher(b, sortField);
if (aV === undefined && bV === undefined) return next ? next(a, b) : 0;
if (aV === undefined && bV !== undefined) return +1;
if (aV !== undefined && bV === undefined) return -1;
if (dir === 'asc') {
if (aV > bV) return 1;
if (aV < bV) return -1;
} else {
if (aV > bV) return -1;
if (aV < bV) return 1;
}
return next ? next(a, b) : 0;
};
}
/**
* @hidden
*/
@HostListener('keydown', ['$event'])
onFocus(event: KeyboardEvent) {
if (event.key === 'Enter') {
const firstSelected = first(this.selected);
if (firstSelected) {
this.dbclick.emit(firstSelected);
}
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
event.preventDefault();
const firstSelected = first(this.selected);
if (!firstSelected) {
this.select(this.sorted[0]);
return;
}
let index = indexOf(this.sorted, firstSelected);
// if (-1 === index) {
// this.select(this.sorted[0]);
// this.paginator.pageIndex = 0;
// return;
// }
if (event.key === 'ArrowUp') {
if (0 === index) {
return;
}
index--;
}
if (event.key === 'ArrowDown') {
if (empty(this.sorted)) {
return;
}
index++;
}
if (this.sorted[index]) {
const item = this.sorted[index];
// if (event.shiftKey) {
// this.selectedMap[item.id] = true;
// this.selected.push(item);
// } else {
this.select(item);
const scrollTop = this.viewport.measureScrollOffset();
const viewportSize = this.viewport.getViewportSize();
const itemTop = this.itemHeight * index;
if (itemTop + this.itemHeight > viewportSize + scrollTop) {
const diff = (itemTop + this.itemHeight) - (viewportSize + scrollTop);
this.viewport.scrollToOffset(scrollTop + diff);
}
if (itemTop < scrollTop) {
const diff = (itemTop) - (scrollTop);
this.viewport.scrollToOffset(scrollTop + diff);
}
}
this.selectedChange.emit(this.selected.slice(0));
this.cd.markForCheck();
}
}
public deselect(item: T) {
arrayRemoveItem(this.selected, item);
this.selectedMap.delete(item);
detectChangesNextFrame(this.parentCd);
}
public select(item: T, $event?: MouseEvent) {
if (this.selectable === false) {
return;
}
if (this.multiSelect === false) {
this.selected = [item];
this.selectedMap.clear();
this.selectedMap.set(item, true);
} else {
if ($event && $event.shiftKey) {
const indexSelected = this.sorted.indexOf(item);
if (this.selected[0]) {
const firstSelected = this.sorted.indexOf(this.selected[0]);
this.selectedMap.clear();
this.selected = [];
if (firstSelected < indexSelected) {
//we select all from index -> indexSelected, downwards
for (let i = firstSelected; i <= indexSelected; i++) {
this.selected.push(this.sorted[i]);
this.selectedMap.set(this.sorted[i], true);
}
} else {
//we select all from indexSelected -> index, upwards
for (let i = firstSelected; i >= indexSelected; i--) {
this.selected.push(this.sorted[i]);
this.selectedMap.set(this.sorted[i], true);
}
}
} else {
//we start at 0 and select all until index
for (let i = 0; i <= indexSelected; i++) {
this.selected.push(this.sorted[i]);
this.selectedMap.set(this.sorted[i], true);
}
}
} else if ($event && $event.metaKey) {
if (arrayHasItem(this.selected, item)) {
arrayRemoveItem(this.selected, item);
this.selectedMap.delete(item);
} else {
this.selectedMap.set(item, true);
this.selected.push(item);
}
} else {
const isRightButton = $event && $event.button == 2;
const isItemSelected = arrayHasItem(this.selected, item);
const resetSelection = !isItemSelected || !isRightButton;
if (resetSelection) {
this.selected = [item];
this.selectedMap.clear();
this.selectedMap.set(item, true);
}
}
}
this.selectedChange.emit(this.selected);
detectChangesNextFrame(this.parentCd);
}
} | the_stack |
import { ApolloQueryResult, FetchResult } from "@apollo/client";
import {
CHANGE_USER_PASSWORD,
EXTERNAL_AUTHENTICATION_URL,
EXTERNAL_LOGOUT,
EXTERNAL_REFRESH,
EXTERNAL_VERIFY_TOKEN,
LOGIN,
OBTAIN_EXTERNAL_ACCESS_TOKEN,
REQUEST_PASSWORD_RESET,
REFRESH_TOKEN,
REGISTER,
SET_PASSWORD,
VERIFY_TOKEN,
REFRESH_TOKEN_WITH_USER,
} from "../apollo/mutations";
import {
ExternalAuthenticationUrlMutation,
ExternalAuthenticationUrlMutationVariables,
ExternalLogoutMutation,
ExternalLogoutMutationVariables,
ExternalObtainAccessTokensMutation,
ExternalObtainAccessTokensMutationVariables,
ExternalRefreshMutation,
ExternalRefreshMutationVariables,
ExternalVerifyMutation,
ExternalVerifyMutationVariables,
LoginMutation,
LoginMutationVariables,
PasswordChangeMutation,
PasswordChangeMutationVariables,
RefreshTokenMutation,
RefreshTokenMutationVariables,
RefreshTokenWithUserMutation,
RefreshTokenWithUserMutationVariables,
RegisterMutation,
RegisterMutationVariables,
RequestPasswordResetMutation,
RequestPasswordResetMutationVariables,
SetPasswordMutation,
SetPasswordMutationVariables,
VerifyTokenMutation,
VerifyTokenMutationVariables,
} from "../apollo/types";
import { SaleorClientMethodsProps } from "./types";
import {
ChangeUserPasswordOpts,
ExternalAuthOpts,
LoginOpts,
RegisterOpts,
RequestPasswordResetOpts,
SetPasswordOpts,
} from "./types";
import { storage } from "./storage";
import { USER } from "../apollo/queries";
export interface AuthSDK {
changePassword: (
opts: ChangeUserPasswordOpts
) => Promise<FetchResult<PasswordChangeMutation>>;
login: (opts: LoginOpts) => Promise<FetchResult<LoginMutation>>;
logout: () => Promise<ApolloQueryResult<null>[] | null>;
refreshToken: (
includeUser?: boolean
) => Promise<FetchResult<RefreshTokenMutation>>;
register: (opts: RegisterOpts) => Promise<FetchResult<RegisterMutation>>;
requestPasswordReset: (
opts: RequestPasswordResetOpts
) => Promise<FetchResult<RequestPasswordResetMutation>>;
setPassword: (
opts: SetPasswordOpts
) => Promise<FetchResult<SetPasswordMutation>>;
verifyToken: () => Promise<FetchResult<VerifyTokenMutation>>;
getExternalAuthUrl: (
opts: ExternalAuthOpts
) => Promise<FetchResult<ExternalAuthenticationUrlMutation>>;
getExternalAccessToken: (
opts: ExternalAuthOpts
) => Promise<FetchResult<ExternalObtainAccessTokensMutation>>;
logoutExternal: (
opts: ExternalAuthOpts
) => Promise<FetchResult<ExternalLogoutMutation>>;
refreshExternalToken: (
opts: ExternalAuthOpts
) => Promise<FetchResult<ExternalRefreshMutation>>;
verifyExternalToken: (
opts: ExternalAuthOpts
) => Promise<FetchResult<ExternalVerifyMutation>>;
}
export const auth = ({
apolloClient: client,
channel,
}: SaleorClientMethodsProps): AuthSDK => {
/**
* Authenticates user with email and password.
*
* @param opts - Object with user's email and password.
* @returns Promise resolved with CreateToken type data.
*/
const login: AuthSDK["login"] = opts => {
client.writeQuery({
query: USER,
data: {
authenticating: true,
},
});
return client.mutate<LoginMutation, LoginMutationVariables>({
mutation: LOGIN,
variables: {
...opts,
},
update: (_, { data }) => {
if (data?.tokenCreate?.token) {
storage.setTokens({
accessToken: data.tokenCreate.token,
csrfToken: data.tokenCreate.csrfToken!,
});
}
},
});
};
/**
* Clears stored token and Apollo store.
*
* @returns Apollo's native resetStore method.
*/
const logout: AuthSDK["logout"] = () => {
storage.clear();
client.writeQuery({
query: USER,
data: {
authenticating: false,
},
});
return client.resetStore();
};
/**
* Registers user with email and password.
*
* @param opts - Object with user's data. Email and password are required fields.
* "channel" can be changed by using first "setChannel" method from api.
* @returns Promise resolved with AccountRegister type data.
*/
const register: AuthSDK["register"] = async opts =>
await client.mutate<RegisterMutation, RegisterMutationVariables>({
mutation: REGISTER,
variables: {
input: {
...opts,
channel,
},
},
});
/**
* Refresh JWT token. Mutation will try to take refreshToken from the function's arguments.
* If it fails, it will try to use refreshToken from the http-only cookie called refreshToken.
*
* @param opts - Optional object with csrfToken and refreshToken. csrfToken is required when refreshToken is provided as a cookie.
* @returns Authorization token.
*/
const refreshToken: AuthSDK["refreshToken"] = (includeUser = false) => {
const csrfToken = storage.getCSRFToken();
if (!csrfToken) {
throw Error("csrfToken not present");
}
if (includeUser) {
return client.mutate<
RefreshTokenWithUserMutation,
RefreshTokenWithUserMutationVariables
>({
mutation: REFRESH_TOKEN_WITH_USER,
variables: {
csrfToken,
},
update: (_, { data }) => {
if (data?.tokenRefresh?.token) {
storage.setAccessToken(data.tokenRefresh.token);
} else {
logout();
}
},
});
} else {
return client.mutate<RefreshTokenMutation, RefreshTokenMutationVariables>(
{
mutation: REFRESH_TOKEN,
variables: {
csrfToken,
},
update: (_, { data }) => {
if (data?.tokenRefresh?.token) {
storage.setAccessToken(data.tokenRefresh.token);
} else {
logout();
}
},
}
);
}
};
/**
* Verify JWT token.
*
* @param token - Token value.
* @returns User assigned to token and the information if the token is valid or not.
*/
const verifyToken: AuthSDK["verifyToken"] = async () => {
const token = storage.getAccessToken();
if (!token) {
throw Error("Token not present");
}
const result = await client.mutate<
VerifyTokenMutation,
VerifyTokenMutationVariables
>({
mutation: VERIFY_TOKEN,
variables: { token },
});
if (!result.data?.tokenVerify?.isValid) {
logout();
}
return result;
};
/**
* Change the password of the logged in user.
*
* @param opts - Object with password and new password.
* @returns Errors if the passoword change has failed.
*/
const changePassword: AuthSDK["changePassword"] = async opts => {
const result = await client.mutate<
PasswordChangeMutation,
PasswordChangeMutationVariables
>({
mutation: CHANGE_USER_PASSWORD,
variables: { ...opts },
});
return result;
};
/**
* Sends an email with the account password modification link.
*
* @param opts - Object with slug of a channel which will be used for notify user,
* email of the user that will be used for password recovery and URL of a view
* where users should be redirected to reset the password. URL in RFC 1808 format.
*
* @returns Errors if there were some.
*/
const requestPasswordReset: AuthSDK["requestPasswordReset"] = async opts => {
const result = await client.mutate<
RequestPasswordResetMutation,
RequestPasswordResetMutationVariables
>({
mutation: REQUEST_PASSWORD_RESET,
variables: { ...opts, channel },
});
return result;
};
/**
* Sets the user's password from the token sent by email.
*
* @param opts - Object with user's email, password and one-time token required to set the password.
* @returns User instance, JWT token, JWT refresh token and CSRF token.
*/
const setPassword: AuthSDK["setPassword"] = opts => {
return client.mutate<SetPasswordMutation, SetPasswordMutationVariables>({
mutation: SET_PASSWORD,
variables: { ...opts },
update: (_, { data }) => {
if (data?.setPassword?.token) {
storage.setTokens({
accessToken: data.setPassword.token,
csrfToken: data.setPassword.csrfToken || null,
});
}
},
});
};
/**
* Executing externalAuthenticationUrl mutation will prepare special URL which will redirect user to requested
* page after successfull authentication. After redirection state and code fields will be added to the URL.
*
* @param opts - Object withpluginId default value set as "mirumee.authentication.openidconnect" and input as
* JSON with redirectUrl - the URL where the user should be redirected after successful authentication.
* @returns Authentication data and errors
*/
const getExternalAuthUrl: AuthSDK["getExternalAuthUrl"] = async opts => {
const result = await client.mutate<
ExternalAuthenticationUrlMutation,
ExternalAuthenticationUrlMutationVariables
>({
mutation: EXTERNAL_AUTHENTICATION_URL,
variables: { ...opts },
});
return result;
};
/**
* The externalObtainAccessTokens mutation will generate requested access tokens.
*
* @param opts - Object withpluginId default value set as "mirumee.authentication.openidconnect" and input as
* JSON with code - the authorization code received from the OAuth provider and state - the state value received
* from the OAuth provider
* @returns Login authentication data and errors
*/
const getExternalAccessToken: AuthSDK["getExternalAccessToken"] = opts => {
return client.mutate<
ExternalObtainAccessTokensMutation,
ExternalObtainAccessTokensMutationVariables
>({
mutation: OBTAIN_EXTERNAL_ACCESS_TOKEN,
variables: { ...opts },
update: (_, { data }) => {
if (data?.externalObtainAccessTokens?.token) {
storage.setTokens({
accessToken: data.externalObtainAccessTokens.token,
csrfToken: data.externalObtainAccessTokens.csrfToken || null,
});
}
},
});
};
/**
* The mutation will prepare the logout URL. All values passed in field input will be added as GET parameters to the logout request.
*
* @param opts - Object withpluginId default value set as "mirumee.authentication.openidconnect" and input as
* JSON with returnTo - the URL where a user should be redirected
* @returns Logout data and errors
*/
const logoutExternal: AuthSDK["logoutExternal"] = async opts => {
logout();
const result = await client.mutate<
ExternalLogoutMutation,
ExternalLogoutMutationVariables
>({
mutation: EXTERNAL_LOGOUT,
variables: { ...opts },
});
return result;
};
/**
* The externalRefresh mutation will generate new access tokens when provided with a valid refresh token.
* If the refresh token is not provided as an argument, the plugin will try to read it from a cookie
* set by the tokenCreate mutation. In that case, a matching CSRF token is required.
*
* @param opts - Object withpluginId default value set as "mirumee.authentication.openidconnect" and input as
* JSON with refreshToken - the refresh token which should be used to refresh the access token and
* csrfToken - required when refreshToken is not provided as an input
* @returns Token refresh data and errors
*/
const refreshExternalToken: AuthSDK["refreshExternalToken"] = opts => {
return client.mutate<
ExternalRefreshMutation,
ExternalRefreshMutationVariables
>({
mutation: EXTERNAL_REFRESH,
variables: { ...opts },
update: (_, { data }) => {
if (data?.externalRefresh?.token) {
storage.setAccessToken(data.externalRefresh.token);
}
},
});
};
/**
* The mutation will verify the authentication token.
*
* @param opts - Object withpluginId default value set as "mirumee.authentication.openidconnect" and input as
* JSON with refreshToken - the refresh token which should be used to refresh the access token and
* csrfToken - required when refreshToken is not provided as an input
* @returns Token verification data and errors
*/
const verifyExternalToken: AuthSDK["verifyExternalToken"] = async opts => {
const result = await client.mutate<
ExternalVerifyMutation,
ExternalVerifyMutationVariables
>({
mutation: EXTERNAL_VERIFY_TOKEN,
variables: { ...opts },
});
if (!result.data?.externalVerify?.isValid) {
storage.clear();
}
return result;
};
return {
changePassword,
getExternalAccessToken,
getExternalAuthUrl,
login,
logout,
logoutExternal,
refreshExternalToken,
refreshToken,
register,
requestPasswordReset,
setPassword,
verifyExternalToken,
verifyToken,
};
}; | the_stack |
import { isString, Message, TrustedTypesPolicy } from "../interfaces.js";
import type { ExecutionContext } from "../observation/observable.js";
import { FAST } from "../platform.js";
import { Parser } from "./markup.js";
import { bind, HTMLBindingDirective, oneTime } from "./binding.js";
import { Aspect, Aspected, ViewBehaviorFactory } from "./html-directive.js";
import type { HTMLTemplateCompilationResult as TemplateCompilationResult } from "./template.js";
import { HTMLView } from "./view.js";
const targetIdFrom = (parentId: string, nodeIndex: number): string =>
`${parentId}.${nodeIndex}`;
const descriptorCache: PropertyDescriptorMap = {};
interface NextNode {
index: number;
node: ChildNode | null;
}
// used to prevent creating lots of objects just to track node and index while compiling
const next: NextNode = {
index: 0,
node: null as ChildNode | null,
};
class CompilationContext<
TSource = any,
TParent = any,
TContext extends ExecutionContext<TParent> = ExecutionContext<TParent>
> implements TemplateCompilationResult<TSource, TParent, TContext> {
private proto: any = null;
private nodeIds = new Set<string>();
private descriptors: PropertyDescriptorMap = {};
public readonly factories: ViewBehaviorFactory[] = [];
constructor(
public readonly fragment: DocumentFragment,
public readonly directives: Record<string, ViewBehaviorFactory>
) {}
public addFactory(
factory: ViewBehaviorFactory,
parentId: string,
nodeId: string,
targetIndex: number
): void {
if (!this.nodeIds.has(nodeId)) {
this.nodeIds.add(nodeId);
this.addTargetDescriptor(parentId, nodeId, targetIndex);
}
factory.nodeId = nodeId;
this.factories.push(factory);
}
public freeze(): TemplateCompilationResult<TSource, TParent, TContext> {
this.proto = Object.create(null, this.descriptors);
return this;
}
private addTargetDescriptor(
parentId: string,
targetId: string,
targetIndex: number
): void {
const descriptors = this.descriptors;
if (
targetId === "r" || // root
targetId === "h" || // host
descriptors[targetId]
) {
return;
}
if (!descriptors[parentId]) {
const index = parentId.lastIndexOf(".");
const grandparentId = parentId.substring(0, index);
const childIndex = parseInt(parentId.substring(index + 1));
this.addTargetDescriptor(grandparentId, parentId, childIndex);
}
let descriptor = descriptorCache[targetId];
if (!descriptor) {
const field = `_${targetId}`;
descriptorCache[targetId] = descriptor = {
get() {
return (
this[field] ??
(this[field] = this[parentId].childNodes[targetIndex])
);
},
};
}
descriptors[targetId] = descriptor;
}
public createView(hostBindingTarget?: Element): HTMLView<TSource, TParent, TContext> {
const fragment = this.fragment.cloneNode(true) as DocumentFragment;
const targets = Object.create(this.proto);
targets.r = fragment;
targets.h = hostBindingTarget ?? fragment;
for (const id of this.nodeIds) {
targets[id]; // trigger locator
}
return new HTMLView(fragment, this.factories, targets);
}
}
function compileAttributes(
context: CompilationContext,
parentId: string,
node: HTMLElement,
nodeId: string,
nodeIndex: number,
includeBasicValues: boolean = false
): void {
const attributes = node.attributes;
const directives = context.directives;
for (let i = 0, ii = attributes.length; i < ii; ++i) {
const attr = attributes[i];
const attrValue = attr.value;
const parseResult = Parser.parse(attrValue, directives);
let result: ViewBehaviorFactory | null = null;
if (parseResult === null) {
if (includeBasicValues) {
result = bind(() => attrValue, oneTime) as ViewBehaviorFactory;
Aspect.assign((result as any) as Aspected, attr.name);
}
} else {
/* eslint-disable-next-line @typescript-eslint/no-use-before-define */
result = Compiler.aggregate(parseResult);
}
if (result !== null) {
node.removeAttributeNode(attr);
i--;
ii--;
context.addFactory(result, parentId, nodeId, nodeIndex);
}
}
}
function compileContent(
context: CompilationContext,
node: Text,
parentId,
nodeId,
nodeIndex
): NextNode {
const parseResult = Parser.parse(node.textContent!, context.directives);
if (parseResult === null) {
next.node = node.nextSibling;
next.index = nodeIndex + 1;
return next;
}
let currentNode: Text;
let lastNode = (currentNode = node);
for (let i = 0, ii = parseResult.length; i < ii; ++i) {
const currentPart = parseResult[i];
if (i !== 0) {
nodeIndex++;
nodeId = targetIdFrom(parentId, nodeIndex);
currentNode = lastNode.parentNode!.insertBefore(
document.createTextNode(""),
lastNode.nextSibling
);
}
if (isString(currentPart)) {
currentNode.textContent = currentPart;
} else {
currentNode.textContent = " ";
context.addFactory(currentPart, parentId, nodeId, nodeIndex);
}
lastNode = currentNode;
}
next.index = nodeIndex + 1;
next.node = lastNode.nextSibling;
return next;
}
function compileChildren(
context: CompilationContext,
parent: Node,
parentId: string
): void {
let nodeIndex = 0;
let childNode = parent.firstChild;
while (childNode) {
/* eslint-disable-next-line @typescript-eslint/no-use-before-define */
const result = compileNode(context, parentId, childNode, nodeIndex);
childNode = result.node;
nodeIndex = result.index;
}
}
function compileNode(
context: CompilationContext,
parentId: string,
node: Node,
nodeIndex: number
): NextNode {
const nodeId = targetIdFrom(parentId, nodeIndex);
switch (node.nodeType) {
case 1: // element node
compileAttributes(context, parentId, node as HTMLElement, nodeId, nodeIndex);
compileChildren(context, node, nodeId);
break;
case 3: // text node
return compileContent(context, node as Text, parentId, nodeId, nodeIndex);
case 8: // comment
const parts = Parser.parse((node as Comment).data, context.directives);
if (parts !== null) {
context.addFactory(
/* eslint-disable-next-line @typescript-eslint/no-use-before-define */
Compiler.aggregate(parts),
parentId,
nodeId,
nodeIndex
);
}
break;
}
next.index = nodeIndex + 1;
next.node = node.nextSibling;
return next;
}
function isMarker(node: Node, directives: Record<string, ViewBehaviorFactory>): boolean {
return (
node &&
node.nodeType == 8 &&
Parser.parse((node as Comment).data, directives) !== null
);
}
/**
* A function capable of compiling a template from the preprocessed form produced
* by the html template function into a result that can instantiate views.
* @public
*/
export type CompilationStrategy = (
/**
* The preprocessed HTML string or template to compile.
*/
html: string | HTMLTemplateElement,
/**
* The behavior factories used within the html that is being compiled.
*/
factories: Record<string, ViewBehaviorFactory>
) => TemplateCompilationResult;
const templateTag = "TEMPLATE";
const policyOptions: TrustedTypesPolicy = { createHTML: html => html };
let htmlPolicy: TrustedTypesPolicy = globalThis.trustedTypes
? globalThis.trustedTypes.createPolicy("fast-html", policyOptions)
: policyOptions;
const fastHTMLPolicy = htmlPolicy;
/**
* Common APIs related to compilation.
* @public
*/
export const Compiler = {
/**
* Sets the HTML trusted types policy used by the compiler.
* @param policy - The policy to set for HTML.
* @remarks
* This API can only be called once, for security reasons. It should be
* called by the application developer at the start of their program.
*/
setHTMLPolicy(policy: TrustedTypesPolicy) {
if (htmlPolicy !== fastHTMLPolicy) {
throw FAST.error(Message.onlySetHTMLPolicyOnce);
}
htmlPolicy = policy;
},
/**
* Compiles a template and associated directives into a compilation
* result which can be used to create views.
* @param html - The html string or template element to compile.
* @param directives - The directives referenced by the template.
* @remarks
* The template that is provided for compilation is altered in-place
* and cannot be compiled again. If the original template must be preserved,
* it is recommended that you clone the original and pass the clone to this API.
* @public
*/
compile<
TSource = any,
TParent = any,
TContext extends ExecutionContext<TParent> = ExecutionContext<TParent>
>(
html: string | HTMLTemplateElement,
directives: Record<string, ViewBehaviorFactory>
): TemplateCompilationResult<TSource, TParent, TContext> {
let template: HTMLTemplateElement;
if (isString(html)) {
template = document.createElement(templateTag) as HTMLTemplateElement;
template.innerHTML = htmlPolicy.createHTML(html);
const fec = template.content.firstElementChild;
if (fec !== null && fec.tagName === templateTag) {
template = fec as HTMLTemplateElement;
}
} else {
template = html;
}
// https://bugs.chromium.org/p/chromium/issues/detail?id=1111864
const fragment = document.adoptNode(template.content);
const context = new CompilationContext<TSource, TParent, TContext>(
fragment,
directives
);
compileAttributes(context, "", template, /* host */ "h", 0, true);
if (
// If the first node in a fragment is a marker, that means it's an unstable first node,
// because something like a when, repeat, etc. could add nodes before the marker.
// To mitigate this, we insert a stable first node. However, if we insert a node,
// that will alter the result of the TreeWalker. So, we also need to offset the target index.
isMarker(fragment.firstChild!, directives) ||
// Or if there is only one node and a directive, it means the template's content
// is *only* the directive. In that case, HTMLView.dispose() misses any nodes inserted by
// the directive. Inserting a new node ensures proper disposal of nodes added by the directive.
(fragment.childNodes.length === 1 && Object.keys(directives).length > 0)
) {
fragment.insertBefore(document.createComment(""), fragment.firstChild);
}
compileChildren(context, fragment, /* root */ "r");
next.node = null; // prevent leaks
return context.freeze();
},
/**
* Sets the default compilation strategy that will be used by the ViewTemplate whenever
* it needs to compile a view preprocessed with the html template function.
* @param strategy - The compilation strategy to use when compiling templates.
*/
setDefaultStrategy(strategy: CompilationStrategy): void {
this.compile = strategy;
},
/**
* Aggregates an array of strings and directives into a single directive.
* @param parts - A heterogeneous array of static strings interspersed with
* directives.
* @returns A single inline directive that aggregates the behavior of all the parts.
*/
aggregate(parts: (string | ViewBehaviorFactory)[]): ViewBehaviorFactory {
if (parts.length === 1) {
return parts[0] as ViewBehaviorFactory;
}
let sourceAspect: string | undefined;
const partCount = parts.length;
const finalParts = parts.map((x: string | ViewBehaviorFactory) => {
if (isString(x)) {
return (): string => x;
}
sourceAspect = ((x as any) as Aspected).sourceAspect || sourceAspect;
return ((x as any) as Aspected).binding!;
});
const binding = (scope: unknown, context: ExecutionContext): string => {
let output = "";
for (let i = 0; i < partCount; ++i) {
output += finalParts[i](scope, context);
}
return output;
};
const directive = bind(binding) as HTMLBindingDirective;
Aspect.assign(directive, sourceAspect!);
return directive;
},
}; | the_stack |
import { injectable } from 'inversify';
import * as ts from 'typescript';
import { DependencyResolver, DependencyResolverFactory, DependencyResolverHost } from './dependency-resolver';
import { resolveCachedResult, djb2, unixifyPath, emptyArray } from '../utils';
import bind from 'bind-decorator';
import { ContentId, ContentIdHost, Finding, StatePersistence, StaticProgramState } from '@fimbul/ymir';
import debug = require('debug');
import { isCompilerOptionEnabled } from 'tsutils';
import * as path from 'path';
const log = debug('wotan:programState');
export interface ProgramState {
update(program: ts.Program, updatedFile: string): void;
getUpToDateResult(fileName: string, configHash: string): readonly Finding[] | undefined;
setFileResult(fileName: string, configHash: string, result: readonly Finding[]): void;
save(): void;
}
@injectable()
export class ProgramStateFactory {
constructor(
private resolverFactory: DependencyResolverFactory,
private statePersistence: StatePersistence,
private contentId: ContentId,
) {}
public create(program: ts.Program, host: ProgramStateHost & DependencyResolverHost, tsconfigPath: string) {
return new ProgramStateImpl(
host,
program,
this.resolverFactory.create(host, program),
this.statePersistence,
this.contentId,
tsconfigPath,
);
}
}
export type ProgramStateHost = Pick<ts.CompilerHost, 'useCaseSensitiveFileNames'>;
interface FileResults {
readonly config: string;
readonly result: ReadonlyArray<Finding>;
}
const enum DependencyState {
Unknown = 0,
Outdated = 1,
Ok = 2,
}
const STATE_VERSION = 1;
const oldStateSymbol = Symbol('oldState');
class ProgramStateImpl implements ProgramState {
private projectDirectory = unixifyPath(path.dirname(this.project));
private caseSensitive = this.host.useCaseSensitiveFileNames();
private canonicalProjectDirectory = this.caseSensitive ? this.projectDirectory : this.projectDirectory.toLowerCase();
private optionsHash = computeCompilerOptionsHash(this.program.getCompilerOptions(), this.projectDirectory);
private assumeChangesOnlyAffectDirectDependencies =
isCompilerOptionEnabled(this.program.getCompilerOptions(), 'assumeChangesOnlyAffectDirectDependencies');
private contentIds = new Map<string, string>();
private fileResults = new Map<string, FileResults>();
private relativePathNames = new Map<string, string>();
private [oldStateSymbol]: StaticProgramState | undefined;
private recheckOldState = true;
private dependenciesUpToDate: Uint8Array;
// TODO this can be removed once ProjectHost correctly reflects applied fixed in readFile
private contentIdHost: ContentIdHost = {
readFile: (f) => this.program.getSourceFile(f)?.text,
};
constructor(
private host: ProgramStateHost,
private program: ts.Program,
private resolver: DependencyResolver,
private statePersistence: StatePersistence,
private contentId: ContentId,
private project: string,
) {
const oldState = this.statePersistence.loadState(project);
if (oldState?.v !== STATE_VERSION || oldState.ts !== ts.version || oldState.options !== this.optionsHash) {
this[oldStateSymbol] = undefined;
this.dependenciesUpToDate = new Uint8Array(0);
} else {
this[oldStateSymbol] = this.remapFileNames(oldState);
this.dependenciesUpToDate = new Uint8Array(oldState.files.length);
}
}
/** get old state if global files didn't change */
private tryReuseOldState() {
const oldState = this[oldStateSymbol];
if (oldState === undefined || !this.recheckOldState)
return oldState;
const filesAffectingGlobalScope = this.resolver.getFilesAffectingGlobalScope();
if (oldState.global.length !== filesAffectingGlobalScope.length)
return this[oldStateSymbol] = undefined;
const globalFilesWithId = this.sortById(filesAffectingGlobalScope);
for (let i = 0; i < globalFilesWithId.length; ++i) {
const index = oldState.global[i];
if (
globalFilesWithId[i].id !== oldState.files[index].id ||
!this.assumeChangesOnlyAffectDirectDependencies &&
!this.fileDependenciesUpToDate(globalFilesWithId[i].fileName, index, oldState)
)
return this[oldStateSymbol] = undefined;
}
this.recheckOldState = false;
return oldState;
}
public update(program: ts.Program, updatedFile: string) {
this.program = program;
this.resolver.update(program, updatedFile);
this.contentIds.delete(updatedFile);
this.recheckOldState = true;
this.dependenciesUpToDate.fill(DependencyState.Unknown);
}
private getContentId(file: string) {
return resolveCachedResult(this.contentIds, file, this.computeContentId);
}
@bind
private computeContentId(file: string) {
return this.contentId.forFile(file, this.contentIdHost);
}
private getRelativePath(fileName: string) {
return resolveCachedResult(this.relativePathNames, fileName, this.makeRelativePath);
}
@bind
private makeRelativePath(fileName: string) {
return unixifyPath(path.relative(this.canonicalProjectDirectory, this.caseSensitive ? fileName : fileName.toLowerCase()));
}
public getUpToDateResult(fileName: string, configHash: string) {
const oldState = this.tryReuseOldState();
if (oldState === undefined)
return;
const index = this.lookupFileIndex(fileName, oldState);
if (index === undefined)
return;
const old = oldState.files[index];
if (
old.result === undefined ||
old.config !== configHash ||
old.id !== this.getContentId(fileName) ||
!this.fileDependenciesUpToDate(fileName, index, oldState)
)
return;
log('reusing state for %s', fileName);
return old.result;
}
public setFileResult(fileName: string, configHash: string, result: ReadonlyArray<Finding>) {
if (!this.isFileUpToDate(fileName)) {
log('File %s is outdated, merging current state into old state', fileName);
// we need to create a state where the file is up-to-date
// so we replace the old state with the current state
// this includes all results from old state that are still up-to-date and all file results if they are still valid
const newState = this[oldStateSymbol] = this.aggregate();
this.recheckOldState = false;
this.fileResults = new Map();
this.dependenciesUpToDate = new Uint8Array(newState.files.length).fill(DependencyState.Ok);
}
this.fileResults.set(fileName, {result, config: configHash});
}
private isFileUpToDate(fileName: string): boolean {
const oldState = this.tryReuseOldState();
if (oldState === undefined)
return false;
const index = this.lookupFileIndex(fileName, oldState);
if (index === undefined || oldState.files[index].id !== this.getContentId(fileName))
return false;
switch (<DependencyState>this.dependenciesUpToDate[index]) {
case DependencyState.Unknown:
return this.fileDependenciesUpToDate(fileName, index, oldState);
case DependencyState.Ok:
return true;
case DependencyState.Outdated:
return false;
}
}
private fileDependenciesUpToDate(fileName: string, index: number, oldState: StaticProgramState): boolean {
// File names that are waiting to be processed, each iteration of the loop processes one file
const fileNameQueue = [fileName];
// For each entry in `fileNameQueue` this holds the index of that file in `oldState.files`
const indexQueue = [index];
// If a file is waiting for its children to be processed, it is moved from `indexQueue` to `parents`
const parents: number[] = [];
// For each entry in `parents` this holds the number of children that still need to be processed for that file
const childCounts = [];
// For each entry in `parents` this holds the index in of the earliest circular dependency in `parents`.
// For example, a value of `[Number.MAX_SAFE_INTEGER, 0]` means that `parents[1]` has a dependency on `parents[0]` (the root file).
const circularDependenciesQueue: number[] = [];
// If a file has a circular on one of its parents, it is moved from `indexQueue` to the current cycle
// or creates a new cycle if its parent is not already in a cycle.
const cycles: Array<Set<number>> = [];
while (true) {
index = indexQueue.pop()!;
fileName = fileNameQueue.pop()!;
processFile: {
switch (<DependencyState>this.dependenciesUpToDate[index]) {
case DependencyState.Outdated:
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
case DependencyState.Ok:
break processFile;
}
for (const cycle of cycles) {
if (cycle.has(index)) {
// we already know this is a circular dependency, skip this one and simply mark the parent as circular
setCircularDependency(
parents,
circularDependenciesQueue,
index,
cycles,
findCircularDependencyOfCycle(parents, circularDependenciesQueue, cycle),
);
break processFile;
}
}
let earliestCircularDependency = Number.MAX_SAFE_INTEGER;
let childCount = 0;
const old = oldState.files[index];
const dependencies = this.resolver.getDependencies(fileName);
const keys = old.dependencies === undefined ? emptyArray : Object.keys(old.dependencies);
if (dependencies.size !== keys.length)
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
for (const key of keys) {
let newDeps = dependencies.get(key);
const oldDeps = old.dependencies![key];
if (oldDeps === null) {
if (newDeps !== null)
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
continue;
}
if (newDeps === null)
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
newDeps = Array.from(new Set(newDeps));
if (newDeps.length !== oldDeps.length)
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
const newDepsWithId = this.sortById(newDeps);
for (let i = 0; i < newDepsWithId.length; ++i) {
const oldDepState = oldState.files[oldDeps[i]];
if (newDepsWithId[i].id !== oldDepState.id)
return markAsOutdated(parents, index, cycles, this.dependenciesUpToDate);
if (!this.assumeChangesOnlyAffectDirectDependencies && fileName !== newDepsWithId[i].fileName) {
const indexInQueue = parents.indexOf(oldDeps[i]);
if (indexInQueue === -1) {
// no circular dependency
fileNameQueue.push(newDepsWithId[i].fileName);
indexQueue.push(oldDeps[i]);
++childCount;
} else if (indexInQueue < earliestCircularDependency) {
earliestCircularDependency = indexInQueue;
}
}
}
}
if (earliestCircularDependency !== Number.MAX_SAFE_INTEGER) {
earliestCircularDependency =
setCircularDependency(parents, circularDependenciesQueue, index, cycles, earliestCircularDependency);
} else if (childCount === 0) {
this.dependenciesUpToDate[index] = DependencyState.Ok;
}
if (childCount !== 0) {
parents.push(index);
childCounts.push(childCount);
circularDependenciesQueue.push(earliestCircularDependency);
continue;
}
}
// we only get here for files with no children to process
if (parents.length === 0)
return true; // only happens if the initial file has no dependencies or they are all already known as Ok
while (--childCounts[childCounts.length - 1] === 0) {
index = parents.pop()!;
childCounts.pop();
const earliestCircularDependency = circularDependenciesQueue.pop()!;
if (earliestCircularDependency >= parents.length) {
this.dependenciesUpToDate[index] = DependencyState.Ok;
if (earliestCircularDependency !== Number.MAX_SAFE_INTEGER)
for (const dep of cycles.pop()!) // cycle ends here
// update result for files that had a circular dependency on this one
this.dependenciesUpToDate[dep] = DependencyState.Ok;
}
if (parents.length === 0)
return true;
}
}
}
public save() {
if (this.fileResults.size === 0)
return; // nothing to save
const oldState = this[oldStateSymbol];
if (oldState !== undefined && this.dependenciesUpToDate.every((v) => v === DependencyState.Ok)) {
// state is still good, only update results
const files = oldState.files.slice();
for (const [fileName, result] of this.fileResults) {
const index = this.lookupFileIndex(fileName, oldState)!;
files[index] = {...files[index], ...result};
}
this.statePersistence.saveState(this.project, {
...oldState,
files,
});
} else {
this.statePersistence.saveState(this.project, this.aggregate());
}
}
private aggregate(): StaticProgramState {
const additionalFiles = new Set<string>();
const oldState = this.tryReuseOldState();
const sourceFiles = this.program.getSourceFiles();
const lookup: Record<string, number> = {};
const mapToIndex = ({fileName}: {fileName: string}) => {
const relativeName = this.getRelativePath(fileName);
let index = lookup[relativeName];
if (index === undefined) {
index = sourceFiles.length + additionalFiles.size;
additionalFiles.add(fileName);
lookup[relativeName] = index;
}
return index;
};
const mapDependencies = (dependencies: ReadonlyMap<string, null | readonly string[]>) => {
if (dependencies.size === 0)
return;
const result: Record<string, null | number[]> = {};
for (const [key, f] of dependencies)
result[key] = f === null
? null
: this.sortById(Array.from(new Set(f))).map(mapToIndex);
return result;
};
const files: StaticProgramState.FileState[] = [];
for (let i = 0; i < sourceFiles.length; ++i)
lookup[this.getRelativePath(sourceFiles[i].fileName)] = i;
for (const file of sourceFiles) {
let results = this.fileResults.get(file.fileName);
if (results === undefined && oldState !== undefined) {
const index = this.lookupFileIndex(file.fileName, oldState);
if (index !== undefined) {
const old = oldState.files[index];
if (old.result !== undefined)
results = <FileResults>old;
}
}
if (results !== undefined && !this.isFileUpToDate(file.fileName)) {
log('Discarding outdated results for %s', file.fileName);
results = undefined;
}
files.push({
...results,
id: this.getContentId(file.fileName),
dependencies: mapDependencies(this.resolver.getDependencies(file.fileName)),
});
}
for (const additional of additionalFiles)
files.push({id: this.getContentId(additional)});
return {
files,
lookup,
v: STATE_VERSION,
ts: ts.version,
cs: this.caseSensitive,
global: this.sortById(this.resolver.getFilesAffectingGlobalScope()).map(mapToIndex),
options: this.optionsHash,
};
}
private sortById(fileNames: readonly string[]) {
return fileNames
.map((f) => ({fileName: f, id: this.getContentId(f)}))
.sort(compareId);
}
private lookupFileIndex(fileName: string, oldState: StaticProgramState): number | undefined {
fileName = this.getRelativePath(fileName);
if (!oldState.cs && this.caseSensitive)
fileName = fileName.toLowerCase();
return oldState.lookup[fileName];
}
private remapFileNames(oldState: StaticProgramState): StaticProgramState {
// only need to remap if oldState is case sensitive and current host is case insensitive
if (!oldState.cs || this.caseSensitive)
return oldState;
const lookup: Record<string, number> = {};
for (const [key, value] of Object.entries(oldState.lookup))
lookup[key.toLowerCase()] = value;
return {...oldState, lookup, cs: false};
}
}
function findCircularDependencyOfCycle(parents: readonly number[], circularDependencies: readonly number[], cycle: ReadonlySet<number>) {
for (let i = 0; i < parents.length; ++i) {
const dep = circularDependencies[i];
if (dep !== Number.MAX_SAFE_INTEGER && cycle.has(parents[i]))
return dep;
}
/* istanbul ignore next */
throw new Error('should never happen');
}
function setCircularDependency(
parents: readonly number[],
circularDependencies: number[],
self: number,
cycles: Array<Set<number>>,
earliestCircularDependency: number,
) {
let cyclesToMerge = 0;
for (let i = circularDependencies.length - 1, inCycle = false; i >= earliestCircularDependency; --i) {
const dep = circularDependencies[i];
if (dep === Number.MAX_SAFE_INTEGER) {
inCycle = false;
} else {
if (!inCycle) {
++cyclesToMerge;
inCycle = true;
}
if (dep === i) {
inCycle = false; // if cycle ends here, the next parent might start a new one
} else if (dep <= earliestCircularDependency) {
earliestCircularDependency = dep;
break;
}
}
}
let targetCycle;
if (cyclesToMerge === 0) {
targetCycle = new Set<number>();
cycles.push(targetCycle);
} else {
targetCycle = cycles[cycles.length - cyclesToMerge];
while (--cyclesToMerge)
for (const d of cycles.pop()!)
targetCycle.add(d);
}
targetCycle.add(self);
for (let i = circularDependencies.length - 1; i >= earliestCircularDependency; --i) {
targetCycle.add(parents[i]);
circularDependencies[i] = earliestCircularDependency;
}
return earliestCircularDependency;
}
function markAsOutdated(parents: readonly number[], index: number, cycles: ReadonlyArray<ReadonlySet<number>>, results: Uint8Array) {
results[index] = DependencyState.Outdated;
for (index of parents)
results[index] = DependencyState.Outdated;
for (const cycle of cycles)
for (index of cycle)
results[index] = DependencyState.Outdated;
return false;
}
function compareId(a: {id: string}, b: {id: string}) {
return +(a.id >= b.id) - +(a.id <= b.id);
}
const enum CompilerOptionKind {
Ignore = 0,
Value = 1,
Path = 2,
PathArray = 3,
}
type KnownCompilerOptions = // tslint:disable-next-line:no-unused
{[K in keyof ts.CompilerOptions]: string extends K ? never : K} extends {[K in keyof ts.CompilerOptions]: infer P} ? P : never;
type AdditionalCompilerOptions = 'pathsBasePath';
const compilerOptionKinds: Record<KnownCompilerOptions | AdditionalCompilerOptions, CompilerOptionKind> = {
allowJs: CompilerOptionKind.Value,
allowSyntheticDefaultImports: CompilerOptionKind.Value,
allowUmdGlobalAccess: CompilerOptionKind.Value,
allowUnreachableCode: CompilerOptionKind.Value,
allowUnusedLabels: CompilerOptionKind.Value,
alwaysStrict: CompilerOptionKind.Value,
assumeChangesOnlyAffectDirectDependencies: CompilerOptionKind.Value,
baseUrl: CompilerOptionKind.Path,
charset: CompilerOptionKind.Value,
checkJs: CompilerOptionKind.Value,
composite: CompilerOptionKind.Value,
declaration: CompilerOptionKind.Value,
declarationDir: CompilerOptionKind.Path,
declarationMap: CompilerOptionKind.Value,
disableReferencedProjectLoad: CompilerOptionKind.Ignore,
disableSizeLimit: CompilerOptionKind.Value,
disableSourceOfProjectReferenceRedirect: CompilerOptionKind.Value,
disableSolutionSearching: CompilerOptionKind.Ignore,
downlevelIteration: CompilerOptionKind.Value,
emitBOM: CompilerOptionKind.Value,
emitDeclarationOnly: CompilerOptionKind.Value,
emitDecoratorMetadata: CompilerOptionKind.Value,
esModuleInterop: CompilerOptionKind.Value,
experimentalDecorators: CompilerOptionKind.Value,
forceConsistentCasingInFileNames: CompilerOptionKind.Value,
importHelpers: CompilerOptionKind.Value,
importsNotUsedAsValues: CompilerOptionKind.Value,
incremental: CompilerOptionKind.Value,
inlineSourceMap: CompilerOptionKind.Value,
inlineSources: CompilerOptionKind.Value,
isolatedModules: CompilerOptionKind.Value,
jsx: CompilerOptionKind.Value,
jsxFactory: CompilerOptionKind.Value,
jsxFragmentFactory: CompilerOptionKind.Value,
jsxImportSource: CompilerOptionKind.Value,
keyofStringsOnly: CompilerOptionKind.Value,
lib: CompilerOptionKind.Value,
locale: CompilerOptionKind.Value,
mapRoot: CompilerOptionKind.Value,
maxNodeModuleJsDepth: CompilerOptionKind.Value,
module: CompilerOptionKind.Value,
moduleResolution: CompilerOptionKind.Value,
newLine: CompilerOptionKind.Value,
noEmit: CompilerOptionKind.Value,
noEmitHelpers: CompilerOptionKind.Value,
noEmitOnError: CompilerOptionKind.Value,
noErrorTruncation: CompilerOptionKind.Value,
noFallthroughCasesInSwitch: CompilerOptionKind.Value,
noImplicitAny: CompilerOptionKind.Value,
noImplicitReturns: CompilerOptionKind.Value,
noImplicitThis: CompilerOptionKind.Value,
noImplicitUseStrict: CompilerOptionKind.Value,
noLib: CompilerOptionKind.Value,
noPropertyAccessFromIndexSignature: CompilerOptionKind.Value,
noResolve: CompilerOptionKind.Value,
noStrictGenericChecks: CompilerOptionKind.Value,
noUncheckedIndexedAccess: CompilerOptionKind.Value,
noUnusedLocals: CompilerOptionKind.Value,
noUnusedParameters: CompilerOptionKind.Value,
out: CompilerOptionKind.Value,
outDir: CompilerOptionKind.Path,
outFile: CompilerOptionKind.Path,
paths: CompilerOptionKind.Value,
pathsBasePath: CompilerOptionKind.Path,
preserveConstEnums: CompilerOptionKind.Value,
preserveSymlinks: CompilerOptionKind.Value,
project: CompilerOptionKind.Ignore,
reactNamespace: CompilerOptionKind.Value,
removeComments: CompilerOptionKind.Value,
resolveJsonModule: CompilerOptionKind.Value,
rootDir: CompilerOptionKind.Path,
rootDirs: CompilerOptionKind.PathArray,
skipDefaultLibCheck: CompilerOptionKind.Value,
skipLibCheck: CompilerOptionKind.Value,
sourceMap: CompilerOptionKind.Value,
sourceRoot: CompilerOptionKind.Value,
strict: CompilerOptionKind.Value,
strictBindCallApply: CompilerOptionKind.Value,
strictFunctionTypes: CompilerOptionKind.Value,
strictNullChecks: CompilerOptionKind.Value,
strictPropertyInitialization: CompilerOptionKind.Value,
stripInternal: CompilerOptionKind.Value,
suppressExcessPropertyErrors: CompilerOptionKind.Value,
suppressImplicitAnyIndexErrors: CompilerOptionKind.Value,
target: CompilerOptionKind.Value,
traceResolution: CompilerOptionKind.Value,
tsBuildInfoFile: CompilerOptionKind.Ignore,
typeRoots: CompilerOptionKind.PathArray,
types: CompilerOptionKind.Value,
useDefineForClassFields: CompilerOptionKind.Value,
};
function computeCompilerOptionsHash(options: ts.CompilerOptions, relativeTo: string) {
const obj: Record<string, unknown> = {};
for (const key of Object.keys(options).sort()) {
switch (compilerOptionKinds[<KnownCompilerOptions>key]) {
case CompilerOptionKind.Value:
obj[key] = options[key];
break;
case CompilerOptionKind.Path:
obj[key] = makeRelativePath(<string>options[key]);
break;
case CompilerOptionKind.PathArray:
obj[key] = (<string[]>options[key]).map(makeRelativePath);
}
}
return '' + djb2(JSON.stringify(obj));
function makeRelativePath(p: string) {
return unixifyPath(path.relative(relativeTo, p));
}
} | the_stack |
import { Transform } from './transform';
import { ViewBasedJSONModel } from './viewbasedjsonmodel';
import { DataGrid } from '@lumino/datagrid';
import { DataModel } from '@lumino/datagrid';
import { Signal, ISignal } from '@lumino/signaling';
import { ElementExt } from '@lumino/domutils';
import { Message, MessageLoop, ConflatableMessage } from '@lumino/messaging';
import { BasicMouseHandler } from '@lumino/datagrid';
import { Widget, BoxPanel } from '@lumino/widgets';
import { VirtualDOM, VirtualElement, h } from '@lumino/virtualdom';
import { FilterValueRenderer } from './valueRenderer';
import { Theme } from '../utils';
/**
* An interactive widget to add filter transformations to the data model.
*/
export class InteractiveFilterDialog extends BoxPanel {
/**
* Construct a new InteractiveFilterDialog.
*
* @param options - The options for initializing the InteractiveFilterDialog.
*/
constructor(options: InteractiveFilterDialog.IOptions) {
super();
// Set CSS
this.addClass('ipydatagrid-filterMenu');
this.node.style.position = 'absolute';
this._model = options.model;
// Widget to display condition operators
this._filterByConditionWidget = new Widget();
this._filterByConditionWidget.addClass(
'ipydatagrid-filter-condition-select',
);
// Grid to display unique values
this._uniqueValueGrid = new DataGrid({
headerVisibility: 'none',
stretchLastColumn: true,
});
this._uniqueValueGrid.addClass('ipydatagrid-unique-value-grid');
// State management for unique value grid
this._uniqueValueStateManager = new UniqueValueStateManager({
grid: this._uniqueValueGrid,
});
const mouseHandler = new UniqueValueGridMouseHandler({
stateManager: this._uniqueValueStateManager,
dialog: this,
});
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
this._uniqueValueGrid.mouseHandler = mouseHandler;
// Widget to display the dialog title
this._titleWidget = new Widget();
this._titleWidget.addClass('ipydatagrid-filter-title');
// Widget to display "apply" button.
this._applyWidget = new Widget();
this._applyWidget.addClass('ipydatagrid-filter-apply');
// Widget for the text search input box in the
// filter-by-value dialog box
this._textInputWidget = new TextInputWidget();
// Create the "Select All" widget and connecting to
// lumino signal
this._selectAllCheckbox = new SelectCanvasWidget();
this._connectToCheckbox();
// Add all widgets to the dock
this.addWidget(this._titleWidget);
this.addWidget(this._textInputWidget);
this.addWidget(this._selectAllCheckbox);
this.addWidget(this._filterByConditionWidget);
this.addWidget(this._uniqueValueGrid);
this.addWidget(this._applyWidget);
}
/**
* Connects to the "Select All" widget signal and
* toggles checking all/none of the unique elements
* by adding/removing them from the state object
*/
private _connectToCheckbox() {
this._selectAllCheckbox.checkChanged.connect(
(sender: SelectCanvasWidget, checked: boolean) => {
this.userInteractedWithDialog = true;
// Adding all unique values to the state **IF** the select
// all box is "checked"
this.addRemoveAllUniqueValuesToState(checked);
},
);
}
/**
* Checks for any undefined values in `this._filterValue`.
*
* Note: This should be expanded in the future to also check for dtype
* inappropriate values.
*/
hasValidFilterValue(): boolean {
if (this._filterValue === '' || this._filterValue === undefined) {
return false;
} else if (Array.isArray(this._filterValue)) {
if (
this._filterValue[0] === '' ||
this._filterValue[0] === undefined ||
this._filterValue[1] === '' ||
this._filterValue[1] === undefined
) {
return false;
}
}
return true;
}
/**
* Applies the active transformation to the linked data model.
*/
applyFilter(): void {
// Bail if no value has been entered
// TODO: Create some kind of visual error state to indicate the blank field
// that needs a value.
if (!this.hasValidFilterValue) {
return;
}
if (
!this.hasFilter &&
!this.userInteractedWithDialog &&
this._mode === 'value'
) {
this.close();
return;
}
const value =
this._mode === 'condition'
? <Transform.FilterValue>this._filterValue
: this._uniqueValueStateManager.getValues(
this.region,
this._columnIndex,
);
// Construct transform
const transform: Transform.TransformSpec = {
type: 'filter',
columnIndex: this.model.getSchemaIndex(this._region, this._columnIndex),
operator: this._filterOperator,
value: value,
};
this._model.addTransform(transform);
this.close();
}
/**
* Updates the DOM elements with transform state from the linked data model.
*/
updateDialog(): void {
const lookupColumn = this.model.getSchemaIndex(
this._region,
this._columnIndex,
);
const columnState = this._model.transformMetadata(lookupColumn);
// Update state with transform metadata, if present
if (columnState && columnState.filter) {
this._filterOperator = columnState.filter.operator;
this._filterValue = columnState.filter.value;
} else {
this._filterOperator = '<';
this._filterValue = undefined;
}
// Override filter operator if in "Filter by value" mode.
if (this._mode === 'value') {
this._filterOperator = 'in';
}
// Render virtual DOM
this._render();
}
/**
* Renders the widget with VirtualDOM.
*/
private _render(): void {
if (this._mode === 'condition') {
this._applyWidget.node.style.minHeight = '65px';
this._selectAllCheckbox.setHidden(true);
this._uniqueValueGrid.setHidden(true);
this._textInputWidget.setHidden(true);
this._filterByConditionWidget.setHidden(false);
// selector
VirtualDOM.render(
[this.createOperatorList()],
this._filterByConditionWidget.node,
);
// title
VirtualDOM.render([this.createTitleNode()], this._titleWidget.node);
// apply buttons
VirtualDOM.render(
[
this._filterOperator === 'between'
? this.createDualValueNode()
: this.createSingleValueNode(),
],
this._applyWidget.node,
);
} else if (this._mode === 'value') {
this._applyWidget.node.style.minHeight = '30px';
this._selectAllCheckbox.setHidden(false);
this._uniqueValueGrid.setHidden(false);
this._textInputWidget.setHidden(false);
this._filterByConditionWidget.setHidden(true);
// title
VirtualDOM.render([this.createTitleNode()], this._titleWidget.node);
// text search box
VirtualDOM.render(
[this.createTextInputDialog()],
this._textInputWidget.node,
);
// apply buttons
VirtualDOM.render([this.createApplyButtonNode()], this._applyWidget.node);
this._renderUniqueVals();
} else {
throw 'unreachable';
}
}
/**
* Displays the unique values of a column.
*/
async _renderUniqueVals() {
const uniqueVals = this._model.uniqueValues(
this._region,
this._columnIndex,
);
uniqueVals.then((value) => {
const items = value.map((val, i) => {
return { index: i, uniqueVals: val };
});
const data: ViewBasedJSONModel.IData = {
schema: {
fields: [
{ name: 'index', type: 'integer', rows: [] },
{ name: 'uniqueVals', type: 'number', rows: [] },
],
primaryKey: ['index'],
primaryKeyUuid: 'index',
},
data: items,
};
this._uniqueValueGrid.dataModel = new ViewBasedJSONModel(data);
const sortTransform: Transform.Sort = {
type: 'sort',
columnIndex: this.model.getSchemaIndex(this._region, 0),
desc: false,
};
// Sort items in filter-by-value menu in ascending order
(<ViewBasedJSONModel>this._uniqueValueGrid.dataModel).addTransform(
sortTransform,
);
});
}
/**
* Checks whether all unique elements in the column
* are present as "selected" in the state. This
* function is used to determine whether the
* "Select all" button should be ticked when
* opening the filter by value menu.
*/
updateSelectAllCheckboxState() {
if (!this.userInteractedWithDialog && !this.hasFilter) {
this._selectAllCheckbox.checked = true;
return;
}
const uniqueVals = this._model.uniqueValues(
this._region,
this._columnIndex,
);
uniqueVals.then((values) => {
let showAsChecked = true;
for (const value of values) {
// If there is a unique value which is not present in the state then it is
// not ticked, and therefore we should not tick the "Select all" checkbox.
if (
!this._uniqueValueStateManager.has(
this._region,
this._columnIndex,
value,
)
) {
showAsChecked = false;
break;
}
}
this._selectAllCheckbox.checked = showAsChecked;
});
}
/**
* Open the menu at the specified location.
*
* @param options - The additional options for opening the menu.
*/
open(options: InteractiveFilterDialog.IOpenOptions): void {
// Update state with the metadata of the event that opened the menu.
this._columnIndex = options.columnIndex;
this._columnDType = this._model.metadata(
options.region,
0,
options.columnIndex,
)['type'];
this._region = options.region;
this._mode = options.mode;
// Setting filter flag
this.hasFilter =
this._model.getFilterTransform(
this.model.getSchemaIndex(this._region, this._columnIndex),
) !== undefined;
this.userInteractedWithDialog = false;
// Determines whether we should or not tick the "Select all" chekcbox
this.updateSelectAllCheckboxState();
// Update styling on unique value grid
this._uniqueValueGrid.style = {
voidColor: Theme.getBackgroundColor(),
backgroundColor: Theme.getBackgroundColor(),
gridLineColor: Theme.getBackgroundColor(),
headerGridLineColor: Theme.getBorderColor(1),
selectionFillColor: Theme.getBrandColor(2, 0.4),
selectionBorderColor: Theme.getBrandColor(1),
headerSelectionFillColor: Theme.getBackgroundColor(3, 0.4),
headerSelectionBorderColor: Theme.getBorderColor(1),
cursorFillColor: Theme.getBrandColor(3, 0.4),
cursorBorderColor: Theme.getBrandColor(1),
};
this._uniqueValueGrid.cellRenderers.update({
body: new FilterValueRenderer({
stateManager: this._uniqueValueStateManager,
dialog: this,
textColor: Theme.getFontColor(),
backgroundColor: Theme.getBackgroundColor(),
}),
});
// Update DOM elements and render virtual DOM
this.updateDialog();
// Get the current position and size of the main viewport.
const px = window.pageXOffset;
const py = window.pageYOffset;
const cw = document.documentElement.clientWidth;
const ch = document.documentElement.clientHeight;
// Compute the maximum allowed height for the menu.
const maxHeight = ch - (options.forceY ? options.y : 0);
// Fetch common variables.
const node = this.node;
const style = node.style;
// Clear the menu geometry and prepare it for measuring.
style.top = '';
style.left = '';
style.width = '';
style.height = '';
style.visibility = 'hidden';
style.maxHeight = `${maxHeight}px`;
// Attach the menu to the document.
Widget.attach(this, document.body);
// Measure the size of the menu.
const { width, height } = node.getBoundingClientRect();
// Adjust the X position of the menu to fit on-screen.
if (!options.forceX && options.x + width > px + cw) {
options.x = px + cw - width;
}
// Adjust the Y position of the menu to fit on-screen.
if (!options.forceY && options.y + height > py + ch) {
if (options.y > py + ch) {
options.y = py + ch - height;
} else {
options.y = options.y - height;
}
}
// Update the position of the menu to the computed position.
style.top = `${Math.max(0, options.y)}px`;
style.left = `${Math.max(0, options.x)}px`;
// Finally, make the menu visible on the screen.
style.visibility = '';
}
/**
* Handle the DOM events for the filter dialog.
*
* @param event - The DOM event sent to the panel.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the panel's DOM node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'mousedown':
this._evtMouseDown(event as MouseEvent);
break;
case 'keydown':
this._evtKeyDown(event as KeyboardEvent);
break;
}
}
/**
* Handle the `'mousedown'` event for the menu.
*
* #### Notes
* This listener is attached to the document node.
*/
protected _evtMouseDown(event: MouseEvent) {
// Close the menu if a click is detected anywhere else
if (!ElementExt.hitTest(this.node, event.clientX, event.clientY)) {
this.close();
}
}
/**
* Handle the `'keydown'` event for the menu.
*
* #### Notes
* This listener is attached to the menu node.
*/
protected _evtKeyDown(event: KeyboardEvent): void {
event.stopPropagation();
switch (event.keyCode) {
// Enter
case 13:
this.applyFilter();
return;
// Escape
case 27:
this.close();
return;
}
}
/**
* A message handler invoked on a `'before-attach'` message.
*/
protected onBeforeAttach(msg: Message): void {
document.addEventListener('mousedown', this, true);
document.addEventListener('keydown', this, true);
}
/**
* A message handler invoked on an `'after-detach'` message.
*/
protected onAfterDetach(msg: Message): void {
document.removeEventListener('mousedown', this, true);
document.removeEventListener('keydown', this, true);
}
/**
* Creates the input dialog box for the filter-by-value
* menu.
*/
createTextInputDialog(): VirtualElement {
return h.div(
{
className: 'ipydatagrid-text-input-filter',
},
h.input({
type: 'text',
style: {
marginRight: '5px',
width: '200px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
},
// Assigning a random key ensures that this
// element is always rerendered.
key: String(Math.random()),
oninput: (evt) => {
const elem = <HTMLInputElement>evt.srcElement;
const dataModel = this._uniqueValueGrid
.dataModel as ViewBasedJSONModel;
// Empty input - remove all transforms and terminate.
if (elem.value === '') {
dataModel.clearTransforms();
this._textInputFilterValue = undefined;
this._selectAllCheckbox.setHidden(false);
return;
}
this._textInputFilterValue = elem.value;
const value = <Transform.FilterValue>this._textInputFilterValue;
const transform: Transform.TransformSpec = {
type: 'filter',
// This is a separate data grid for the dialog box
// which will always have two columns.
columnIndex: 1,
operator: 'stringContains',
value: value,
};
// Disabling "select all" toggle when
// filtering with text input.
this._selectAllCheckbox.setHidden(true);
// Removing any previously assigned transforms so we do
// not accumulate transforms with each key stroke.
dataModel.clearTransforms();
dataModel.addTransform(transform);
},
}),
);
}
/**
* Creates a `VirtualElement` to display the menu title.
*/
createTitleNode(): VirtualElement {
return h.div(
{
className: '',
style: {
paddingLeft: '5px',
color: 'var(--ipydatagrid-filter-dlg-textcolor,black)',
},
},
this._mode === 'condition' ? 'Filter by condition:' : 'Filter by value:',
);
}
/**
* Creates a `VirtualElement` to display an input element with "apply" button.
*
* Note: The `key` is randomly assigned to ensure that this element is always
* rerendered with current state. User interaction with `input` elements
* can cause attribute changes that are not recognized by VirtualDOM.
*/
createSingleValueNode(): VirtualElement {
return h.div(
{
className: 'widget-text',
style: { paddingLeft: '5px', minHeight: '60px' },
},
h.input({
type: 'text',
style: {
marginRight: '5px',
width: '200px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
visibility:
this._filterOperator === 'empty' ||
this._filterOperator === 'notempty' ||
this._mode === 'value'
? 'hidden'
: 'visible',
},
// Assigning a random key ensures that this element is always
// rerendered
key: String(Math.random()),
oninput: (evt) => {
const elem = <HTMLInputElement>evt.srcElement;
this._filterValue =
this._columnDType === 'number' || this._columnDType === 'integer'
? Number(elem.value)
: elem.value;
},
value:
this._filterValue !== undefined && !Array.isArray(this._filterValue)
? String(this._filterValue)
: '',
}),
h.div(
{
className: '',
style: {
width: '202px',
textAlign: 'right',
paddingTop: '5px',
},
},
h.button(
{
className: 'jupyter-widgets jupyter-button widget-button',
style: {
width: '60px',
padding: '1px',
border: '1px solid var(--ipydatagrid-menu-border-color, #bdbdbd)',
},
onclick: this.applyFilter.bind(this),
},
'Apply',
),
),
);
}
/**
* Creates a `VirtualElement` to display an input element with "apply" button.
*
* Note: The `key` is randomly assigned to ensure that this element is always
* rerendered with current state. User interaction with `input` elements
* can cause attribute changes that are not recognized by VirtualDOM.
*/
createDualValueNode(): VirtualElement {
const value = <any[]>this._filterValue;
return h.div(
{
className: 'widget-text',
style: {
paddingLeft: '5px',
color: 'var(--ipydatagrid-filter-dlg-textcolor,black)',
},
},
h.input({
style: {
marginRight: '5px',
width: '75px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
},
// Assigning a random key ensures that this element is always
// rerendered
key: String(Math.random()),
type: 'text',
oninput: (evt) => {
const elem = <HTMLInputElement>evt.srcElement;
this._filterValue = [
this._columnDType === 'number' || this._columnDType === 'integer'
? Number(elem.value)
: elem.value,
(<any[]>this._filterValue)[1],
];
},
// this._filterValue is converted to an array in
// this.createOperatorList
value: value[0] !== undefined ? String(value[0]) : '',
}),
'and ',
h.input({
style: {
marginRight: '5px',
width: '75px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
},
// Assigning a random key ensures that this element is always
// rerendered
key: String(Math.random()),
type: 'text',
oninput: (evt) => {
const elem = <HTMLInputElement>evt.srcElement;
this._filterValue = [
(<any[]>this._filterValue)[0],
this._columnDType === 'number' || this._columnDType === 'integer'
? Number(elem.value)
: elem.value,
];
},
// this._filterValue is converted to an array in
// this.createOperatorList
value: value[1] !== undefined ? String(value[1]) : '',
}),
h.div(
{
className: '',
style: { width: '202px', textAlign: 'right', paddingTop: '5px' },
},
h.button(
{
className: 'jupyter-widgets jupyter-button widget-button',
style: {
width: '60px',
padding: '1px',
border: '1px solid var(--ipydatagrid-menu-border-color, #bdbdbd)',
},
onclick: this.applyFilter.bind(this),
},
'Apply',
),
),
);
}
/**
* Creates a `VirtualElement` to display a "loading" message.
*/
protected createLoadingMessageNodes(): VirtualElement {
return h.div(
{
className: 'p-Menu-itemLabel widget-text',
style: { paddingLeft: '5px' },
},
'Loading unique values...',
);
}
/**
* Creates a Promise that resolves to a `VirtualElement` to display the unique
* values of a column.
*/
protected async createUniqueValueNodes(): Promise<VirtualElement> {
const uniqueVals = await this._model.uniqueValues(
this._region,
this._columnIndex,
);
const optionElems = uniqueVals.map((val) => {
return h.option({ value: val }, String(val));
});
return h.li(
{ className: 'p-Menu-item' },
h.div(
{
className: 'widget-select widget-select-multiple',
style: { width: '200px' },
},
h.select(
{
multiple: '',
value: '',
style: {
width: '200px',
height: '200px',
margin: '5px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
},
onchange: (evt) => {
const selectElem = <HTMLSelectElement>evt.srcElement;
const values = [];
for (let i = 0; i < selectElem.options.length; i++) {
if (selectElem.options[i].selected) {
values.push(
this._columnDType === 'number' ||
this._columnDType === 'integer'
? Number(selectElem.options[i].value)
: selectElem.options[i].value,
);
}
}
this._filterValue = <number[] | string[]>values;
},
},
optionElems,
),
),
);
}
/**
* Creates a `VirtualElement` to display the available filter operators.
*
* Note: The `key` is randomly assigned to ensure that this element is always
* rerendered with current state. User interaction with `input` elements
* can cause attribute changes that are not recognized by VirtualDOM.
*/
protected createOperatorList() {
let operators: VirtualElement[];
// TODO: Refactor this to a switch statement
if (this._columnDType === 'number' || this._columnDType === 'integer') {
operators = this._createNumericalOperators();
} else if (['date', 'time', 'datetime'].includes(this._columnDType)) {
operators = this._createDateOperators();
} else if (this._columnDType === 'boolean') {
operators = this._createBooleanOperators();
} else {
operators = this._createCategoricalOperators();
}
return h.div(
{ className: 'widget-dropdown', style: { paddingLeft: '5px' } },
h.select(
{
style: {
width: '200px',
fontSize: '12px',
background: 'var(--ipydatagrid-filter-dlg-bgcolor,white)',
},
// Assigning a random key ensures that this element is always
// rerendered
key: String(Math.random()),
onchange: (evt) => {
const elem = <HTMLSelectElement>evt.srcElement;
this._filterOperator = <Transform.FilterOperator>elem.value;
if (elem.value === 'between') {
this._filterValue = new Array(2);
}
// Re-render virtual DOM, in case input elements need to change.
this._render();
},
value: this._filterOperator,
},
...operators,
),
);
}
/**
* Creates a `VirtualElement` to display an "apply" button.
*/
protected createApplyButtonNode(): VirtualElement {
return h.div(
{
className: '',
style: { paddingLeft: '5px', textAlign: 'right', minHeight: '30px' },
},
h.button(
{
className: 'jupyter-widgets jupyter-button widget-button',
style: {
width: '60px',
border: '1px solid var(--ipydatagrid-menu-border-color, #bdbdbd)',
},
onclick: this.applyFilter.bind(this),
},
'Apply',
),
);
}
/**
* Creates an array of VirtualElements to represent the available operators
* for columns with a numerical dtype.
*/
private _createNumericalOperators(): VirtualElement[] {
const op = this._filterOperator;
return [
h.option(
{
value: 'empty',
...(op === 'empty' && { selected: '' }),
},
'Is empty:',
),
h.option(
{
value: 'notempty',
...(op === 'notempty' && { selected: '' }),
},
'Is not empty:',
),
h.option(
{
value: '',
disabled: 'disabled',
},
'───────────',
),
h.option(
{
value: '<',
...(op === '<' && { selected: '' }),
},
'Less than:',
),
h.option(
{
value: '>',
...(op === '>' && { selected: '' }),
},
'Greater than:',
),
h.option(
{
value: '<=',
...(op === '<=' && { selected: '' }),
},
'Less than or equal to:',
),
h.option(
{
value: '>=',
...(op === '>=' && { selected: '' }),
},
'Greater than or equal to:',
),
h.option(
{
value: 'between',
...(op === 'between' && { selected: '' }),
},
'In between:',
),
h.option(
{
value: '=',
...(op === '=' && { selected: '' }),
},
'Is equal to:',
),
h.option(
{
value: '!=',
...(op === '!=' && { selected: '' }),
},
'Is not equal to:',
),
];
}
/**
* Creates an array of VirtualElements to represent the available operators
* for columns with a date dtype.
*/
private _createDateOperators(): VirtualElement[] {
const op = this._filterOperator;
return [
h.option(
{
value: 'empty',
...(op === 'empty' && { selected: '' }),
},
'Is empty:',
),
h.option(
{
value: 'notempty',
...(op === 'notempty' && { selected: '' }),
},
'Is not empty:',
),
h.option(
{
value: '',
disabled: 'disabled',
},
'───────────',
),
h.option(
{
value: '<',
...(op === '<' && { selected: '' }),
},
'Date is before:',
),
h.option(
{
value: '>',
...(op === '>' && { selected: '' }),
},
'Date is after:',
),
h.option(
{
value: '<=',
...(op === '<' && { selected: '' }),
},
'Date is on or before:',
),
h.option(
{
value: '>=',
...(op === '>' && { selected: '' }),
},
'Date is on or after:',
),
h.option(
{
value: 'isOnSameDay',
...(op === 'between' && { selected: '' }),
},
'Date is exactly:',
),
h.option(
{
value: 'between',
...(op === 'between' && { selected: '' }),
},
'Date is in between:',
),
h.option(
{
value: '=',
...(op === '=' && { selected: '' }),
},
'Timestamp is exactly equal to:',
),
h.option(
{
value: '!=',
...(op === '!=' && { selected: '' }),
},
'Timestamp is not exactly equal to:',
),
];
}
/**
* Creates an array of VirtualElements to represent the available operators
* for columns with a boolean dtype.
*/
private _createBooleanOperators(): VirtualElement[] {
const op = this._filterOperator;
return [
h.option(
{
value: 'empty',
...(op === 'empty' && { selected: '' }),
},
'Is empty:',
),
h.option(
{
value: 'notempty',
...(op === 'notempty' && { selected: '' }),
},
'Is not empty:',
),
];
}
/**
* Creates an array of VirtualElements to represent the available operators
* for columns with a categorical dtype.
*/
private _createCategoricalOperators(): VirtualElement[] {
const op = this._filterOperator;
return [
h.option(
{
value: 'empty',
...(op === 'empty' && { selected: '' }),
},
'Is empty',
),
h.option(
{
value: 'notempty',
...(op === 'notempty' && { selected: '' }),
},
'Is not empty',
),
h.option(
{
value: '',
disabled: 'disabled',
},
'───────────',
),
h.option(
{
value: 'contains',
...(op === 'contains' && { selected: '' }),
},
'Contains',
),
h.option(
{
value: '!contains',
...(op === '!contains' && { selected: '' }),
},
'Does not contain',
),
h.option(
{
value: 'startswith',
...(op === 'startswith' && { selected: '' }),
},
'Starts with',
),
h.option(
{
value: 'endswith',
...(op === 'endswith' && { selected: '' }),
},
'Ends with',
),
h.option(
{
value: '=',
...(op === '=' && { selected: '' }),
},
'Is exactly',
),
h.option(
{
value: '!=',
...(op === '!=' && { selected: '' }),
},
'Is not exactly',
),
h.option(
{
value: '',
disabled: 'disabled',
},
'───────────',
),
h.option(
{
value: '<',
...(op === '<' && { selected: '' }),
},
'Is before',
),
h.option(
{
value: '>',
...(op === '>' && { selected: '' }),
},
'Is after',
),
h.option(
{
value: 'between',
...(op === 'between' && { selected: '' }),
},
'Is in between',
),
];
}
async addRemoveAllUniqueValuesToState(add: boolean) {
const uniqueVals = this.model.uniqueValues(this._region, this._columnIndex);
return uniqueVals.then((values) => {
for (const value of values) {
if (add) {
this._uniqueValueStateManager.add(
this._region,
this._columnIndex,
value,
);
} else {
this._uniqueValueStateManager.remove(
this._region,
this._columnIndex,
value,
);
}
}
});
}
/**
* Returns a reference to the data model used for this menu.
*/
get model(): ViewBasedJSONModel {
return this._model;
}
/**
* Updates the data model used for this menu.
*/
set model(model: ViewBasedJSONModel) {
this._model = model;
}
/**
* Returns the current input value of the dialog.
*/
get value(): InteractiveFilterDialog.FilterValue {
return this._filterValue;
}
/**
* Returns the currently active filter operator.
*/
get operator(): Transform.FilterOperator {
return this._filterOperator;
}
/**
* Returns the active column index.
*/
get region(): DataModel.CellRegion {
return this._region;
}
/**
* Returns the active Cellregion.
*/
get columnIndex(): number {
return this._columnIndex;
}
/**
* Returns the active column dtype.
*/
get columnDType(): string {
return this._columnDType;
}
private _model: ViewBasedJSONModel;
// Cell metadata
private _columnDType = 'number';
private _columnIndex = 0;
private _region: DataModel.CellRegion = 'column-header';
// Menu state
private _mode: 'condition' | 'value' = 'value';
private _filterOperator: Transform.FilterOperator = '<';
private _filterValue: InteractiveFilterDialog.FilterValue;
private _textInputFilterValue: InteractiveFilterDialog.FilterValue;
// Phosphor widgets
private _uniqueValueGrid: DataGrid;
private _filterByConditionWidget: Widget;
private _titleWidget: Widget;
private _textInputWidget: Widget;
private _applyWidget: Widget;
// Unique value state
private _uniqueValueStateManager: UniqueValueStateManager;
// Checking filter status
hasFilter = false;
userInteractedWithDialog = false;
private _selectAllCheckbox: SelectCanvasWidget;
}
/**
* A lumino widget for the text search input box
* for the filter-by-value dialog
*/
class TextInputWidget extends Widget {
constructor() {
super();
this.node.style.minHeight = '16px';
this.node.style.overflow = 'visible';
}
}
/**
* A lumino widget to draw and control the
* "Select All" checkbox
*/
class SelectCanvasWidget extends Widget {
constructor() {
super();
this.canvas = document.createElement('canvas');
this.node.style.minHeight = '16px';
this.node.style.overflow = 'visible';
this.node.appendChild(this.canvas);
}
get checked(): boolean {
return this._checked;
}
/**
* We re-render reach time the box is checked
*/
set checked(value: boolean) {
this._checked = value;
this.renderCheckbox();
}
get checkChanged(): ISignal<this, boolean> {
return this._checkedChanged;
}
/**
* Toggles and checkbox value and emits
* a signal to add all unique values to
* the state
*/
toggleCheckMark = () => {
this._checked = !this._checked;
this.renderCheckbox();
this._checkedChanged.emit(this._checked);
};
/**
* Rendering the actual tickmark inside the
* canvas box. This function is only called
* from within renderCheckbox() below
*/
addCheckMark() {
const gc = this.canvas.getContext('2d')!;
const BOX_OFFSET = 8;
const x = 0;
const y = 0;
gc.lineWidth = 1;
gc.beginPath();
gc.strokeStyle = '#000000';
gc.moveTo(x + BOX_OFFSET + 3, y + BOX_OFFSET + 5);
gc.lineTo(x + BOX_OFFSET + 4, y + BOX_OFFSET + 8);
gc.lineTo(x + BOX_OFFSET + 8, y + BOX_OFFSET + 2);
gc.lineWidth = 2;
gc.stroke();
}
/**
* Renders the checkbox and tick mark. Tick mark
* rendering is conditional
*/
renderCheckbox() {
const gc = this.canvas.getContext('2d')!;
// Needed to avoid blurring issue.
// Set display size (css pixels).
const size = 100;
this.canvas.style.width = size + 'px';
this.canvas.style.height = size + 'px';
// Set actual size in memory (scaled to account for extra pixel density)
const scale = window.devicePixelRatio;
this.canvas.width = Math.floor(size * scale);
this.canvas.height = Math.floor(size * scale);
// Normalize coordinate system to use css pixels.
gc.scale(scale, scale);
// Draw the checkmark rectangle
const BOX_OFFSET = 8;
const x = 0;
const y = 0;
gc.lineWidth = 1;
gc.fillStyle = '#ffffff';
gc.fillRect(x + BOX_OFFSET, y + BOX_OFFSET, 10, 10);
gc.strokeStyle = 'black';
gc.strokeRect(x + BOX_OFFSET, y + BOX_OFFSET, 10, 10);
// Draw "Select all" text
gc.font = '12px sans-serif';
gc.fillStyle = Theme.getFontColor(0);
gc.fillText('(Select All)', x + 30, y + 17);
// Draw actual tickmark inside the checkmark rect
if (this._checked) {
this.addCheckMark();
}
}
/**
* Adding an event listener for clicks in the box
* area and rendering the checkbox
*/
onAfterAttach() {
this.renderCheckbox();
this.canvas.addEventListener('click', this.toggleCheckMark, true);
}
/**
* Removing the event listener to declutter the
* DOM space
* @param msg lumino msg
*/
protected onAfterDetach(msg: Message): void {
this.canvas.removeEventListener('click', this.toggleCheckMark, true);
}
private canvas: HTMLCanvasElement;
private _checked = false;
private _checkedChanged = new Signal<this, boolean>(this);
}
/**
* The namespace for the `InteractiveFilterDialog` class statics.
*/
export namespace InteractiveFilterDialog {
/**
* An options object for creating an `InteractiveFilterDialog`.
*/
export interface IOptions {
model: ViewBasedJSONModel;
}
/**
* A type alias for various filter modes.
*/
export type FilterMode = 'condition' | 'value';
/**
* Type alias for valid input element values.
*/
export type FilterValue = Transform.FilterValue | undefined | undefined[];
/**
* An options object for the `open` method of this item.
*/
export interface IOpenOptions {
/**
* The client X coordinate of the menu location.
*/
x: number;
/**
* The client Y coordinate of the menu location.
*/
y: number;
/**
* The CellRegion of the `cellClick` that triggered this call.
*/
region: DataModel.CellRegion;
/**
* The column index of the `cellClick` that triggered this call.
*/
columnIndex: number;
/**
* Disallow repositioning of the X coordinates to prevent the menu from
* extending out of the window.
*/
forceX: boolean;
/**
* Disallow repositioning of the Y coordinates to prevent the menu from
* extending out of the window.
*/
forceY: boolean;
/**
* Selects if widget will open in `condition` or `value` mode.
*/
mode: FilterMode;
}
}
/**
* Manages the selection state of the grid that displays the unique values
* of a column.
*/
export class UniqueValueStateManager {
constructor(options: UniqueValueStateManager.IOptions) {
this._grid = options.grid;
}
has(region: DataModel.CellRegion, columnIndex: number, value: any): boolean {
const key = this.getKeyName(region, columnIndex);
return this._state.hasOwnProperty(key) && this._state[key].has(value);
}
getKeyName(region: DataModel.CellRegion, columnIndex: number): string {
return `${region}:${columnIndex}`;
}
add(region: DataModel.CellRegion, columnIndex: number, value: any): void {
const key = this.getKeyName(region, columnIndex);
if (this._state.hasOwnProperty(key)) {
this._state[key].add(value);
} else {
this._state[key] = new Set<number | string>();
this._state[key].add(value);
}
const msg = new PaintRequest('all', 0, 0, 0, 0);
MessageLoop.postMessage(this._grid.viewport, msg);
}
remove(region: DataModel.CellRegion, columnIndex: number, value: any): void {
const key = this.getKeyName(region, columnIndex);
if (this._state.hasOwnProperty(key)) {
this._state[key].delete(value);
}
const msg = new PaintRequest('all', 0, 0, 0, 0);
MessageLoop.postMessage(this._grid.viewport, msg);
}
getValues(region: DataModel.CellRegion, columnIndex: number): any[] {
const key = this.getKeyName(region, columnIndex);
if (this._state.hasOwnProperty(key)) {
return Array.from(this._state[key]);
} else {
return [];
}
}
private _state: { [key: string]: Set<number | string> } = {};
private _grid: DataGrid;
}
class UniqueValueGridMouseHandler extends BasicMouseHandler {
constructor(options: UniqueValueGridMouseHandler.IOptions) {
super();
this._uniqueValuesSelectionState = options.stateManager;
this._filterDialog = options.dialog;
}
/**
* Handle the mouse down event for the data grid.
*
* @param grid - The data grid of interest.
*
* @param event - The mouse down event of interest.
*/
//@ts-ignore added so we don't have to add basicmousehandler.ts fork
onMouseDown(grid: DataGrid, event: MouseEvent): void {
const hit = grid.hitTest(event.clientX, event.clientY);
// Bail if hitting on an invalid area
if (hit.region === 'void') {
return;
}
const row = hit.row;
const colIndex = this._filterDialog.columnIndex;
const region = this._filterDialog.region;
const value = grid.dataModel!.data('body', row, 0);
const updateCheckState = () => {
if (this._uniqueValuesSelectionState.has(region, colIndex, value)) {
this._uniqueValuesSelectionState.remove(region, colIndex, value);
} else {
this._uniqueValuesSelectionState.add(region, colIndex, value);
}
// Updating the "Select all" chexboox if needed
this._filterDialog.updateSelectAllCheckboxState();
};
// User is clicking for the first time when no filter is applied
if (
!this._filterDialog.hasFilter &&
!this._filterDialog.userInteractedWithDialog
) {
this._filterDialog.addRemoveAllUniqueValuesToState(true).then(() => {
this._filterDialog.userInteractedWithDialog = true;
updateCheckState();
});
} else {
updateCheckState();
}
}
private _uniqueValuesSelectionState: UniqueValueStateManager;
private _filterDialog: InteractiveFilterDialog;
}
class PaintRequest extends ConflatableMessage {
/**
* Construct a new paint request messages.
*
* @param region - The cell region for the paint.
*
* @param r1 - The top-left row of the dirty region.
*
* @param c1 - The top-left column of the dirty region.
*
* @param r2 - The bottom-right row of the dirty region.
*
* @param c2 - The bottom-right column of the dirty region.
*/
constructor(
region: DataModel.CellRegion | 'all',
r1: number,
c1: number,
r2: number,
c2: number,
) {
super('paint-request');
this._region = region;
this._r1 = r1;
this._c1 = c1;
this._r2 = r2;
this._c2 = c2;
}
/**
* The cell region for the paint.
*/
get region(): DataModel.CellRegion | 'all' {
return this._region;
}
/**
* The top-left row of the dirty region.
*/
get r1(): number {
return this._r1;
}
/**
* The top-left column of the dirty region.
*/
get c1(): number {
return this._c1;
}
/**
* The bottom-right row of the dirty region.
*/
get r2(): number {
return this._r2;
}
/**
* The bottom-right column of the dirty region.
*/
get c2(): number {
return this._c2;
}
/**
* Conflate this message with another paint request.
*/
conflate(other: PaintRequest): boolean {
// Bail early if the request is already painting everything.
if (this._region === 'all') {
return true;
}
// Any region can conflate with the `'all'` region.
if (other._region === 'all') {
this._region = 'all';
return true;
}
// Otherwise, do not conflate with a different region.
if (this._region !== other._region) {
return false;
}
// Conflate the region to the total boundary.
this._r1 = Math.min(this._r1, other._r1);
this._c1 = Math.min(this._c1, other._c1);
this._r2 = Math.max(this._r2, other._r2);
this._c2 = Math.max(this._c2, other._c2);
return true;
}
private _region: DataModel.CellRegion | 'all';
private _r1: number;
private _c1: number;
private _r2: number;
private _c2: number;
}
/**
* The namespace for the `UniqueValueStateManager` class statics.
*/
export namespace UniqueValueStateManager {
/**
* An options object for initializing an UniqueValueStateManager.
*/
export interface IOptions {
/**
* The DataGrid to manage selection state for
*/
grid: DataGrid;
}
}
/**
* The namespace for the `UniqueValueGridMouseHandler` class statics.
*/
export namespace UniqueValueGridMouseHandler {
/**
* An options object for initializing a UniqueValueGridMouseHandler.
*/
export interface IOptions {
/**
* The state manager linked to the grid for this mouse handler.
*/
stateManager: UniqueValueStateManager;
/**
* The dialog linked to this mouse handler.
*/
dialog: InteractiveFilterDialog;
}
} | the_stack |
import * as assert from 'assert';
import * as fsExtra from 'fs-extra';
import * as path from 'path';
import type { CodeAction, CompletionItem, Position, Range, SignatureInformation } from 'vscode-languageserver';
import { Location, CompletionItemKind } from 'vscode-languageserver';
import type { BsConfig } from './BsConfig';
import { Scope } from './Scope';
import { DiagnosticMessages } from './DiagnosticMessages';
import { BrsFile } from './files/BrsFile';
import { XmlFile } from './files/XmlFile';
import type { BsDiagnostic, File, FileReference, FileObj, BscFile, SemanticToken } from './interfaces';
import { standardizePath as s, util } from './util';
import { XmlScope } from './XmlScope';
import { DiagnosticFilterer } from './DiagnosticFilterer';
import { DependencyGraph } from './DependencyGraph';
import { Logger, LogLevel } from './Logger';
import chalk from 'chalk';
import { globalFile } from './globalCallables';
import type { ManifestValue } from './preprocessor/Manifest';
import { parseManifest } from './preprocessor/Manifest';
import { URI } from 'vscode-uri';
import PluginInterface from './PluginInterface';
import { isBrsFile, isXmlFile, isClassMethodStatement, isXmlScope } from './astUtils/reflection';
import type { FunctionStatement, Statement } from './parser/Statement';
import { ParseMode } from './parser';
import { TokenKind } from './lexer';
import { BscPlugin } from './bscPlugin/BscPlugin';
const startOfSourcePkgPath = `source${path.sep}`;
const bslibNonAliasedRokuModulesPkgPath = s`source/roku_modules/rokucommunity_bslib/bslib.brs`;
const bslibAliasedRokuModulesPkgPath = s`source/roku_modules/bslib/bslib.brs`;
export interface SourceObj {
pathAbsolute: string;
source: string;
definitions?: string;
}
export interface TranspileObj {
file: BscFile;
outputPath: string;
}
export interface SignatureInfoObj {
index: number;
key: string;
signature: SignatureInformation;
}
export interface FileLink<T> {
item: T;
file: BrsFile;
}
interface PartialStatementInfo {
commaCount: number;
statementType: string;
name: string;
dotPart: string;
}
export class Program {
constructor(
/**
* The root directory for this program
*/
public options: BsConfig,
logger?: Logger,
plugins?: PluginInterface
) {
this.options = util.normalizeConfig(options);
this.logger = logger || new Logger(options.logLevel as LogLevel);
this.plugins = plugins || new PluginInterface([], this.logger);
//inject the bsc plugin as the first plugin in the stack.
this.plugins.addFirst(new BscPlugin());
//normalize the root dir path
this.options.rootDir = util.getRootDir(this.options);
this.createGlobalScope();
}
public logger: Logger;
private createGlobalScope() {
//create the 'global' scope
this.globalScope = new Scope('global', this, 'scope:global');
this.globalScope.attachDependencyGraph(this.dependencyGraph);
this.scopes.global = this.globalScope;
//hardcode the files list for global scope to only contain the global file
this.globalScope.getAllFiles = () => [globalFile];
this.globalScope.validate();
//for now, disable validation of global scope because the global files have some duplicate method declarations
this.globalScope.getDiagnostics = () => [];
//TODO we might need to fix this because the isValidated clears stuff now
(this.globalScope as any).isValidated = true;
}
/**
* A graph of all files and their dependencies.
* For example:
* File.xml -> [lib1.brs, lib2.brs]
* lib2.brs -> [lib3.brs] //via an import statement
*/
private dependencyGraph = new DependencyGraph();
private diagnosticFilterer = new DiagnosticFilterer();
/**
* A scope that contains all built-in global functions.
* All scopes should directly or indirectly inherit from this scope
*/
public globalScope: Scope;
/**
* Plugins which can provide extra diagnostics or transform AST
*/
public plugins: PluginInterface;
/**
* A set of diagnostics. This does not include any of the scope diagnostics.
* Should only be set from `this.validate()`
*/
private diagnostics = [] as BsDiagnostic[];
/**
* The path to bslib.brs (the BrightScript runtime for certain BrighterScript features)
*/
public get bslibPkgPath() {
//if there's an aliased (preferred) version of bslib from roku_modules loaded into the program, use that
if (this.getFileByPkgPath(bslibAliasedRokuModulesPkgPath)) {
return bslibAliasedRokuModulesPkgPath;
//if there's a non-aliased version of bslib from roku_modules, use that
} else if (this.getFileByPkgPath(bslibNonAliasedRokuModulesPkgPath)) {
return bslibNonAliasedRokuModulesPkgPath;
//default to the embedded version
} else {
return `source${path.sep}bslib.brs`;
}
}
public get bslibPrefix() {
if (this.bslibPkgPath === bslibNonAliasedRokuModulesPkgPath) {
return 'rokucommunity_bslib';
} else {
return 'bslib';
}
}
/**
* A map of every file loaded into this program, indexed by its original file location
*/
public files = {} as Record<string, BscFile>;
private pkgMap = {} as Record<string, BscFile>;
private scopes = {} as Record<string, Scope>;
protected addScope(scope: Scope) {
this.scopes[scope.name] = scope;
this.plugins.emit('afterScopeCreate', scope);
}
/**
* A map of every component currently loaded into the program, indexed by the component name.
* It is a compile-time error to have multiple components with the same name. However, we store an array of components
* by name so we can provide a better developer expreience. You shouldn't be directly accessing this array,
* but if you do, only ever use the component at index 0.
*/
private components = {} as Record<string, { file: XmlFile; scope: XmlScope }[]>;
/**
* Get the component with the specified name
*/
public getComponent(componentName: string) {
if (componentName) {
//return the first compoment in the list with this name
//(components are ordered in this list by pkgPath to ensure consistency)
return this.components[componentName.toLowerCase()]?.[0];
} else {
return undefined;
}
}
/**
* Register (or replace) the reference to a component in the component map
*/
private registerComponent(xmlFile: XmlFile, scope: XmlScope) {
const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
if (!this.components[key]) {
this.components[key] = [];
}
this.components[key].push({
file: xmlFile,
scope: scope
});
this.components[key].sort(
(x, y) => x.file.pkgPath.toLowerCase().localeCompare(y.file.pkgPath.toLowerCase())
);
this.syncComponentDependencyGraph(this.components[key]);
}
/**
* Remove the specified component from the components map
*/
private unregisterComponent(xmlFile: XmlFile) {
const key = (xmlFile.componentName?.text ?? xmlFile.pkgPath).toLowerCase();
const arr = this.components[key] || [];
for (let i = 0; i < arr.length; i++) {
if (arr[i].file === xmlFile) {
arr.splice(i, 1);
break;
}
}
this.syncComponentDependencyGraph(arr);
}
/**
* re-attach the dependency graph with a new key for any component who changed
* their position in their own named array (only matters when there are multiple
* components with the same name)
*/
private syncComponentDependencyGraph(components: Array<{ file: XmlFile; scope: XmlScope }>) {
//reattach every dependency graph
for (let i = 0; i < components.length; i++) {
const { file, scope } = components[i];
//attach (or re-attach) the dependencyGraph for every component whose position changed
if (file.dependencyGraphIndex !== i) {
file.dependencyGraphIndex = i;
file.attachDependencyGraph(this.dependencyGraph);
scope.attachDependencyGraph(this.dependencyGraph);
}
}
}
/**
* Get a list of all files that are included in the project but are not referenced
* by any scope in the program.
*/
public getUnreferencedFiles() {
let result = [] as File[];
for (let filePath in this.files) {
let file = this.files[filePath];
if (!this.fileIsIncludedInAnyScope(file)) {
//no scopes reference this file. add it to the list
result.push(file);
}
}
return result;
}
/**
* Get the list of errors for the entire program. It's calculated on the fly
* by walking through every file, so call this sparingly.
*/
public getDiagnostics() {
return this.logger.time(LogLevel.info, ['Program.getDiagnostics()'], () => {
let diagnostics = [...this.diagnostics];
//get the diagnostics from all scopes
for (let scopeName in this.scopes) {
let scope = this.scopes[scopeName];
diagnostics.push(
...scope.getDiagnostics()
);
}
//get the diagnostics from all unreferenced files
let unreferencedFiles = this.getUnreferencedFiles();
for (let file of unreferencedFiles) {
diagnostics.push(
...file.getDiagnostics()
);
}
const filteredDiagnostics = this.logger.time(LogLevel.debug, ['filter diagnostics'], () => {
//filter out diagnostics based on our diagnostic filters
let finalDiagnostics = this.diagnosticFilterer.filter({
...this.options,
rootDir: this.options.rootDir
}, diagnostics);
return finalDiagnostics;
});
this.logger.info(`diagnostic counts: total=${chalk.yellow(diagnostics.length.toString())}, after filter=${chalk.yellow(filteredDiagnostics.length.toString())}`);
return filteredDiagnostics;
});
}
public addDiagnostics(diagnostics: BsDiagnostic[]) {
this.diagnostics.push(...diagnostics);
}
/**
* Determine if the specified file is loaded in this program right now.
* @param filePath
*/
public hasFile(filePath: string) {
filePath = s`${filePath}`;
return this.files[filePath] !== undefined;
}
public getPkgPath(...args: any[]): any { //eslint-disable-line
throw new Error('Not implemented');
}
/**
* roku filesystem is case INsensitive, so find the scope by key case insensitive
* @param scopeName
*/
public getScopeByName(scopeName: string) {
if (!scopeName) {
return undefined;
}
//most scopes are xml file pkg paths. however, the ones that are not are single names like "global" and "scope",
//so it's safe to run the standardizePkgPath method
scopeName = s`${scopeName}`;
let key = Object.keys(this.scopes).find(x => x.toLowerCase() === scopeName.toLowerCase());
return this.scopes[key];
}
/**
* Return all scopes
*/
public getScopes() {
return Object.values(this.scopes);
}
/**
* Find the scope for the specified component
*/
public getComponentScope(componentName: string) {
return this.getComponent(componentName)?.scope;
}
/**
* Load a file into the program. If that file already exists, it is replaced.
* If file contents are provided, those are used, Otherwise, the file is loaded from the file system
* @param relativePath the file path relative to the root dir
* @param fileContents the file contents
*/
public addOrReplaceFile<T extends BscFile>(relativePath: string, fileContents: string): T;
/**
* Load a file into the program. If that file already exists, it is replaced.
* @param fileEntry an object that specifies src and dest for the file.
* @param fileContents the file contents. If not provided, the file will be loaded from disk
*/
public addOrReplaceFile<T extends BscFile>(fileEntry: FileObj, fileContents: string): T;
public addOrReplaceFile<T extends BscFile>(fileParam: FileObj | string, fileContents: string): T {
assert.ok(fileParam, 'fileEntry is required');
let srcPath: string;
let pkgPath: string;
if (typeof fileParam === 'string') {
srcPath = s`${this.options.rootDir}/${fileParam}`;
pkgPath = s`${fileParam}`;
} else {
srcPath = s`${fileParam.src}`;
pkgPath = s`${fileParam.dest}`;
}
let file = this.logger.time(LogLevel.debug, ['Program.addOrReplaceFile()', chalk.green(srcPath)], () => {
assert.ok(srcPath, 'fileEntry.src is required');
assert.ok(pkgPath, 'fileEntry.dest is required');
//if the file is already loaded, remove it
if (this.hasFile(srcPath)) {
this.removeFile(srcPath);
}
let fileExtension = path.extname(srcPath).toLowerCase();
let file: BscFile | undefined;
if (fileExtension === '.brs' || fileExtension === '.bs') {
let brsFile = new BrsFile(srcPath, pkgPath, this);
//add file to the `source` dependency list
if (brsFile.pkgPath.startsWith(startOfSourcePkgPath)) {
this.createSourceScope();
this.dependencyGraph.addDependency('scope:source', brsFile.dependencyGraphKey);
}
//add the file to the program
this.files[srcPath] = brsFile;
this.pkgMap[brsFile.pkgPath.toLowerCase()] = brsFile;
let sourceObj: SourceObj = {
pathAbsolute: srcPath,
source: fileContents
};
this.plugins.emit('beforeFileParse', sourceObj);
this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
brsFile.parse(sourceObj.source);
});
file = brsFile;
brsFile.attachDependencyGraph(this.dependencyGraph);
this.plugins.emit('afterFileValidate', brsFile);
} else if (
//is xml file
fileExtension === '.xml' &&
//resides in the components folder (Roku will only parse xml files in the components folder)
pkgPath.toLowerCase().startsWith(util.pathSepNormalize(`components/`))
) {
let xmlFile = new XmlFile(srcPath, pkgPath, this);
//add the file to the program
this.files[srcPath] = xmlFile;
this.pkgMap[xmlFile.pkgPath.toLowerCase()] = xmlFile;
let sourceObj: SourceObj = {
pathAbsolute: srcPath,
source: fileContents
};
this.plugins.emit('beforeFileParse', sourceObj);
this.logger.time(LogLevel.debug, ['parse', chalk.green(srcPath)], () => {
xmlFile.parse(sourceObj.source);
});
file = xmlFile;
//create a new scope for this xml file
let scope = new XmlScope(xmlFile, this);
this.addScope(scope);
//register this compoent now that we have parsed it and know its component name
this.registerComponent(xmlFile, scope);
this.plugins.emit('afterFileValidate', xmlFile);
} else {
//TODO do we actually need to implement this? Figure out how to handle img paths
// let genericFile = this.files[pathAbsolute] = <any>{
// pathAbsolute: pathAbsolute,
// pkgPath: pkgPath,
// wasProcessed: true
// } as File;
// file = <any>genericFile;
}
return file;
});
return file as T;
}
/**
* Ensure source scope is created.
* Note: automatically called internally, and no-op if it exists already.
*/
public createSourceScope() {
if (!this.scopes.source) {
const sourceScope = new Scope('source', this, 'scope:source');
sourceScope.attachDependencyGraph(this.dependencyGraph);
this.addScope(sourceScope);
}
}
/**
* Find the file by its absolute path. This is case INSENSITIVE, since
* Roku is a case insensitive file system. It is an error to have multiple files
* with the same path with only case being different.
* @param pathAbsolute
*/
public getFileByPathAbsolute<T extends BrsFile | XmlFile>(pathAbsolute: string) {
pathAbsolute = s`${pathAbsolute}`;
for (let filePath in this.files) {
if (filePath.toLowerCase() === pathAbsolute.toLowerCase()) {
return this.files[filePath] as T;
}
}
}
/**
* Get a list of files for the given (platform-normalized) pkgPath array.
* Missing files are just ignored.
*/
public getFilesByPkgPaths<T extends BscFile[]>(pkgPaths: string[]) {
return pkgPaths
.map(pkgPath => this.getFileByPkgPath(pkgPath))
.filter(file => file !== undefined) as T;
}
/**
* Get a file with the specified (platform-normalized) pkg path.
* If not found, return undefined
*/
public getFileByPkgPath<T extends BscFile>(pkgPath: string) {
return this.pkgMap[pkgPath.toLowerCase()] as T;
}
/**
* Remove a set of files from the program
* @param absolutePaths
*/
public removeFiles(absolutePaths: string[]) {
for (let pathAbsolute of absolutePaths) {
this.removeFile(pathAbsolute);
}
}
/**
* Remove a file from the program
* @param pathAbsolute
*/
public removeFile(pathAbsolute: string) {
this.logger.debug('Program.removeFile()', pathAbsolute);
if (!path.isAbsolute(pathAbsolute)) {
throw new Error(`Path must be absolute: "${pathAbsolute}"`);
}
let file = this.getFile(pathAbsolute);
if (file) {
this.plugins.emit('beforeFileDispose', file);
//if there is a scope named the same as this file's path, remove it (i.e. xml scopes)
let scope = this.scopes[file.pkgPath];
if (scope) {
this.plugins.emit('beforeScopeDispose', scope);
scope.dispose();
//notify dependencies of this scope that it has been removed
this.dependencyGraph.remove(scope.dependencyGraphKey);
delete this.scopes[file.pkgPath];
this.plugins.emit('afterScopeDispose', scope);
}
//remove the file from the program
delete this.files[file.pathAbsolute];
delete this.pkgMap[file.pkgPath.toLowerCase()];
this.dependencyGraph.remove(file.dependencyGraphKey);
//if this is a pkg:/source file, notify the `source` scope that it has changed
if (file.pkgPath.startsWith(startOfSourcePkgPath)) {
this.dependencyGraph.removeDependency('scope:source', file.dependencyGraphKey);
}
//if this is a component, remove it from our components map
if (isXmlFile(file)) {
this.unregisterComponent(file);
}
this.plugins.emit('afterFileDispose', file);
}
}
/**
* Traverse the entire project, and validate all scopes
* @param force - if true, then all scopes are force to validate, even if they aren't marked as dirty
*/
public validate() {
this.logger.time(LogLevel.log, ['Validating project'], () => {
this.diagnostics = [];
this.plugins.emit('beforeProgramValidate', this);
this.logger.time(LogLevel.info, ['Validate all scopes'], () => {
for (let scopeName in this.scopes) {
let scope = this.scopes[scopeName];
scope.validate();
}
});
//find any files NOT loaded into a scope
for (let filePath in this.files) {
let file = this.files[filePath];
if (!this.fileIsIncludedInAnyScope(file)) {
this.logger.debug('Program.validate(): fileNotReferenced by any scope', () => chalk.green(file?.pkgPath));
//the file is not loaded in any scope
this.diagnostics.push({
...DiagnosticMessages.fileNotReferencedByAnyOtherFile(),
file: file,
range: util.createRange(0, 0, 0, Number.MAX_VALUE)
});
}
}
this.detectDuplicateComponentNames();
this.plugins.emit('afterProgramValidate', this);
});
}
/**
* Flag all duplicate component names
*/
private detectDuplicateComponentNames() {
const componentsByName = Object.keys(this.files).reduce<Record<string, XmlFile[]>>((map, filePath) => {
const file = this.files[filePath];
//if this is an XmlFile, and it has a valid `componentName` property
if (isXmlFile(file) && file.componentName?.text) {
let lowerName = file.componentName.text.toLowerCase();
if (!map[lowerName]) {
map[lowerName] = [];
}
map[lowerName].push(file);
}
return map;
}, {});
for (let name in componentsByName) {
const xmlFiles = componentsByName[name];
//add diagnostics for every duplicate component with this name
if (xmlFiles.length > 1) {
for (let xmlFile of xmlFiles) {
const { componentName } = xmlFile;
this.diagnostics.push({
...DiagnosticMessages.duplicateComponentName(componentName.text),
range: xmlFile.componentName.range,
file: xmlFile,
relatedInformation: xmlFiles.filter(x => x !== xmlFile).map(x => {
return {
location: Location.create(
URI.file(xmlFile.pathAbsolute).toString(),
x.componentName.range
),
message: 'Also defined here'
};
})
});
}
}
}
}
/**
* Determine if the given file is included in at least one scope in this program
*/
private fileIsIncludedInAnyScope(file: BscFile) {
for (let scopeName in this.scopes) {
if (this.scopes[scopeName].hasFile(file)) {
return true;
}
}
return false;
}
/**
* Get the file at the given path
* @param pathAbsolute
*/
private getFile<T extends BscFile>(pathAbsolute: string) {
pathAbsolute = s`${pathAbsolute}`;
return this.files[pathAbsolute] as T;
}
/**
* Get a list of all scopes the file is loaded into
* @param file
*/
public getScopesForFile(file: XmlFile | BrsFile) {
let result = [] as Scope[];
for (let key in this.scopes) {
let scope = this.scopes[key];
if (scope.hasFile(file)) {
result.push(scope);
}
}
return result;
}
public getStatementsByName(name: string, originFile: BrsFile, namespaceName?: string): FileLink<Statement>[] {
let results = new Map<Statement, FileLink<Statement>>();
const filesSearched = new Set<BrsFile>();
let lowerNamespaceName = namespaceName?.toLowerCase();
let lowerName = name?.toLowerCase();
//look through all files in scope for matches
for (const scope of this.getScopesForFile(originFile)) {
for (const file of scope.getAllFiles()) {
if (isXmlFile(file) || filesSearched.has(file)) {
continue;
}
filesSearched.add(file);
for (const statement of [...file.parser.references.functionStatements, ...file.parser.references.classStatements.flatMap((cs) => cs.methods)]) {
let parentNamespaceName = statement.namespaceName?.getName(originFile.parseMode)?.toLowerCase();
if (statement.name.text.toLowerCase() === lowerName && (!parentNamespaceName || parentNamespaceName === lowerNamespaceName)) {
if (!results.has(statement)) {
results.set(statement, { item: statement, file: file });
}
}
}
}
}
return [...results.values()];
}
public getStatementsForXmlFile(scope: XmlScope, filterName?: string): FileLink<FunctionStatement>[] {
let results = new Map<Statement, FileLink<FunctionStatement>>();
const filesSearched = new Set<BrsFile>();
//get all function names for the xml file and parents
let funcNames = new Set<string>();
let currentScope = scope;
while (isXmlScope(currentScope)) {
for (let name of currentScope.xmlFile.ast.component.api?.functions.map((f) => f.name) ?? []) {
if (!filterName || name === filterName) {
funcNames.add(name);
}
}
currentScope = currentScope.getParentScope() as XmlScope;
}
//look through all files in scope for matches
for (const file of scope.getOwnFiles()) {
if (isXmlFile(file) || filesSearched.has(file)) {
continue;
}
filesSearched.add(file);
for (const statement of file.parser.references.functionStatements) {
if (funcNames.has(statement.name.text)) {
if (!results.has(statement)) {
results.set(statement, { item: statement, file: file });
}
}
}
}
return [...results.values()];
}
/**
* Find all available completion items at the given position
* @param pathAbsolute
* @param lineIndex
* @param columnIndex
*/
public getCompletions(pathAbsolute: string, position: Position) {
let file = this.getFile(pathAbsolute);
if (!file) {
return [];
}
let result = [] as CompletionItem[];
if (isBrsFile(file) && file.isPositionNextToTokenKind(position, TokenKind.Callfunc)) {
// is next to a @. callfunc invocation - must be an interface method
for (const scope of this.getScopes().filter((s) => isXmlScope(s))) {
let fileLinks = this.getStatementsForXmlFile(scope as XmlScope);
for (let fileLink of fileLinks) {
result.push(scope.createCompletionFromFunctionStatement(fileLink.item));
}
}
//no other result is possible in this case
return result;
}
//find the scopes for this file
let scopes = this.getScopesForFile(file);
//if there are no scopes, include the global scope so we at least get the built-in functions
scopes = scopes.length > 0 ? scopes : [this.globalScope];
//get the completions from all scopes for this file
let allCompletions = util.flatMap(
scopes.map(ctx => file.getCompletions(position, ctx)),
c => c
);
//only keep completions common to every scope for this file
let keyCounts = {} as Record<string, number>;
for (let completion of allCompletions) {
let key = `${completion.label}-${completion.kind}`;
keyCounts[key] = keyCounts[key] ? keyCounts[key] + 1 : 1;
if (keyCounts[key] === scopes.length) {
result.push(completion);
}
}
return result;
}
/**
* Goes through each file and builds a list of workspace symbols for the program. Used by LanguageServer's onWorkspaceSymbol functionality
*/
public getWorkspaceSymbols() {
const results = Object.keys(this.files).map(key => {
const file = this.files[key];
if (isBrsFile(file)) {
return file.getWorkspaceSymbols();
}
return [];
});
return util.flatMap(results, c => c);
}
/**
* Given a position in a file, if the position is sitting on some type of identifier,
* go to the definition of that identifier (where this thing was first defined)
*/
public getDefinition(pathAbsolute: string, position: Position) {
let file = this.getFile(pathAbsolute);
if (!file) {
return [];
}
if (isBrsFile(file)) {
return file.getDefinition(position);
} else {
let results = [] as Location[];
const scopes = this.getScopesForFile(file);
for (const scope of scopes) {
results = results.concat(...scope.getDefinition(file, position));
}
return results;
}
}
public getHover(pathAbsolute: string, position: Position) {
//find the file
let file = this.getFile(pathAbsolute);
if (!file) {
return null;
}
return Promise.resolve(file.getHover(position));
}
/**
* Compute code actions for the given file and range
*/
public getCodeActions(pathAbsolute: string, range: Range) {
const codeActions = [] as CodeAction[];
const file = this.getFile(pathAbsolute);
if (file) {
const diagnostics = this
//get all current diagnostics (filtered by diagnostic filters)
.getDiagnostics()
//only keep diagnostics related to this file
.filter(x => x.file === file)
//only keep diagnostics that touch this range
.filter(x => util.rangesIntersect(x.range, range));
const scopes = this.getScopesForFile(file);
this.plugins.emit('onGetCodeActions', {
program: this,
file: file,
range: range,
diagnostics: diagnostics,
scopes: scopes,
codeActions: codeActions
});
}
return codeActions;
}
/**
* Get semantic tokens for the specified file
*/
public getSemanticTokens(srcPath: string) {
const file = this.getFile(srcPath);
if (file) {
const result = [] as SemanticToken[];
this.plugins.emit('onGetSemanticTokens', {
program: this,
file: file,
scopes: this.getScopesForFile(file),
semanticTokens: result
});
return result;
}
}
public getSignatureHelp(filepath: string, position: Position): SignatureInfoObj[] {
let file: BrsFile = this.getFile(filepath);
if (!file || !isBrsFile(file)) {
return [];
}
const results = new Map<string, SignatureInfoObj>();
let functionScope = file.getFunctionScopeAtPosition(position);
let identifierInfo = this.getPartialStatementInfo(file, position);
if (identifierInfo.statementType === '') {
// just general function calls
let statements = file.program.getStatementsByName(identifierInfo.name, file);
for (let statement of statements) {
//TODO better handling of collisions - if it's a namespace, then don't show any other overrides
//if we're on m - then limit scope to the current class, if present
let sigHelp = statement.file.getSignatureHelpForStatement(statement.item);
if (sigHelp && !results.has[sigHelp.key]) {
sigHelp.index = identifierInfo.commaCount;
results.set(sigHelp.key, sigHelp);
}
}
} else if (identifierInfo.statementType === '.') {
//if m class reference.. then
//only get statements from the class I am in..
if (functionScope) {
let myClass = file.getClassFromMReference(position, file.getTokenAt(position), functionScope);
if (myClass) {
for (let scope of this.getScopesForFile(myClass.file)) {
let classes = scope.getClassHierarchy(myClass.item.getName(ParseMode.BrighterScript).toLowerCase());
//and anything from any class in scope to a non m class
for (let statement of [...classes].filter((i) => isClassMethodStatement(i.item))) {
let sigHelp = statement.file.getSignatureHelpForStatement(statement.item);
if (sigHelp && !results.has[sigHelp.key]) {
results.set(sigHelp.key, sigHelp);
return;
}
}
}
}
}
if (identifierInfo.dotPart) {
//potential namespaces
let statements = file.program.getStatementsByName(identifierInfo.name, file, identifierInfo.dotPart);
if (statements.length === 0) {
//was not a namespaced function, it could be any method on any class now
statements = file.program.getStatementsByName(identifierInfo.name, file);
}
for (let statement of statements) {
//TODO better handling of collisions - if it's a namespace, then don't show any other overrides
//if we're on m - then limit scope to the current class, if present
let sigHelp = statement.file.getSignatureHelpForStatement(statement.item);
if (sigHelp && !results.has[sigHelp.key]) {
sigHelp.index = identifierInfo.commaCount;
results.set(sigHelp.key, sigHelp);
}
}
}
} else if (identifierInfo.statementType === '@.') {
for (const scope of this.getScopes().filter((s) => isXmlScope(s))) {
let fileLinks = this.getStatementsForXmlFile(scope as XmlScope, identifierInfo.name);
for (let fileLink of fileLinks) {
let sigHelp = fileLink.file.getSignatureHelpForStatement(fileLink.item);
if (sigHelp && !results.has[sigHelp.key]) {
sigHelp.index = identifierInfo.commaCount;
results.set(sigHelp.key, sigHelp);
}
}
}
} else if (identifierInfo.statementType === 'new') {
let classItem = file.getClassFileLink(identifierInfo.dotPart ? `${identifierInfo.dotPart}.${identifierInfo.name}` : identifierInfo.name);
let sigHelp = classItem?.file?.getClassSignatureHelp(classItem?.item);
if (sigHelp && !results.has(sigHelp.key)) {
sigHelp.index = identifierInfo.commaCount;
results.set(sigHelp.key, sigHelp);
}
}
return [...results.values()];
}
private getPartialStatementInfo(file: BrsFile, position: Position): PartialStatementInfo {
let lines = util.splitIntoLines(file.fileContents);
let line = lines[position.line];
let index = position.character;
let itemCounts = this.getPartialItemCounts(line, index);
if (!itemCounts.isArgStartFound && line.charAt(index) === ')') {
//try previous char, in case we were on a close bracket..
index--;
itemCounts = this.getPartialItemCounts(line, index);
}
let argStartIndex = itemCounts.argStartIndex;
index = itemCounts.argStartIndex - 1;
let statementType = '';
let name;
let dotPart;
if (!itemCounts.isArgStartFound) {
//try to get sig help based on the name
index = position.character;
let currentToken = file.getTokenAt(position);
if (currentToken && currentToken.kind !== TokenKind.Comment) {
name = file.getPartialVariableName(currentToken, [TokenKind.New]);
if (!name) {
//try the previous token, incase we're on a bracket
currentToken = file.getPreviousToken(currentToken);
name = file.getPartialVariableName(currentToken, [TokenKind.New]);
}
if (name?.indexOf('.')) {
let parts = name.split('.');
name = parts[parts.length - 1];
}
index = currentToken.range.start.character;
argStartIndex = index;
} else {
// invalid location
index = 0;
itemCounts.comma = 0;
}
}
//this loop is quirky. walk to -1 (which will result in the last char being '' thus satisfying the situation where there is no leading whitespace).
while (index >= -1) {
if (!(/[a-z0-9_\.\@]/i).test(line.charAt(index))) {
if (!name) {
name = line.substring(index + 1, argStartIndex);
} else {
dotPart = line.substring(index + 1, argStartIndex);
if (dotPart.endsWith('.')) {
dotPart = dotPart.substr(0, dotPart.length - 1);
}
}
break;
}
if (line.substr(index - 2, 2) === '@.') {
statementType = '@.';
name = name || line.substring(index, argStartIndex);
break;
} else if (line.charAt(index - 1) === '.' && statementType === '') {
statementType = '.';
name = name || line.substring(index, argStartIndex);
argStartIndex = index;
}
index--;
}
if (line.substring(0, index).trim().endsWith('new')) {
statementType = 'new';
}
return {
commaCount: itemCounts.comma,
statementType: statementType,
name: name,
dotPart: dotPart
};
}
private getPartialItemCounts(line: string, index: number) {
let isArgStartFound = false;
let itemCounts = {
normal: 0,
square: 0,
curly: 0,
comma: 0,
endIndex: 0,
argStartIndex: index,
isArgStartFound: false
};
while (index >= 0) {
const currentChar = line.charAt(index);
if (currentChar === '\'') { //found comment, invalid index
itemCounts.isArgStartFound = false;
break;
}
if (isArgStartFound) {
if (currentChar !== ' ') {
break;
}
} else {
if (currentChar === ')') {
itemCounts.normal++;
}
if (currentChar === ']') {
itemCounts.square++;
}
if (currentChar === '}') {
itemCounts.curly++;
}
if (currentChar === ',' && itemCounts.normal <= 0 && itemCounts.curly <= 0 && itemCounts.square <= 0) {
itemCounts.comma++;
}
if (currentChar === '(') {
if (itemCounts.normal === 0) {
itemCounts.isArgStartFound = true;
itemCounts.argStartIndex = index;
} else {
itemCounts.normal--;
}
}
if (currentChar === '[') {
itemCounts.square--;
}
if (currentChar === '{') {
itemCounts.curly--;
}
}
index--;
}
return itemCounts;
}
public getReferences(pathAbsolute: string, position: Position) {
//find the file
let file = this.getFile(pathAbsolute);
if (!file) {
return null;
}
return file.getReferences(position);
}
/**
* Get a list of all script imports, relative to the specified pkgPath
* @param sourcePkgPath - the pkgPath of the source that wants to resolve script imports.
*/
public getScriptImportCompletions(sourcePkgPath: string, scriptImport: FileReference) {
let lowerSourcePkgPath = sourcePkgPath.toLowerCase();
let result = [] as CompletionItem[];
/**
* hashtable to prevent duplicate results
*/
let resultPkgPaths = {} as Record<string, boolean>;
//restrict to only .brs files
for (let key in this.files) {
let file = this.files[key];
if (
//is a BrightScript or BrighterScript file
(file.extension === '.bs' || file.extension === '.brs') &&
//this file is not the current file
lowerSourcePkgPath !== file.pkgPath.toLowerCase()
) {
//add the relative path
let relativePath = util.getRelativePath(sourcePkgPath, file.pkgPath).replace(/\\/g, '/');
let pkgPathStandardized = file.pkgPath.replace(/\\/g, '/');
let filePkgPath = `pkg:/${pkgPathStandardized}`;
let lowerFilePkgPath = filePkgPath.toLowerCase();
if (!resultPkgPaths[lowerFilePkgPath]) {
resultPkgPaths[lowerFilePkgPath] = true;
result.push({
label: relativePath,
detail: file.pathAbsolute,
kind: CompletionItemKind.File,
textEdit: {
newText: relativePath,
range: scriptImport.filePathRange
}
});
//add the absolute path
result.push({
label: filePkgPath,
detail: file.pathAbsolute,
kind: CompletionItemKind.File,
textEdit: {
newText: filePkgPath,
range: scriptImport.filePathRange
}
});
}
}
}
return result;
}
/**
* Transpile a single file and get the result as a string.
* This does not write anything to the file system.
*/
public getTranspiledFileContents(pathAbsolute: string) {
let file = this.getFile(pathAbsolute);
let result = file.transpile();
return {
...result,
pathAbsolute: file.pathAbsolute,
pkgPath: file.pkgPath
};
}
public async transpile(fileEntries: FileObj[], stagingFolderPath: string) {
// map fileEntries using their path as key, to avoid excessive "find()" operations
const mappedFileEntries = fileEntries.reduce<Record<string, FileObj>>((collection, entry) => {
collection[s`${entry.src}`] = entry;
return collection;
}, {});
const entries = Object.values(this.files).map(file => {
let filePathObj = mappedFileEntries[s`${file.pathAbsolute}`];
if (!filePathObj) {
//this file has been added in-memory, from a plugin, for example
filePathObj = {
//add an interpolated src path (since it doesn't actually exist in memory)
src: `bsc:/${file.pkgPath}`,
dest: file.pkgPath
};
}
//replace the file extension
let outputPath = filePathObj.dest.replace(/\.bs$/gi, '.brs');
//prepend the staging folder path
outputPath = s`${stagingFolderPath}/${outputPath}`;
return {
file: file,
outputPath: outputPath
};
});
this.plugins.emit('beforeProgramTranspile', this, entries);
const promises = entries.map(async (entry) => {
//skip transpiling typedef files
if (isBrsFile(entry.file) && entry.file.isTypedef) {
return;
}
this.plugins.emit('beforeFileTranspile', entry);
const { file, outputPath } = entry;
const result = file.transpile();
//make sure the full dir path exists
await fsExtra.ensureDir(path.dirname(outputPath));
if (await fsExtra.pathExists(outputPath)) {
throw new Error(`Error while transpiling "${file.pathAbsolute}". A file already exists at "${outputPath}" and will not be overwritten.`);
}
const writeMapPromise = result.map ? fsExtra.writeFile(`${outputPath}.map`, result.map.toString()) : null;
await Promise.all([
fsExtra.writeFile(outputPath, result.code),
writeMapPromise
]);
if (isBrsFile(file) && this.options.emitDefinitions) {
const typedef = file.getTypedef();
const typedefPath = outputPath.replace(/\.brs$/i, '.d.bs');
await fsExtra.writeFile(typedefPath, typedef);
}
this.plugins.emit('afterFileTranspile', entry);
});
//if there's no bslib file already loaded into the program, copy it to the staging directory
if (!this.getFileByPkgPath(bslibAliasedRokuModulesPkgPath) && !this.getFileByPkgPath(s`source/bslib.brs`)) {
promises.push(util.copyBslibToStaging(stagingFolderPath));
}
await Promise.all(promises);
this.plugins.emit('afterProgramTranspile', this, entries);
}
/**
* Find a list of files in the program that have a function with the given name (case INsensitive)
*/
public findFilesForFunction(functionName: string) {
const files = [] as BscFile[];
const lowerFunctionName = functionName.toLowerCase();
//find every file with this function defined
for (const file of Object.values(this.files)) {
if (isBrsFile(file)) {
//TODO handle namespace-relative function calls
//if the file has a function with this name
if (file.parser.references.functionStatementLookup.get(lowerFunctionName) !== undefined) {
files.push(file);
}
}
}
return files;
}
/**
* Find a list of files in the program that have a function with the given name (case INsensitive)
*/
public findFilesForClass(className: string) {
const files = [] as BscFile[];
const lowerClassName = className.toLowerCase();
//find every file with this class defined
for (const file of Object.values(this.files)) {
if (isBrsFile(file)) {
//TODO handle namespace-relative classes
//if the file has a function with this name
if (file.parser.references.classStatementLookup.get(lowerClassName) !== undefined) {
files.push(file);
}
}
}
return files;
}
/**
* Get a map of the manifest information
*/
public getManifest() {
if (!this._manifest) {
//load the manifest file.
//TODO update this to get the manifest from the files array or require it in the options...we shouldn't assume the location of the manifest
let manifestPath = path.join(this.options.rootDir, 'manifest');
let contents: string;
try {
//we only load this manifest once, so do it sync to improve speed downstream
contents = fsExtra.readFileSync(manifestPath, 'utf-8');
this._manifest = parseManifest(contents);
} catch (err) {
this._manifest = new Map();
}
}
return this._manifest;
}
private _manifest: Map<string, ManifestValue>;
public dispose() {
for (let filePath in this.files) {
this.files[filePath].dispose();
}
for (let name in this.scopes) {
this.scopes[name].dispose();
}
this.globalScope.dispose();
this.dependencyGraph.dispose();
}
} | the_stack |
import { MockedResponse } from '@apollo/client/testing'
import { subDays } from 'date-fns'
import { GitRefType } from '@sourcegraph/shared/src/graphql-operations'
import { getDocumentNode } from '@sourcegraph/shared/src/graphql/graphql'
import {
GitCommitAncestorsConnectionFields,
GitRefConnectionFields,
RepositoryGitCommitResult,
RepositoryGitRefsResult,
} from '../../graphql-operations'
import { REPOSITORY_GIT_REFS } from '../GitReference'
import { RevisionsPopoverProps } from './RevisionsPopover'
import { REPOSITORY_GIT_COMMIT } from './RevisionsPopoverCommits'
export const MOCK_PROPS: RevisionsPopoverProps = {
repo: 'some-repo-id',
repoName: 'testorg/testrepo',
defaultBranch: 'main',
currentRev: 'main',
togglePopover: () => null,
showSpeculativeResults: false,
}
const yesterday = subDays(new Date(), 1).toISOString()
const commitPerson = {
displayName: 'display-name',
user: {
username: 'username',
},
}
const generateGitReferenceNodes = (nodeCount: number, variant: GitRefType): GitRefConnectionFields['nodes'] =>
new Array(nodeCount).fill(null).map((_value, index) => {
const id = `${variant}-${index}`
return {
__typename: 'GitRef',
id,
displayName: `${id}-display-name`,
abbrevName: `${id}-abbrev-name`,
name: `refs/heads/${id}`,
url: `/github.com/testorg/testrepo@${id}-display-name`,
target: {
commit: {
author: {
__typename: 'Signature',
date: yesterday,
person: commitPerson,
},
committer: {
__typename: 'Signature',
date: yesterday,
person: commitPerson,
},
behindAhead: null,
},
},
}
})
const generateGitCommitNodes = (nodeCount: number): GitCommitAncestorsConnectionFields['nodes'] =>
new Array(nodeCount).fill(null).map((_value, index) => ({
__typename: 'GitCommit',
id: `git-commit-${index}`,
oid: `git-commit-oid-${index}`,
abbreviatedOID: `git-commit-oid-${index}`,
author: {
person: {
name: commitPerson.displayName,
avatarURL: null,
},
date: yesterday,
},
subject: `Commit ${index}: Hello world`,
}))
const branchesMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
query: getDocumentNode(REPOSITORY_GIT_REFS),
variables: {
query: '',
first: 50,
repo: MOCK_PROPS.repo,
type: GitRefType.GIT_BRANCH,
withBehindAhead: false,
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 100,
nodes: generateGitReferenceNodes(50, GitRefType.GIT_BRANCH),
pageInfo: {
hasNextPage: true,
},
},
},
},
},
}
const additionalBranchesMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
...branchesMock.request,
variables: {
...branchesMock.request.variables,
first: 100,
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 100,
nodes: generateGitReferenceNodes(100, GitRefType.GIT_BRANCH),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
}
const filteredBranchesMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
...branchesMock.request,
variables: {
...branchesMock.request.variables,
query: 'some query',
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 2,
nodes: generateGitReferenceNodes(2, GitRefType.GIT_BRANCH),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
}
const filteredBranchesNoResultsMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
...branchesMock.request,
variables: {
...branchesMock.request.variables,
query: 'some other query',
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 0,
nodes: [],
pageInfo: {
hasNextPage: false,
},
},
},
},
},
}
const tagsMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
query: getDocumentNode(REPOSITORY_GIT_REFS),
variables: {
query: '',
first: 50,
repo: MOCK_PROPS.repo,
type: GitRefType.GIT_TAG,
withBehindAhead: false,
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 100,
nodes: generateGitReferenceNodes(50, GitRefType.GIT_TAG),
pageInfo: {
hasNextPage: true,
},
},
},
},
},
}
const additionalTagsMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
...tagsMock.request,
variables: {
...tagsMock.request.variables,
first: 100,
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 100,
nodes: generateGitReferenceNodes(100, GitRefType.GIT_TAG),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
}
const filteredTagsMock: MockedResponse<RepositoryGitRefsResult> = {
request: {
...tagsMock.request,
variables: {
...tagsMock.request.variables,
query: 'some query',
},
},
result: {
data: {
node: {
__typename: 'Repository',
gitRefs: {
__typename: 'GitRefConnection',
totalCount: 2,
nodes: generateGitReferenceNodes(2, GitRefType.GIT_TAG),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
}
const commitsMock: MockedResponse<RepositoryGitCommitResult> = {
request: {
query: getDocumentNode(REPOSITORY_GIT_COMMIT),
variables: {
query: '',
first: 15,
repo: MOCK_PROPS.repo,
revision: MOCK_PROPS.currentRev,
},
},
result: {
data: {
node: {
__typename: 'Repository',
commit: {
__typename: 'GitCommit',
ancestors: {
__typename: 'GitCommitConnection',
nodes: generateGitCommitNodes(15),
pageInfo: {
hasNextPage: true,
},
},
},
},
},
},
}
const additionalCommitsMock: MockedResponse<RepositoryGitCommitResult> = {
request: {
...commitsMock.request,
variables: {
...commitsMock.request.variables,
first: 30,
},
},
result: {
data: {
node: {
__typename: 'Repository',
commit: {
__typename: 'GitCommit',
ancestors: {
__typename: 'GitCommitConnection',
nodes: generateGitCommitNodes(30),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
},
}
const filteredCommitsMock: MockedResponse<RepositoryGitCommitResult> = {
request: {
...commitsMock.request,
variables: {
...commitsMock.request.variables,
query: 'some query',
},
},
result: {
data: {
node: {
__typename: 'Repository',
commit: {
__typename: 'GitCommit',
ancestors: {
__typename: 'GitCommitConnection',
nodes: generateGitCommitNodes(2),
pageInfo: {
hasNextPage: false,
},
},
},
},
},
},
}
/**
* This mock is to test the case where a speculative revision is provided as context.
* In this case, the code should not error as it is still valid to display 0 results.
*/
const noCommitsMock: MockedResponse<RepositoryGitCommitResult> = {
request: {
...commitsMock.request,
variables: {
...commitsMock.request.variables,
revision: 'non-existent-revision',
},
},
result: {
data: {
node: {
__typename: 'Repository',
commit: null,
},
},
},
}
export const MOCK_REQUESTS = [
branchesMock,
additionalBranchesMock,
filteredBranchesMock,
filteredBranchesNoResultsMock,
tagsMock,
additionalTagsMock,
filteredTagsMock,
commitsMock,
additionalCommitsMock,
filteredCommitsMock,
noCommitsMock,
] | the_stack |
import { Reader, ReaderModel } from '@maxmind/geoip2-node'
import { captureException } from '@sentry/minimal'
import { DateTime } from 'luxon'
import net from 'net'
import { AddressInfo } from 'net'
import fetch from 'node-fetch'
import prettyBytes from 'pretty-bytes'
import { serialize } from 'v8'
import { brotliDecompress } from 'zlib'
import {
MMDB_ATTACHMENT_KEY,
MMDB_ENDPOINT,
MMDB_INTERNAL_SERVER_TIMEOUT_SECONDS,
MMDB_STALE_AGE_DAYS,
MMDB_STATUS_REDIS_KEY,
MMDBRequestStatus,
} from '../../config/mmdb-constants'
import { Hub, PluginAttachmentDB } from '../../types'
import { status } from '../../utils/status'
import { delay } from '../../utils/utils'
import { ServerInstance } from '../pluginsServer'
type MMDBPrepServerInstance = Pick<ServerInstance, 'hub' | 'mmdb'>
enum MMDBFileStatus {
Idle = 'idle',
Fetching = 'fetching',
Unavailable = 'unavailable',
}
/** Check if MMDB is being currently fetched by any other plugin server worker in the cluster. */
async function getMmdbStatus(hub: Hub): Promise<MMDBFileStatus> {
return (await hub.db.redisGet(MMDB_STATUS_REDIS_KEY, MMDBFileStatus.Idle)) as MMDBFileStatus
}
/** Decompress a Brotli-compressed MMDB buffer and open a reader from it. */
async function decompressAndOpenMmdb(brotliContents: Buffer, filename: string): Promise<ReaderModel> {
return await new Promise((resolve, reject) => {
brotliDecompress(brotliContents, (error, result) => {
if (error) {
reject(error)
} else {
status.info(
'🪗',
`Decompressed ${filename} from ${prettyBytes(brotliContents.byteLength)} into ${prettyBytes(
result.byteLength
)}`
)
try {
resolve(Reader.openBuffer(result))
} catch (e) {
reject(e)
}
}
})
})
}
/** Download latest MMDB database, save it, and return its reader. */
async function fetchAndInsertFreshMmdb(hub: Hub): Promise<ReaderModel> {
const { db } = hub
status.info('⏳', 'Downloading GeoLite2 database from PostHog servers...')
const response = await fetch(MMDB_ENDPOINT, { compress: false })
const contentType = response.headers.get('content-type')
const filename = response.headers.get('content-disposition')!.match(/filename="(.+)"/)![1]
const brotliContents = await response.buffer()
status.info('✅', `Downloaded ${filename} of ${prettyBytes(brotliContents.byteLength)}`)
// Insert new attachment
const newAttachmentResults = await db.postgresQuery<PluginAttachmentDB>(
`
INSERT INTO posthog_pluginattachment (
key, content_type, file_name, file_size, contents, plugin_config_id, team_id
) VALUES ($1, $2, $3, $4, $5, NULL, NULL) RETURNING *
`,
[MMDB_ATTACHMENT_KEY, contentType, filename + '.br', brotliContents.byteLength, brotliContents],
'insertGeoIpAttachment'
)
// Ensure that there's no old attachments lingering
await db.postgresQuery(
`
DELETE FROM posthog_pluginattachment WHERE key = $1 AND id != $2
`,
[MMDB_ATTACHMENT_KEY, newAttachmentResults.rows[0].id],
'deleteGeoIpAttachment'
)
status.info('💾', `Saved ${filename} into the database`)
return await decompressAndOpenMmdb(brotliContents, filename)
}
/** Drop-in replacement for fetchAndInsertFreshMmdb that handles multiple worker concurrency better. */
async function distributableFetchAndInsertFreshMmdb(
serverInstance: MMDBPrepServerInstance
): Promise<ReaderModel | null> {
const { hub } = serverInstance
let fetchingStatus = await getMmdbStatus(hub)
if (fetchingStatus === MMDBFileStatus.Unavailable) {
status.info(
'☹️',
'MMDB fetch and insert for GeoIP capabilities is currently unavailable in this PostHog instance - IP location data may be stale or unavailable'
)
return null
}
if (fetchingStatus === MMDBFileStatus.Fetching) {
while (fetchingStatus === MMDBFileStatus.Fetching) {
// Retrying shortly, when perhaps the MMDB has been fetched somewhere else and the attachment is up to date
// Only one plugin server thread out of instances*(workers+1) needs to download the file this way
await delay(200)
fetchingStatus = await getMmdbStatus(hub)
}
return prepareMmdb(serverInstance)
}
// Allow 120 seconds of download until another worker retries
await hub.db.redisSet(MMDB_STATUS_REDIS_KEY, MMDBFileStatus.Fetching, 120)
try {
const mmdb = await fetchAndInsertFreshMmdb(hub)
await hub.db.redisSet(MMDB_STATUS_REDIS_KEY, MMDBFileStatus.Idle)
return mmdb
} catch (e) {
// In case of an error mark the MMDB feature unavailable for an hour
await hub.db.redisSet(MMDB_STATUS_REDIS_KEY, MMDBFileStatus.Unavailable, 120)
status.error('❌', 'An error occurred during MMDB fetch and insert:', e)
return null
}
}
/** Update server MMDB in the background, with no availability interruptions. */
async function backgroundInjectFreshMmdb(serverInstance: MMDBPrepServerInstance): Promise<void> {
const mmdb = await distributableFetchAndInsertFreshMmdb(serverInstance)
if (mmdb) {
serverInstance.mmdb = mmdb
status.info('💉', `Injected fresh ${MMDB_ATTACHMENT_KEY}`)
}
}
/** Ensure that an MMDB is available and return its reader. If needed, update the MMDB in the background. */
export async function prepareMmdb(
serverInstance: MMDBPrepServerInstance,
onlyBackground?: false
): Promise<ReaderModel | null>
export async function prepareMmdb(serverInstance: MMDBPrepServerInstance, onlyBackground: true): Promise<boolean>
export async function prepareMmdb(
serverInstance: MMDBPrepServerInstance,
onlyBackground = false
): Promise<ReaderModel | null | boolean> {
const { hub } = serverInstance
const { db } = hub
const readResults = await db.postgresQuery<PluginAttachmentDB>(
`
SELECT * FROM posthog_pluginattachment
WHERE key = $1 AND plugin_config_id IS NULL AND team_id IS NULL
ORDER BY file_name ASC
`,
[MMDB_ATTACHMENT_KEY],
'fetchGeoIpAttachment'
)
if (!readResults.rowCount) {
status.info('⬇️', `Fetching ${MMDB_ATTACHMENT_KEY} for the first time`)
if (onlyBackground) {
await backgroundInjectFreshMmdb(serverInstance)
return true
} else {
const mmdb = await distributableFetchAndInsertFreshMmdb(serverInstance)
if (!mmdb) {
status.warn('🤒', 'Because of MMDB unavailability, GeoIP plugins will fail in this PostHog instance')
}
return mmdb
}
}
const [mmdbRow] = readResults.rows
if (!mmdbRow.contents) {
throw new Error(`${MMDB_ATTACHMENT_KEY} attachment ID ${mmdbRow.id} has no file contents!`)
}
const mmdbDateStringMatch = mmdbRow.file_name.match(/\d{4}-\d{2}-\d{2}/)
if (!mmdbDateStringMatch) {
throw new Error(
`${MMDB_ATTACHMENT_KEY} attachment ID ${mmdbRow.id} has an invalid filename! ${MMDB_ATTACHMENT_KEY} filename must include an ISO date`
)
}
const mmdbAge = Math.round(-DateTime.fromISO(mmdbDateStringMatch[0]).diffNow().as('days'))
if (mmdbAge > MMDB_STALE_AGE_DAYS) {
status.info(
'🔁',
`${MMDB_ATTACHMENT_KEY} is ${mmdbAge} ${
mmdbAge === 1 ? 'day' : 'days'
} old, which is more than the staleness threshold of ${MMDB_STALE_AGE_DAYS} days, refreshing in the background...`
)
if (onlyBackground) {
await backgroundInjectFreshMmdb(serverInstance)
return true
} else {
void backgroundInjectFreshMmdb(serverInstance)
}
}
if (onlyBackground) {
return false
} else {
return await decompressAndOpenMmdb(mmdbRow.contents, mmdbRow.file_name)
}
}
/** Check for MMDB staleness every 4 hours, if needed perform a no-interruption update. */
export async function performMmdbStalenessCheck(serverInstance: MMDBPrepServerInstance): Promise<void> {
status.info('⏲', 'Performing periodic MMDB staleness check...')
const wasUpdatePerformed = await prepareMmdb(serverInstance, true)
if (wasUpdatePerformed) {
status.info('✅', 'MMDB staleness check completed, update performed')
} else {
status.info('❎', 'MMDB staleness check completed, no update was needed')
}
}
export async function createMmdbServer(serverInstance: MMDBPrepServerInstance): Promise<net.Server> {
status.info('🗺', 'Starting internal MMDB server...')
const mmdbServer = net.createServer((socket) => {
socket.setEncoding('utf8')
let status: MMDBRequestStatus = MMDBRequestStatus.OK
socket.on('data', (partialData) => {
// partialData SHOULD be an IP address string
let responseData: any
if (status === MMDBRequestStatus.OK) {
if (serverInstance.mmdb) {
try {
responseData = serverInstance.mmdb.city(partialData.toString().trim())
} catch (e) {
responseData = null
}
} else {
captureException(new Error(status))
status = MMDBRequestStatus.ServiceUnavailable
}
}
if (status !== MMDBRequestStatus.OK) {
responseData = status
}
socket.write(serialize(responseData ?? null))
})
socket.setTimeout(MMDB_INTERNAL_SERVER_TIMEOUT_SECONDS * 1000).on('timeout', () => {
captureException(new Error(status))
status = MMDBRequestStatus.TimedOut
socket.emit('end')
})
socket.once('end', () => {
if (status !== MMDBRequestStatus.OK) {
socket.write(serialize(status))
}
socket.destroy()
})
})
mmdbServer.on('error', (error) => {
captureException(error)
})
return new Promise((resolve, reject) => {
const rejectTimeout = setTimeout(
() => reject(new Error('Internal MMDB server could not start listening!')),
3000
)
mmdbServer.listen(serverInstance.hub.INTERNAL_MMDB_SERVER_PORT, 'localhost', () => {
const port = (mmdbServer.address() as AddressInfo).port
status.info('👂', `Internal MMDB server listening on port ${port}`)
clearTimeout(rejectTimeout)
resolve(mmdbServer)
})
})
} | the_stack |
import Yasgui from "./";
import TabContextMenu from "./TabContextMenu";
import { hasClass, addClass, removeClass } from "@triply/yasgui-utils";
const sortablejs = require("sortablejs");
require("./TabElements.scss");
export interface TabList {}
export class TabListEl {
private tabList: TabList;
private tabId: string;
private yasgui: Yasgui;
private renameEl?: HTMLInputElement;
private nameEl?: HTMLSpanElement;
public tabEl?: HTMLDivElement;
constructor(yasgui: Yasgui, tabList: TabList, tabId: string) {
this.tabList = tabList;
this.yasgui = yasgui;
this.tabId = tabId;
}
public delete() {
if (this.tabEl) {
this.tabList._tabsListEl?.removeChild(this.tabEl);
delete this.tabList._tabs[this.tabId];
}
}
public startRename() {
if (this.renameEl) {
const tab = this.yasgui.getTab(this.tabId);
if (tab) {
this.renameEl.value = tab.name();
addClass(this.tabEl, "renaming");
this.renameEl.focus();
}
}
}
public active(active: boolean) {
if (!this.tabEl) return;
if (active) {
addClass(this.tabEl, "active");
// add aria-properties
this.tabEl.children[0].setAttribute("aria-selected", "true");
this.tabEl.children[0].setAttribute("tabindex", "0");
} else {
removeClass(this.tabEl, "active");
// remove aria-properties
this.tabEl.children[0].setAttribute("aria-selected", "false");
this.tabEl.children[0].setAttribute("tabindex", "-1");
}
}
public rename(name: string) {
if (this.nameEl) {
this.nameEl.textContent = name;
}
}
public setAsQuerying(querying: boolean) {
if (querying) {
addClass(this.tabEl, "querying");
} else {
removeClass(this.tabEl, "querying");
}
}
public draw(name: string) {
this.tabEl = document.createElement("div");
this.tabEl.setAttribute("role", "presentation");
this.tabEl.ondblclick = () => {
this.startRename();
};
addClass(this.tabEl, "tab");
this.tabEl.addEventListener("keydown", (e: KeyboardEvent) => {
if (e.code === "Delete") handleDeleteTab();
});
const handleDeleteTab = (e?: MouseEvent) => {
e?.preventDefault();
this.yasgui.getTab(this.tabId)?.close();
};
const tabLinkEl = document.createElement("a");
tabLinkEl.setAttribute("role", "tab");
tabLinkEl.href = "#" + this.tabId;
tabLinkEl.id = "tab-" + this.tabId; // use the id for the tabpanel which is tabId to set the actual tab id
tabLinkEl.setAttribute("aria-controls", this.tabId); // respective tabPanel id
tabLinkEl.addEventListener("blur", () => {
if (!this.tabEl) return;
if (this.tabEl.classList.contains("active")) {
tabLinkEl.setAttribute("tabindex", "0");
} else {
tabLinkEl.setAttribute("tabindex", "-1");
}
});
tabLinkEl.addEventListener("focus", () => {
if (!this.tabEl) return;
if (this.tabEl.classList.contains("active")) {
const allTabs = Object.keys(this.tabList._tabs);
const currentTabIndex = allTabs.indexOf(this.tabId);
this.tabList.tabEntryIndex = currentTabIndex;
}
});
// if (this.yasgui.persistentConfig.tabIsActive(this.tabId)) {
// this.yasgui.store.dispatch(selectTab(this.tabId))
// }
tabLinkEl.addEventListener("click", (e) => {
e.preventDefault();
this.yasgui.selectTabId(this.tabId);
});
//tab name
this.nameEl = document.createElement("span");
this.nameEl.textContent = name;
tabLinkEl.appendChild(this.nameEl);
//tab close btn
const closeBtn = document.createElement("div");
closeBtn.innerHTML = "✖";
closeBtn.title = "Close tab";
closeBtn.setAttribute("tabindex", "-1");
closeBtn.setAttribute("aria-hidden", "true");
addClass(closeBtn, "closeTab");
closeBtn.addEventListener("click", handleDeleteTab);
tabLinkEl.appendChild(closeBtn);
const renameEl = (this.renameEl = document.createElement("input"));
renameEl.type = "text";
renameEl.value = name;
renameEl.onkeyup = (event) => {
if (event.key === "Enter") {
this.yasgui.getTab(this.tabId)?.setName(renameEl.value);
removeClass(this.tabEl, "renaming");
}
};
renameEl.onblur = () => {
this.yasgui.getTab(this.tabId)?.setName(renameEl.value);
removeClass(this.tabEl, "renaming");
};
tabLinkEl.appendChild(this.renameEl);
tabLinkEl.oncontextmenu = (ev: MouseEvent) => {
// Close possible old
this.tabList.tabContextMenu?.closeConfigMenu();
this.openTabConfigMenu(ev);
ev.preventDefault();
ev.stopPropagation();
};
this.tabEl.appendChild(tabLinkEl);
//draw loading animation overlay
const loaderEl = document.createElement("div");
addClass(loaderEl, "loader");
this.tabEl.appendChild(loaderEl);
return this.tabEl;
}
private openTabConfigMenu(event: MouseEvent) {
this.tabList.tabContextMenu?.openConfigMenu(this.tabId, this, event);
}
redrawContextMenu() {
this.tabList.tabContextMenu?.redraw();
}
}
export class TabList {
yasgui: Yasgui;
private _selectedTab?: string;
private addTabEl?: HTMLDivElement;
public _tabs: { [tabId: string]: TabListEl } = {};
public _tabsListEl?: HTMLDivElement;
public tabContextMenu?: TabContextMenu;
public tabEntryIndex: number | undefined;
constructor(yasgui: Yasgui) {
this.yasgui = yasgui;
this.registerListeners();
this.tabEntryIndex = this.getActiveIndex();
}
get(tabId: string) {
return this._tabs[tabId];
}
private registerListeners() {
this.yasgui.on("query", (_yasgui, tab) => {
const id = tab.getId();
if (this._tabs[id]) {
this._tabs[id].setAsQuerying(true);
}
});
this.yasgui.on("queryResponse", (_yasgui, tab) => {
const id = tab.getId();
if (this._tabs[id]) {
this._tabs[id].setAsQuerying(false);
}
});
this.yasgui.on("queryAbort", (_yasgui, tab) => {
const id = tab.getId();
if (this._tabs[id]) {
this._tabs[id].setAsQuerying(false);
}
});
}
private getActiveIndex() {
if (!this._selectedTab) return;
const allTabs = Object.keys(this._tabs);
const currentTabIndex = allTabs.indexOf(this._selectedTab);
return currentTabIndex;
}
private handleKeydownArrowKeys = (e: KeyboardEvent) => {
if (e.code === "ArrowLeft" || e.code === "ArrowRight") {
if (!this._tabsListEl) return;
const numOfChildren = this._tabsListEl.childElementCount;
if (typeof this.tabEntryIndex !== "number") return;
const tabEntryDiv = this._tabsListEl.children[this.tabEntryIndex];
// If the current tab does not have active set its tabindex to -1
if (!tabEntryDiv.classList.contains("active")) {
tabEntryDiv.children[0].setAttribute("tabindex", "-1"); // cur tab removed from tab index
}
if (e.code === "ArrowLeft") {
this.tabEntryIndex--;
if (this.tabEntryIndex < 0) {
this.tabEntryIndex = numOfChildren - 1;
}
}
if (e.code === "ArrowRight") {
this.tabEntryIndex++;
if (this.tabEntryIndex >= numOfChildren) {
this.tabEntryIndex = 0;
}
}
const newTabEntryDiv = this._tabsListEl.children[this.tabEntryIndex];
newTabEntryDiv.children[0].setAttribute("tabindex", "0");
(newTabEntryDiv.children[0] as HTMLElement).focus(); // focus on the a tag inside the div for click event
}
};
drawTabsList() {
this._tabsListEl = document.createElement("div");
addClass(this._tabsListEl, "tabsList");
this._tabsListEl.setAttribute("role", "tablist");
this._tabsListEl.addEventListener("keydown", this.handleKeydownArrowKeys);
sortablejs.default.create(this._tabsListEl, {
group: "tabList",
animation: 100,
onUpdate: (_ev: any) => {
const tabs = this.deriveTabOrderFromEls();
this.yasgui.emit("tabOrderChanged", this.yasgui, tabs);
this.yasgui.persistentConfig.setTabOrder(tabs);
},
filter: ".addTab",
onMove: (ev: any, _origEv: any) => {
return hasClass(ev.related, "tab");
},
});
this.addTabEl = document.createElement("div");
this.addTabEl.setAttribute("role", "presentation");
const addTabLink = document.createElement("button");
addTabLink.className = "addTab";
addTabLink.textContent = "+";
addTabLink.title = "Add tab";
addTabLink.setAttribute("aria-label", "Add a new tab");
addTabLink.addEventListener("click", this.handleAddNewTab);
addTabLink.addEventListener("focus", () => {
// sets aria tabEntryIndex to active tab
// this.tabEntryIndex = this.getActiveIndex();
if (!this._tabsListEl) return;
this.tabEntryIndex = this._tabsListEl.childElementCount - 1; // sets tabEntry to add tab, visually makes sense, not sure about accessibility-wise
});
addTabLink.addEventListener("blur", () => {
addTabLink.setAttribute("tabindex", "0"); // maintains tabability
});
this.addTabEl.appendChild(addTabLink);
this._tabsListEl.appendChild(this.addTabEl);
this.tabContextMenu = TabContextMenu.get(
this.yasgui,
this.yasgui.config.contextMenuContainer ? this.yasgui.config.contextMenuContainer : this._tabsListEl
);
return this._tabsListEl;
}
handleAddNewTab = (event: Event) => {
event.preventDefault();
this.yasgui.addTab(true);
};
// drawPanels() {
// this.tabPanelsEl = document.createElement("div");
// return this.tabsListEl;
// }
public addTab(tabId: string, index?: number) {
return this.drawTab(tabId, index);
}
public deriveTabOrderFromEls() {
const tabs: string[] = [];
if (this._tabsListEl) {
for (let i = 0; i < this._tabsListEl.children.length; i++) {
const child = this._tabsListEl.children[i]; //this is the tab div
const anchorTag = child.children[0]; //this one has an href
if (anchorTag) {
const href = (<HTMLAnchorElement>anchorTag).href;
if (href && href.indexOf("#") >= 0) {
tabs.push(href.substr(href.indexOf("#") + 1));
}
}
}
}
return tabs;
}
public selectTab(tabId: string) {
this._selectedTab = tabId;
for (const id in this._tabs) {
this._tabs[id].active(this._selectedTab === id);
}
}
public drawTab(tabId: string, index?: number) {
this._tabs[tabId] = new TabListEl(this.yasgui, this, tabId);
const tabConf = this.yasgui.persistentConfig.getTab(tabId);
if (index !== undefined && index < this.yasgui.persistentConfig.getTabs().length - 1) {
this._tabsListEl?.insertBefore(
this._tabs[tabId].draw(tabConf.name),
this._tabs[this.yasgui.persistentConfig.getTabs()[index + 1]].tabEl || null
);
} else {
this._tabsListEl?.insertBefore(this._tabs[tabId].draw(tabConf.name), this.addTabEl || null);
}
}
public destroy() {
for (const tabId in this._tabs) {
const tab = this._tabs[tabId];
tab.delete();
}
this._tabs = {};
this.tabContextMenu?.destroy();
this._tabsListEl?.remove();
this._tabsListEl = undefined;
}
}
export default TabList; | the_stack |
import * as s3 from '@aws-cdk/aws-s3';
import * as s3_assets from '@aws-cdk/aws-s3-assets';
import { Duration } from '@aws-cdk/core';
import { InitBindOptions, InitElementConfig, InitPlatform } from './private/cfn-init-internal';
/**
* An object that represents reasons to restart an InitService.
*
* Pass an instance of this object to the `InitFile`, `InitCommand`,
* `InitSource` and `InitPackage` objects, and finally to an `InitService`
* itself to cause the actions (files, commands, sources, and packages)
* to trigger a restart of the service.
*
* For example, the following will run a custom command to install Nginx,
* and trigger the nginx service to be restarted after the command has run.
*
* ```ts
* const handle = new ec2.InitServiceRestartHandle();
* ec2.CloudFormationInit.fromElements(
* ec2.InitCommand.shellCommand('/usr/bin/custom-nginx-install.sh', { serviceRestartHandles: [handle] }),
* ec2.InitService.enable('nginx', { serviceRestartHandle: handle }),
* );
* ```
*
* @stability stable
*/
export declare class InitServiceRestartHandle {
private readonly commands;
private readonly files;
private readonly sources;
private readonly packages;
/**
* Add a command key to the restart set
* @internal
*/
_addCommand(key: string): number;
/**
* Add a file key to the restart set
* @internal
*/
_addFile(key: string): number;
/**
* Add a source key to the restart set
* @internal
*/
_addSource(key: string): number;
/**
* Add a package key to the restart set
* @internal
*/
_addPackage(packageType: string, key: string): void;
/**
* Render the restart handles for use in an InitService declaration
* @internal
*/
_renderRestartHandles(): any;
}
/**
* Base class for all CloudFormation Init elements.
*
* @stability stable
*/
export declare abstract class InitElement {
/**
* Returns the init element type for this element.
*
* @stability stable
*/
abstract readonly elementType: string;
/**
* Called when the Init config is being consumed. Renders the CloudFormation
* representation of this init element, and calculates any authentication
* properties needed, if any.
*
* @param options bind options for the element.
* @internal
*/
abstract _bind(options: InitBindOptions): InitElementConfig;
}
/**
* Options for InitCommand.
*
* @stability stable
*/
export interface InitCommandOptions {
/**
* Identifier key for this command.
*
* Commands are executed in lexicographical order of their key names.
*
* @default - Automatically generated based on index
* @stability stable
*/
readonly key?: string;
/**
* Sets environment variables for the command.
*
* This property overwrites, rather than appends, the existing environment.
*
* @default - Use current environment
* @stability stable
*/
readonly env?: Record<string, string>;
/**
* The working directory.
*
* @default - Use default working directory
* @stability stable
*/
readonly cwd?: string;
/**
* Command to determine whether this command should be run.
*
* If the test passes (exits with error code of 0), the command is run.
*
* @default - Always run the command
* @stability stable
*/
readonly testCmd?: string;
/**
* Continue running if this command fails.
*
* @default false
* @stability stable
*/
readonly ignoreErrors?: boolean;
/**
* The duration to wait after a command has finished in case the command causes a reboot.
*
* Set this value to `InitCommandWaitDuration.none()` if you do not want to wait for every command;
* `InitCommandWaitDuration.forever()` directs cfn-init to exit and resume only after the reboot is complete.
*
* For Windows systems only.
*
* @default - 60 seconds
* @stability stable
*/
readonly waitAfterCompletion?: InitCommandWaitDuration;
/**
* Restart the given service(s) after this command has run.
*
* @default - Do not restart any service
* @stability stable
*/
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
/**
* Represents a duration to wait after a command has finished, in case of a reboot (Windows only).
*
* @stability stable
*/
export declare abstract class InitCommandWaitDuration {
/**
* Wait for a specified duration after a command.
*
* @stability stable
*/
static of(duration: Duration): InitCommandWaitDuration;
/**
* Do not wait for this command.
*
* @stability stable
*/
static none(): InitCommandWaitDuration;
/**
* cfn-init will exit and resume only after a reboot.
*
* @stability stable
*/
static forever(): InitCommandWaitDuration;
/**
* Render to a CloudFormation value.
* @internal
*/
abstract _render(): any;
}
/**
* Command to execute on the instance.
*
* @stability stable
*/
export declare class InitCommand extends InitElement {
private readonly command;
private readonly options;
/**
* Run a shell command.
*
* Remember that some characters like `&`, `|`, `;`, `>` etc. have special meaning in a shell and
* need to be preceded by a `\` if you want to treat them as part of a filename.
*
* @stability stable
*/
static shellCommand(shellCommand: string, options?: InitCommandOptions): InitCommand;
/**
* Run a command from an argv array.
*
* You do not need to escape space characters or enclose command parameters in quotes.
*
* @stability stable
*/
static argvCommand(argv: string[], options?: InitCommandOptions): InitCommand;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
private constructor();
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
}
/**
* Options for InitFile.
*
* @stability stable
*/
export interface InitFileOptions {
/**
* The name of the owning group for this file.
*
* Not supported for Windows systems.
*
* @default 'root'
* @stability stable
*/
readonly group?: string;
/**
* The name of the owning user for this file.
*
* Not supported for Windows systems.
*
* @default 'root'
* @stability stable
*/
readonly owner?: string;
/**
* A six-digit octal value representing the mode for this file.
*
* Use the first three digits for symlinks and the last three digits for
* setting permissions. To create a symlink, specify 120xxx, where xxx
* defines the permissions of the target file. To specify permissions for a
* file, use the last three digits, such as 000644.
*
* Not supported for Windows systems.
*
* @default '000644'
* @stability stable
*/
readonly mode?: string;
/**
* True if the inlined content (from a string or file) should be treated as base64 encoded.
*
* Only applicable for inlined string and file content.
*
* @default false
* @stability stable
*/
readonly base64Encoded?: boolean;
/**
* Restart the given service after this file has been written.
*
* @default - Do not restart any service
* @stability stable
*/
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
/**
* Additional options for creating an InitFile from an asset.
*
* @stability stable
*/
export interface InitFileAssetOptions extends InitFileOptions, s3_assets.AssetOptions {
}
/**
* Create files on the EC2 instance.
*
* @stability stable
*/
export declare abstract class InitFile extends InitElement {
private readonly fileName;
private readonly options;
/**
* Use a literal string as the file content.
*
* @stability stable
*/
static fromString(fileName: string, content: string, options?: InitFileOptions): InitFile;
/**
* Write a symlink with the given symlink target.
*
* @stability stable
*/
static symlink(fileName: string, target: string, options?: InitFileOptions): InitFile;
/**
* Use a JSON-compatible object as the file content, write it to a JSON file.
*
* May contain tokens.
*
* @stability stable
*/
static fromObject(fileName: string, obj: Record<string, any>, options?: InitFileOptions): InitFile;
/**
* Read a file from disk and use its contents.
*
* The file will be embedded in the template, so care should be taken to not
* exceed the template size.
*
* If options.base64encoded is set to true, this will base64-encode the file's contents.
*
* @stability stable
*/
static fromFileInline(targetFileName: string, sourceFileName: string, options?: InitFileOptions): InitFile;
/**
* Download from a URL at instance startup time.
*
* @stability stable
*/
static fromUrl(fileName: string, url: string, options?: InitFileOptions): InitFile;
/**
* Download a file from an S3 bucket at instance startup time.
*
* @stability stable
*/
static fromS3Object(fileName: string, bucket: s3.IBucket, key: string, options?: InitFileOptions): InitFile;
/**
* Create an asset from the given file.
*
* This is appropriate for files that are too large to embed into the template.
*
* @stability stable
*/
static fromAsset(targetFileName: string, path: string, options?: InitFileAssetOptions): InitFile;
/**
* Use a file from an asset at instance startup time.
*
* @stability stable
*/
static fromExistingAsset(targetFileName: string, asset: s3_assets.Asset, options?: InitFileOptions): InitFile;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
/**
* @stability stable
*/
protected constructor(fileName: string, options: InitFileOptions);
/** @internal */
_bind(bindOptions: InitBindOptions): InitElementConfig;
/**
* Perform the actual bind and render
*
* This is in a second method so the superclass can guarantee that
* the common work of registering into serviceHandles cannot be forgotten.
* @internal
*/
protected abstract _doBind(options: InitBindOptions): InitElementConfig;
/**
* Render the standard config block, given content vars
* @internal
*/
protected _standardConfig(fileOptions: InitFileOptions, platform: InitPlatform, contentVars: Record<string, any>): Record<string, any>;
}
/**
* Create Linux/UNIX groups and assign group IDs.
*
* Not supported for Windows systems.
*
* @stability stable
*/
export declare class InitGroup extends InitElement {
private groupName;
private groupId?;
/**
* Create a group from its name, and optionally, group id.
*
* @stability stable
*/
static fromName(groupName: string, groupId?: number): InitGroup;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
/**
* @stability stable
*/
protected constructor(groupName: string, groupId?: number | undefined);
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
}
/**
* Optional parameters used when creating a user.
*
* @stability stable
*/
export interface InitUserOptions {
/**
* The user's home directory.
*
* @default assigned by the OS
* @stability stable
*/
readonly homeDir?: string;
/**
* A user ID.
*
* The creation process fails if the user name exists with a different user ID.
* If the user ID is already assigned to an existing user the operating system may
* reject the creation request.
*
* @default assigned by the OS
* @stability stable
*/
readonly userId?: number;
/**
* A list of group names.
*
* The user will be added to each group in the list.
*
* @default the user is not associated with any groups.
* @stability stable
*/
readonly groups?: string[];
}
/**
* Create Linux/UNIX users and to assign user IDs.
*
* Users are created as non-interactive system users with a shell of
* /sbin/nologin. This is by design and cannot be modified.
*
* Not supported for Windows systems.
*
* @stability stable
*/
export declare class InitUser extends InitElement {
private readonly userName;
private readonly userOptions;
/**
* Create a user from user name.
*
* @stability stable
*/
static fromName(userName: string, options?: InitUserOptions): InitUser;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
/**
* @stability stable
*/
protected constructor(userName: string, userOptions: InitUserOptions);
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
}
/**
* Options for InitPackage.rpm/InitPackage.msi.
*
* @stability stable
*/
export interface LocationPackageOptions {
/**
* Identifier key for this package.
*
* You can use this to order package installs.
*
* @default - Automatically generated
* @stability stable
*/
readonly key?: string;
/**
* Restart the given service after this command has run.
*
* @default - Do not restart any service
* @stability stable
*/
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
/**
* Options for InitPackage.yum/apt/rubyGem/python.
*
* @stability stable
*/
export interface NamedPackageOptions {
/**
* Specify the versions to install.
*
* @default - Install the latest version
* @stability stable
*/
readonly version?: string[];
/**
* Restart the given services after this command has run.
*
* @default - Do not restart any service
* @stability stable
*/
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
/**
* A package to be installed during cfn-init time.
*
* @stability stable
*/
export declare class InitPackage extends InitElement {
private readonly type;
private readonly versions;
private readonly packageName?;
private readonly serviceHandles?;
/**
* Install an RPM from an HTTP URL or a location on disk.
*
* @stability stable
*/
static rpm(location: string, options?: LocationPackageOptions): InitPackage;
/**
* Install a package using Yum.
*
* @stability stable
*/
static yum(packageName: string, options?: NamedPackageOptions): InitPackage;
/**
* Install a package from RubyGems.
*
* @stability stable
*/
static rubyGem(gemName: string, options?: NamedPackageOptions): InitPackage;
/**
* Install a package from PyPI.
*
* @stability stable
*/
static python(packageName: string, options?: NamedPackageOptions): InitPackage;
/**
* Install a package using APT.
*
* @stability stable
*/
static apt(packageName: string, options?: NamedPackageOptions): InitPackage;
/**
* Install an MSI package from an HTTP URL or a location on disk.
*
* @stability stable
*/
static msi(location: string, options?: LocationPackageOptions): InitPackage;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
/**
* @stability stable
*/
protected constructor(type: string, versions: string[], packageName?: string | undefined, serviceHandles?: InitServiceRestartHandle[] | undefined);
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
/**
* @stability stable
*/
protected renderPackageVersions(): any;
}
/**
* Options for an InitService.
*
* @stability stable
*/
export interface InitServiceOptions {
/**
* Enable or disable this service.
*
* Set to true to ensure that the service will be started automatically upon boot.
*
* Set to false to ensure that the service will not be started automatically upon boot.
*
* @default - true if used in `InitService.enable()`, no change to service
* state if used in `InitService.fromOptions()`.
* @stability stable
*/
readonly enabled?: boolean;
/**
* Make sure this service is running or not running after cfn-init finishes.
*
* Set to true to ensure that the service is running after cfn-init finishes.
*
* Set to false to ensure that the service is not running after cfn-init finishes.
*
* @default - same value as `enabled`.
* @stability stable
*/
readonly ensureRunning?: boolean;
/**
* Restart service when the actions registered into the restartHandle have been performed.
*
* Register actions into the restartHandle by passing it to `InitFile`, `InitCommand`,
* `InitPackage` and `InitSource` objects.
*
* @default - No files trigger restart
* @stability stable
*/
readonly serviceRestartHandle?: InitServiceRestartHandle;
}
/**
* A services that be enabled, disabled or restarted when the instance is launched.
*
* @stability stable
*/
export declare class InitService extends InitElement {
private readonly serviceName;
private readonly serviceOptions;
/**
* Enable and start the given service, optionally restarting it.
*
* @stability stable
*/
static enable(serviceName: string, options?: InitServiceOptions): InitService;
/**
* Disable and stop the given service.
*
* @stability stable
*/
static disable(serviceName: string): InitService;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
private constructor();
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
}
/**
* Additional options for an InitSource.
*
* @stability stable
*/
export interface InitSourceOptions {
/**
* Restart the given services after this archive has been extracted.
*
* @default - Do not restart any service
* @stability stable
*/
readonly serviceRestartHandles?: InitServiceRestartHandle[];
}
/**
* Additional options for an InitSource that builds an asset from local files.
*
* @stability stable
*/
export interface InitSourceAssetOptions extends InitSourceOptions, s3_assets.AssetOptions {
}
/**
* Extract an archive into a directory.
*
* @stability stable
*/
export declare abstract class InitSource extends InitElement {
private readonly targetDirectory;
private readonly serviceHandles?;
/**
* Retrieve a URL and extract it into the given directory.
*
* @stability stable
*/
static fromUrl(targetDirectory: string, url: string, options?: InitSourceOptions): InitSource;
/**
* Extract a GitHub branch into a given directory.
*
* @stability stable
*/
static fromGitHub(targetDirectory: string, owner: string, repo: string, refSpec?: string, options?: InitSourceOptions): InitSource;
/**
* Extract an archive stored in an S3 bucket into the given directory.
*
* @stability stable
*/
static fromS3Object(targetDirectory: string, bucket: s3.IBucket, key: string, options?: InitSourceOptions): InitSource;
/**
* Create an InitSource from an asset created from the given path.
*
* @stability stable
*/
static fromAsset(targetDirectory: string, path: string, options?: InitSourceAssetOptions): InitSource;
/**
* Extract a directory from an existing directory asset.
*
* @stability stable
*/
static fromExistingAsset(targetDirectory: string, asset: s3_assets.Asset, options?: InitSourceOptions): InitSource;
/**
* Returns the init element type for this element.
*
* @stability stable
*/
readonly elementType: string;
/**
* @stability stable
*/
protected constructor(targetDirectory: string, serviceHandles?: InitServiceRestartHandle[] | undefined);
/** @internal */
_bind(options: InitBindOptions): InitElementConfig;
/**
* Perform the actual bind and render
*
* This is in a second method so the superclass can guarantee that
* the common work of registering into serviceHandles cannot be forgotten.
* @internal
*/
protected abstract _doBind(options: InitBindOptions): InitElementConfig;
} | the_stack |
var playingBoardSize = 500;
var height = playingBoardSize + 200;
var width = playingBoardSize + (200 * (window.innerWidth / window.innerHeight));// additional for camera extend - fullsize of board
var canvas = <HTMLCanvasElement>document.getElementById("viewport");
var ResourcesText = <HTMLElement>document.getElementById('Resources');
var HealthGauge = <HTMLElement>document.getElementById('healthGauge');
var levelScreen = <HTMLElement>document.getElementById('nextLevelScreen');
var StatusText = <HTMLElement>document.getElementById('dir');
var pausedMessage = <HTMLElement>document.getElementById('pauseScreen');
// Jquery style
var btnFacebook = $("#btnFacebook");
var btnGoogle = $("#btnGoogle");
var btnMicrosoft = $("#btnMicrosoft");
var modal = $("#login-modal");
var divLoged = $("#loged");
var divLogin = $("#login");
var btnStart = $("#btnStartNewGame");
var btnLogout = $("#btnLogout");
var container = $("#container");
var gameViewport = $("#gameViewport");
// not migrated
declare var GameSound: any;
// Babylon engine / scene
var engine: BABYLON.Engine;
var scene: BABYLON.Scene;
var camera: BABYLON.ArcRotateCamera;
var playerGraphic: BABYLON.AbstractMesh;
var particleTexture: BABYLON.Texture;
var radar: BABYLON.Mesh;
var enemywing: BABYLON.Mesh;
var enemywing2: BABYLON.Mesh;
var wingconnector: BABYLON.Mesh;
var wingconnector2: BABYLON.Mesh;
var enemyship: BABYLON.Mesh;
var bulletobj: BABYLON.Mesh;
var bulletobj2: BABYLON.Mesh;
var bulletobj3: BABYLON.Mesh;
var bulletpart: BABYLON.ParticleSystem;
var bulletpart2: BABYLON.ParticleSystem;
var rock: BABYLON.AbstractMesh;
var rock2: BABYLON.AbstractMesh;
var mine: BABYLON.AbstractMesh;
// player shipt
var playerShip: LightSpeed.PlayerShip;
// Pausing game state
var pause = false;
// keys
var up, down, left, right = false;
// is loaded
var loaded = false;
// Ennemies
var enemies: Array<LightSpeed.BaseEnemy> = new Array<LightSpeed.BaseEnemy>();
// time
var time = 0;
// current game level;
var gameLevel: number;
var adjmovement: number;
var nextlvlneed: number;
// babylon leaderboard
var applicationUrl = "https://babylonjs.azure-mobile.net/";
var applicationKey = "dHfEVuqRtCczLCvSdtmAdfVlrWpgfU55";
var gameId = 1;
var leaderBoard = new BABYLON.LeaderBoard.Client(applicationUrl, applicationKey, gameId);
var player: LightSpeed.Player;
var disconnect = (callback?: any) => {
gameViewport.css('z-index', '-1');
container.show();
leaderBoard.logout();
if (!divLoged.hasClass('hidden'))
divLoged.addClass('hidden');
if (divLogin.hasClass('hidden'))
divLogin.removeClass('hidden');
if (callback != undefined)
callback();
}
// Login player. Get Character profile form Leaderboard
var login = (provider: string, callback: any) => {
leaderBoard.loginWithProfile(provider, (chars) => {
if (chars && chars.length > 0) {
player = <LightSpeed.Player>chars[0];
if (player.shipLevel == undefined || player.shipLevel <= 0)
player.shipLevel = 0;
if (player.highScore == null || player.highScore <= 0)
player.highScore = 0;
if (player.levelPoints == null || player.levelPoints <= 0)
player.levelPoints = 0;
if (player.lastLevel == null || player.lastLevel <= 0)
player.lastLevel = 1;
if (player.timePlayed == null || player.timePlayed <= 0)
player.timePlayed = 0;
if (player.currentLives == null || player.currentLives <= 0)
player.currentLives = 3;
if (player.levelMax == null || player.levelMax <= 0)
player.levelMax = 0;
leaderBoard.addOrUpdateCharacter(player,
(c) => {
player = c[0];
callback();
},
(error) => {
console.error(error);
});
}
},
(error) => {
console.error(error);
});
}
var initStartScreen = () => {
if (divLoged.hasClass('hidden'))
divLoged.removeClass('hidden');
if (!divLogin.hasClass('hidden'))
divLogin.addClass('hidden');
var img = $("#sImgChar");
if (player && player.imageUrl != null) {
img.attr('src', player.imageUrl);
img.show();
}
$('#sLastPlayedTime').html('Last Played : ' + player.updatedDate.toDateString());
$('#sLastSessionLevel').html('Last Session level : ' + player.lastLevel);
$('#sCharacterHighScore').html('High Score : ' + player.highScore);
divLoged.show();
modal.modal('hide')
}
// Login action
btnFacebook.click(() => {
login('facebook', () => {
initStartScreen();
});
});
btnGoogle.click(() => {
login('google', () => {
initStartScreen();
});
});
btnMicrosoft.click(() => {
login('microsoftaccount', () => {
initStartScreen();
});
});
// Starting a new game
btnStart.click(() => {
gameViewport.css('z-index', '1');
container.hide();
var img = $("#imgChar");
if (player && player.imageUrl != null) {
img.attr('src', player.imageUrl);
img.show();
}
startGame();
});
btnLogout.click(() => {
disconnect();
});
gameViewport.css('z-index', '-1');
// Get the current user
var u = leaderBoard.getCurrentUser();
// if already logged
if (u != null && u.userId != null) {
divLoged.removeClass('hidden');
var profile = leaderBoard.getLoginProvider();
leaderBoard.getCharacterFromProfile(profile.source,
(chars) => {
if (chars && chars.length > 0) {
player = <LightSpeed.Player>chars[0];
initStartScreen();
divLoged.show();
modal.modal('hide')
}
},
(error) => {
console.error(error);
});
} else {
divLogin.removeClass('hidden');
}
var loader = new LightSpeed.Loader();
loader.load(canvas, (r) => {
// Get results
scene = r.scene;
engine = r.engine;
camera = r.camera;
playerGraphic = r.playerGraphic;
particleTexture = r.particleTexture;
radar = r.radar;
enemyship = r.enemyship;
bulletobj = r.bulletobj;
bulletobj2 = r.bulletobj2;
bulletobj3 = r.bulletobj3;
rock = r.rock;
rock2 = r.rock2;
mine = r.mine;
playerShip = new LightSpeed.PlayerShip(scene, camera, playerGraphic, particleTexture);
playerShip.resetOccured = () => {
$('#lightSpeedReminder').hide();
}
// ship speed gauge change
playerShip.lightSpeedGaugeChanged = (val) => {
var v = $('#lightSpeedGauge').width();
$('#lightSpeedGauge').width(val);
}
// ship health change
playerShip.healthGaugeChanged = (val) => {
var v = $('#healthGauge').width();
$('#healthGauge').width(val);
}
// ship light speed ready
playerShip.lightSpeedReadyOccured = () => {
GameSound.play("lightspeedready");
$('#lightSpeedReady').show();
$('#lightSpeedReady').css('opacity', '1');
$('#lightSpeedReminder').show();
$('#lightSpeedReminder').css('opacity', '1');
}
// ship explode
// LeaderBoard decrement lives
playerShip.explodeOccured = () => {
player.currentLives -= 1;
if (player.kills > player.experience)
player.experience = player.kills;
leaderBoard.addOrUpdateCharacter(player);
$('#deadScreen').show();
}
// ship jumpt to next level;
playerShip.jumpToLightSpeedEnd = () => {
player.lastLevel = gameLevel;
gameLevel += 1;
player.levelMax = Math.max(gameLevel, player.levelMax);
leaderBoard.addOrUpdateCharacter(player);
sceneReset();
}
playerShip.pointsChanged = (levelPoints, gamePoints) => {
$('#levelPoints').html('Points to next level : ' + playerShip.levelPoints.toString() + " / " + nextlvlneed.toString());
$('#gamePoints').html('Score : ' + playerShip.gamePoints.toString());
player.levelPoints = levelPoints;
player.highScore = Math.max(player.highScore, gamePoints);
}
// player ship level change
playerShip.shipLevelChanged = (lvl, speed, health, bulletDamage) => {
player.shipLevel = lvl;
// get next level need points
nextlvlneed = levelingDefs[playerShip.shipLevel + 1].need;
$('#shipLevel').html("Current Ship Level:" + lvl);
$('#levelUp').show();
$('#levelUp').css('opacity', '1');
}
var beforeRender = function () {
time = time + (1 / BABYLON.Tools.GetFps());
// StatusText.innerHTML = scene.getActiveParticles();// BABYLON.Tools.GetFps().toFixed() + " FPS";
adjmovement = scene.getAnimationRatio();
if (loader.isLoaded == true && pause == false) {
// update playerShip
playerShip.update(up, down, left, right, adjmovement, height, width, playingBoardSize);
// making level up message desappear if actually shown
var op = +$('#levelUp').css('opacity');
if (op > 0)
$('#levelUp').css('opacity', (op - 0.01).toString());
op = +$('#lightSpeedReady').css('opacity');
if (op > 0)
$('#lightSpeedReady').css('opacity', (op - 0.01).toString());
/////////check for collisions/////////////////////
var index = enemies.length;
while (index--) {
var enemy = enemies[index];
// an ennemy is dead and we must dispose it (or respawn it
if (!enemy.canRespawn && enemy.health <= 0) {
delete enemies[index];
enemies.splice(index, 1);
enemy.dispose();
continue;
}
if (enemy.canRespawn && enemy.health <= 0) {
enemy.respawn();
continue;
}
// Enemy is alive
enemy.update();
if (playerShip.canMove == true) {
var bulletCount = playerShip.bullets.length;
while (bulletCount--) {
// check enemy visibility and bullet visibility
if (enemy.enemyMesh.isVisible == true && playerShip.bullets[bulletCount].graphic.isVisible == true) {
// check intersection
if (enemy.enemyMesh.intersectsMesh(playerShip.bullets[bulletCount].graphic, true)) {
// get damage on enemy
enemy.getDamage(playerShip.bullets[bulletCount].damage);
// bullet desapear
playerShip.bullets[bulletCount].graphic.isVisible = false;
playerShip.bullets[bulletCount].graphic.dispose();
// clean bullet from bullets collection
playerShip.bullets.splice(bulletCount, 1);
}
}
}
// check collision beetween player and enemy
if (playerShip.boundingBox.intersectsMesh(enemy.enemyMesh, true) == true) {
if (enemy.enemyMesh.isVisible == true) {
// player get damages from enemy max health
playerShip.getDamage(enemy.maxHealth / 2);
// enemy get damages from player max health
enemy.getDamage(playerShip.maxHealth / 2);
}
}
}
}
}
}
scene.registerBeforeRender(() => beforeRender());
engine.runRenderLoop(() => {
//StatusText.innerHTML = scene.getActiveParticles();// BABYLON.Tools.GetFps().toFixed() + " FPS";
scene.render();
});
}, () => {
//startDisplay.innerHTML = "<div class='alert'>Sorry, your browser exudes awesomeness.<br> Just not awesome enough to play this game.<br> Why don't you try IE 11, Firefox or Google Chrome instead.</div>";
//startDisplay.style.display = "block";
//loadingMessage.style.display = "none";
});
var sceneReset = function () {
if (enemies && enemies.length > 0) {
var xEnemy = enemies.length;
while (xEnemy--) {
enemies[xEnemy].dispose();
}
}
enemies = LightSpeed.BaseEnemy.SpawnEnemies(gameLevel);
camera.radius = 500;
camera.target = playerShip.cameraFollower.position;
// get next level need points
nextlvlneed = levelingDefs[playerShip.shipLevel + 1].need;
// hiding dead screen
$('#deadScreen').hide();
// hiding speed ready message. set opacity to be able to desaspear with opacity animation
$('#lightSpeedReady').hide();
$('#lightSpeedReady').css('opacity', '1');
// set light speed gauge to 0;
$('#lightSpeedGauge').width(0);
// hiding reminder of light speed in speed gauge
$('#lightSpeedReminder').hide();
// hiding level up message and set opacity to be able to make it desapear
$('#levelUp').css('opacity', '1');
$('#levelUp').hide();
// set informations
$('#gameLevel').html("Current Game Level :" + gameLevel.toString());
$('#shipLevel').html("Current Ship Level :" + player.shipLevel.toString());
$('#characterHighScore').html('High Score ' + player.highScore.toString());
$('#levelPoints').html('Points to next level : ' + playerShip.levelPoints.toString() + " / " + nextlvlneed.toString());
$('#gamePoints').html('Score : ' + player.levelPoints.toString() + " / " + nextlvlneed.toString());
playerShip.reset();
};
var startGame = function () {
gameLevel = 1;
playerShip.gamePoints = 0;
sceneReset();
loaded = true;
};
document.onkeydown = handleKeyDown;
document.onkeyup = handleKeyUp;
function handleKeyUp(event) {
if (loaded) {
if (event.keyCode == 68 || event.keyCode == 39) {
right = false;
}
if (event.keyCode == 65 || event.keyCode == 37) {
left = false;
}
if (event.keyCode == 87 || event.keyCode == 38) {
up = false;
}
if (event.keyCode == 83 || event.keyCode == 40) {
down = false;
}
}
}
function handleKeyDown(event) {
if (loaded) {
if (event.keyCode == 68 || event.keyCode == 39) {
if (loaded == true) {
right = true;
}
}
if (event.keyCode == 65 || event.keyCode == 37) {
if (loaded == true) {
left = true;
}
}
if (event.keyCode == 87 || event.keyCode == 38) {
if (loaded == true) {
up = true;
}
}
if (event.keyCode == 83 || event.keyCode == 40) {
if (loaded == true) {
down = true;
}
}
if (event.keyCode == 82) {
playerShip.jumpToLightSpeed();
}
if (event.keyCode == 80) {
PauseGame(!pause)
}
}
}
// Resize
window.addEventListener("resize", function () {
engine.resize();
});
window.onblur = function () {
//if (loaded) {
// PauseGame(true)
//}
};
function PauseGame(status) {
if (playerShip.canMove == true) {
pause = status;
if (pause) { pausedMessage.style.display = "block"; }
else if (!pause) { pausedMessage.style.display = "none"; }
}
} | the_stack |
import {
FeaturesDataSource,
MapViewFeature,
MapViewMultiPointFeature,
MapViewPolygonFeature
} from "@here/harp-features-datasource";
import { GeoBox, GeoCoordinates, GeoPolygon, mercatorProjection } from "@here/harp-geoutils";
import { geoCoordLikeToGeoPointLike } from "@here/harp-geoutils/lib/coordinates/GeoCoordLike";
import { MapControls, MapControlsUI } from "@here/harp-map-controls";
import { BoundsGenerator, CameraUtils, CopyrightElementHandler, MapView } from "@here/harp-mapview";
import { VectorTileDataSource } from "@here/harp-vectortile-datasource";
import { GUI, GUIController } from "dat.gui";
import { apikey } from "../config";
export namespace BoundsExample {
// Create a new MapView for the HTMLCanvasElement of the given id.
function initMapView(id: string): MapView {
const canvas = document.getElementById(id) as HTMLCanvasElement;
// Look at BERLIN
const BERLIN = new GeoCoordinates(52.5186234, 13.373993);
const map = new MapView({
canvas,
projection: mercatorProjection,
tileWrappingEnabled: false,
theme: {
extends: "resources/berlin_tilezen_night_reduced.json",
styles: {
geojson: [
{
when: [
"all",
["==", ["geometry-type"], "Polygon"],
["==", ["get", "name"], "bounds"]
],
technique: "fill",
renderOrder: 10003,
attr: {
color: ["get", "color"], // "#77ccff",
opacity: 0.2,
lineWidth: 1,
lineColor: "#ff0000",
enabled: true
}
},
{
when: [
"all",
["==", ["geometry-type"], "Polygon"],
["==", ["get", "name"], "bbox"]
],
technique: "solid-line",
renderOrder: 10005,
attr: {
color: "#0ff",
lineWidth: "5px"
}
},
{
when: [
"all",
["==", ["geometry-type"], "Point"],
["==", ["get", "name"], "bbox"]
],
technique: "circles",
renderOrder: 10006,
attr: {
color: "#00f",
size: 20
}
},
{
when: "$geometryType == 'point'",
technique: "circles",
renderOrder: 10004,
attr: {
color: "#f0f",
size: 10
}
}
]
}
},
target: BERLIN,
zoomLevel: 8,
tilt: 45,
heading: -80
});
map.renderLabels = false;
CopyrightElementHandler.install("copyrightNotice", map);
const mapControls = new MapControls(map);
mapControls.maxTiltAngle = 180;
const ui = new MapControlsUI(mapControls, { zoomLevel: "input", projectionSwitch: true });
canvas.parentElement!.appendChild(ui.domElement);
map.resize(window.innerWidth, window.innerHeight);
window.addEventListener("resize", () => {
map.resize(window.innerWidth, window.innerHeight);
});
addVectorTileDataSource(map);
return map;
}
let viewpoly: MapViewPolygonFeature;
let cornerpoints: MapViewMultiPointFeature;
let bboxFeature: MapViewMultiPointFeature;
let bboxPolygonFeature: MapViewPolygonFeature;
function updateBoundsFeatures(polygon: GeoPolygon, featuresDataSource: FeaturesDataSource) {
const corners = polygon.coordinates;
if (corners && corners.length > 0) {
//add starting vertex to the end to close the polygon
corners.push((corners[0] as GeoCoordinates).clone());
}
//convert the array to an array usable for the MapViewPolygonFeature
const polygonArray: number[][][] = [];
const pointArray: number[][] = [];
polygonArray.push(pointArray);
corners.forEach(corner => {
if (corner === null) {
return;
}
pointArray.push(geoCoordLikeToGeoPointLike(corner) as number[]);
});
if (viewpoly) {
//remove the former polygon
featuresDataSource?.remove(viewpoly);
}
//add the new polygon
viewpoly = new MapViewPolygonFeature(polygonArray, {
name: "bounds",
height: 10000,
color: "#ffff00"
});
featuresDataSource?.add(viewpoly);
// add circles at the corner points
if (cornerpoints) {
featuresDataSource?.remove(cornerpoints);
}
cornerpoints = new MapViewMultiPointFeature(pointArray, {
name: "cornerpoints"
});
featuresDataSource?.add(cornerpoints);
}
function updateBoundingBoxFeatures(
geoPolygon: GeoPolygon,
featuresDataSource: FeaturesDataSource,
isVisible: boolean = true
) {
if (bboxFeature) {
featuresDataSource?.remove(bboxFeature);
}
if (bboxPolygonFeature) {
featuresDataSource?.remove(bboxPolygonFeature);
}
if (isVisible) {
const geoBBox = geoPolygon.getGeoBoundingBox() as GeoBox;
const geoBBoxCornerArray: number[][] = [];
[
new GeoCoordinates(geoBBox?.south, geoBBox?.west, 70),
new GeoCoordinates(geoBBox?.south, geoBBox?.east, 70),
new GeoCoordinates(geoBBox?.north, geoBBox?.east, 70),
new GeoCoordinates(geoBBox?.north, geoBBox?.west, 70),
new GeoCoordinates(geoBBox?.south, geoBBox?.west, 70)
].forEach(point => {
if (!point) {
return;
}
geoBBoxCornerArray.push([
point.longitude,
point.latitude,
point.altitude as number
]);
});
const centroid = geoPolygon.getCentroid() as GeoCoordinates;
bboxFeature = new MapViewMultiPointFeature(
[[centroid.longitude, centroid.latitude, 70]].concat(geoBBoxCornerArray),
{
name: "bbox"
}
);
featuresDataSource?.add(bboxFeature);
bboxPolygonFeature = new MapViewPolygonFeature([geoBBoxCornerArray], {
name: "bbox"
});
featuresDataSource?.add(bboxPolygonFeature);
}
}
function addVectorTileDataSource(map: MapView) {
const omvDataSource = new VectorTileDataSource({
baseUrl: "https://vector.hereapi.com/v2/vectortiles/base/mc",
authenticationCode: apikey
});
map.addDataSource(omvDataSource);
return map;
}
function addFeaturesDataSource(map: MapView, featureList: MapViewFeature[]) {
const featuresDataSource = new FeaturesDataSource({
name: "featureDataSource",
styleSetName: "geojson",
features: featureList,
gatherFeatureAttributes: true
});
map.addDataSource(featuresDataSource);
return featuresDataSource;
}
function addButton(gui: GUI, name: string, callback: () => void): GUIController {
return gui.add(
{
[name]: callback
},
name
);
}
function initGUI(
map: MapView,
boundsGenerator: BoundsGenerator,
viewBoundsDataSource: FeaturesDataSource
) {
const gui = new GUI();
gui.width = 350;
let bounds: GeoPolygon | undefined;
const options = {
bbox: false,
wrap: false,
ppalPointX: 0,
ppalPointY: 0
};
addButton(gui, "Draw view bounds polygon", () => {
// Generate the the bounds of the current view and add them as a feature
bounds = boundsGenerator.generate();
if (bounds) {
updateBoundsFeatures(bounds, viewBoundsDataSource);
updateBoundingBoxFeatures(bounds, viewBoundsDataSource, options.bbox);
}
});
addButton(gui, "Look at bounds bbox", () => {
map.lookAt({ bounds: bounds?.getGeoBoundingBox() });
});
addButton(gui, "Look at bounds polygon", () => {
map.lookAt({ bounds });
});
gui.add(options, "bbox")
.onChange((enabled: boolean) => {
if (bounds) {
updateBoundingBoxFeatures(bounds, viewBoundsDataSource, enabled);
}
})
.name("Show polygon's bbox");
gui.add(options, "wrap")
.onChange((enabled: boolean) => {
map.tileWrappingEnabled = enabled;
map.update();
})
.name("Repeat world (planar)");
const ppFolder = gui.addFolder("Principal point (NDC)");
ppFolder
.add(options, "ppalPointX", -1, 1, 0.1)
.onChange((x: number) => {
CameraUtils.setPrincipalPoint(map.camera, {
x,
y: CameraUtils.getPrincipalPoint(map.camera).y
});
map.update();
})
.name("x");
ppFolder
.add(options, "ppalPointY", -1, 1, 0.1)
.onChange((y: number) => {
CameraUtils.setPrincipalPoint(map.camera, {
x: CameraUtils.getPrincipalPoint(map.camera).x,
y
});
map.update();
})
.name("y");
addButton(gui, "Log camera settings", () => {
// eslint-disable-next-line no-console
console.log(
"target: ",
map.target,
" tilt: ",
map.tilt,
" heading: ",
map.heading,
" zoom: ",
map.zoomLevel,
" canvassize: ",
map.canvas.height,
map.canvas.width,
"near: ",
map.camera.near,
"far: ",
map.camera.far
);
});
}
export const mapView = initMapView("mapCanvas");
const boundsGenerator = new BoundsGenerator(mapView);
const viewBoundsDataSource = addFeaturesDataSource(mapView, []);
initGUI(mapView, boundsGenerator, viewBoundsDataSource);
} | the_stack |
import * as RetroStoreProto from "./RetroStoreProto";
import {clearElement} from "teamten-ts-utils";
import {makeIcon, makeIconButton} from "./Utils";
import {Context} from "./Context";
import {decodeTrs80File} from "trs80-base";
import {FileBuilder} from "./File";
import {PageTab} from "./PageTab";
const RETRO_STORE_API_URL = "https://retrostore.org/api/";
const APP_FETCH_COUNT = 10;
/**
* Stores info about a RetroStore app and its media.
*/
class RetroStoreApp {
public readonly app: RetroStoreProto.App;
public element: HTMLElement | undefined = undefined;
constructor(app: RetroStoreProto.App) {
this.app = app;
}
}
/**
* Fetch all apps from RetroStore. If an error occurs, returns an empty list.
*/
function fetchApps(start: number, count: number): Promise<RetroStoreProto.App[]> {
const query = "";
const apiRequest = {
start: start,
num: count,
query: query,
trs80: {
mediaTypes: [],
},
};
const fetchOptions: RequestInit = {
method: "POST",
cache: "no-cache",
body: JSON.stringify(apiRequest),
};
return fetch(RETRO_STORE_API_URL + "listApps", fetchOptions)
.then(response => {
if (response.status === 200) {
return response.arrayBuffer();
} else {
throw new Error("Error code " + response.status);
}
})
.then(array => {
const apps = RetroStoreProto.decodeApiResponseApps(new Uint8Array(array));
if (apps.success) {
return Promise.resolve(apps.app ?? []);
} else {
// TODO.
console.error("Can't get apps: " + apps.message);
return Promise.resolve([]);
}
})
.catch(error => {
// TODO
console.error(error);
return Promise.resolve([]);
});
}
/**
* Fetch all media images for the specified app ID. If an error occurs, returns an empty list.
*/
function fetchMediaImages(appId: string): Promise<RetroStoreProto.MediaImage[]> {
const apiRequest = {
appId: appId,
};
const fetchOptions: RequestInit = {
method: "POST",
cache: "no-cache",
body: JSON.stringify(apiRequest),
};
return fetch(RETRO_STORE_API_URL + "fetchMediaImages", fetchOptions)
.then(response => {
if (response.status === 200) {
return response.arrayBuffer();
} else {
throw new Error("Error code " + response.status);
}
})
.then(array => {
const mediaImages = RetroStoreProto.decodeApiResponseMediaImages(new Uint8Array(array));
if (mediaImages.success) {
return Promise.resolve(mediaImages.mediaImage ?? []);
} else {
// TODO.
console.error("Can't get media images for " + appId + ": " + mediaImages.message);
return Promise.reject();
}
})
.catch(error => {
// TODO
console.error(error);
return Promise.reject();
});
}
/**
* The tab for showing apps from RetroStore.org.
*/
export class RetroStoreTab extends PageTab {
private readonly context: Context;
private readonly appsDiv: HTMLElement;
private readonly moreDiv: HTMLElement;
private readonly apps: RetroStoreApp[] = [];
private complete = false;
private fetching = false;
constructor(context: Context) {
super("RetroStore");
this.context = context;
this.element.classList.add("retro-store-tab");
this.appsDiv = document.createElement("div");
this.appsDiv.classList.add("retro-store-apps");
this.appsDiv.addEventListener("scroll", () => this.fetchNextBatchIfNecessary());
this.element.append(this.appsDiv);
this.moreDiv = document.createElement("div");
this.moreDiv.classList.add("retro-store-more");
this.moreDiv.append(makeIcon("cached"));
this.populateApps();
// If the window is resized, it might reveal slots to load.
window.addEventListener("resize", () => this.fetchNextBatchIfNecessary());
}
public onShow(): void {
// When showing the tab, wait for layout and maybe fetch more.
setTimeout(() => this.fetchNextBatchIfNecessary(), 0);
}
/**
* If the "More" section is visible, fetch more apps.
*/
private fetchNextBatchIfNecessary(): void {
const moreVisible = this.moreDiv.getBoundingClientRect().top < this.appsDiv.getBoundingClientRect().bottom;
if (moreVisible && !this.complete && !this.fetching) {
this.fetchNextBatch();
}
}
/**
* Get the next batch of apps if necessary.
*/
private fetchNextBatch(): void {
if (!this.complete) {
this.fetching = true;
fetchApps(this.apps.length, APP_FETCH_COUNT)
.then(apps => {
this.fetching = false;
if (apps.length !== APP_FETCH_COUNT) {
// Got all apps.
this.complete = true;
}
this.apps.push(...apps.map(a => new RetroStoreApp(a)));
this.populateApps();
// See if we need to fetch any more.
this.fetchNextBatchIfNecessary();
})
.catch(error => {
// TODO.
console.error(error);
this.fetching = false;
this.complete = true;
});
}
}
/**
* Populate the UI with the apps we have.
*/
private populateApps(): void {
clearElement(this.appsDiv);
for (const app of this.apps) {
if (app.element === undefined) {
app.element = this.createAppTile(app.app);
}
this.appsDiv.append(app.element);
}
if (!this.complete) {
this.appsDiv.append(this.moreDiv);
}
}
/**
* Create a tile for an app.
*/
private createAppTile(app: RetroStoreProto.App): HTMLElement {
const appDiv = document.createElement("div");
appDiv.classList.add("retro-store-app");
const screenshotDiv = document.createElement("img");
screenshotDiv.classList.add("screenshot");
if (app.screenshot_url !== undefined && app.screenshot_url.length > 0) {
screenshotDiv.src = app.screenshot_url[0];
}
appDiv.append(screenshotDiv);
const nameDiv = document.createElement("div");
nameDiv.classList.add("name");
const appName = app.name ?? "Unknown name";
nameDiv.innerText = appName;
if (app.release_year !== undefined) {
const releaseYearSpan = document.createElement("span");
releaseYearSpan.classList.add("release-year");
releaseYearSpan.innerText = " (" + app.release_year + ")";
nameDiv.append(releaseYearSpan);
}
appDiv.append(nameDiv);
if (app.author !== undefined && app.author !== "") {
const authorDiv = document.createElement("div");
authorDiv.classList.add("author");
authorDiv.innerText = app.author;
appDiv.append(authorDiv);
}
if (app.version !== undefined && app.version !== "") {
const versionDiv = document.createElement("div");
versionDiv.classList.add("version");
versionDiv.innerText = "Version " + app.version;
appDiv.append(versionDiv);
}
if (app.description !== undefined && app.description !== "") {
const descriptionDiv = document.createElement("div");
descriptionDiv.classList.add("description");
descriptionDiv.innerText = app.description;
appDiv.append(descriptionDiv);
}
const buttonDiv = document.createElement("div");
buttonDiv.classList.add("button-set");
appDiv.append(buttonDiv);
let validMediaImage: RetroStoreProto.MediaImage | undefined = undefined;
const playButton = makeIconButton(makeIcon("play_arrow"), "Run app", () => {
if (validMediaImage !== undefined && validMediaImage.data !== undefined) {
const cmdProgram = decodeTrs80File(validMediaImage.data, validMediaImage.filename);
// TODO should set context.runningFile
this.context.trs80.runTrs80File(cmdProgram);
this.context.panelManager.close();
}
});
playButton.disabled = true;
buttonDiv.append(playButton);
const importButton = makeIconButton(makeIcon("get_app"), "Import app", () => {
if (validMediaImage !== undefined && validMediaImage.data !== undefined && this.context.user !== undefined) {
const noteParts: string[] = [];
if (app.description !== undefined && app.description !== "") {
noteParts.push(app.description);
}
if (validMediaImage.description !== undefined && validMediaImage.description !== "") {
noteParts.push(validMediaImage.description);
}
noteParts.push("Imported from RetroStore.org.");
const note = noteParts.join("\n\n");
let file = new FileBuilder()
.withUid(this.context.user.uid)
.withName(appName)
.withNote(note)
.withAuthor(app.author ?? "")
.withReleaseYear(app.release_year === undefined ? "" : app.release_year.toString())
.withTags(["RetroStore"])
.withFilename(validMediaImage.filename ?? "UNKNOWN")
.withBinary(validMediaImage.data)
.build();
this.context.db.addFile(file)
.then(docRef => {
file = file.builder().withId(docRef.id).build();
this.context.library.addFile(file);
this.context.openFilePanel(file);
})
.catch(error => {
// TODO
console.error("Error adding document: ", error);
});
}
});
importButton.classList.add("import-button");
importButton.disabled = true;
buttonDiv.append(importButton);
if (app.id !== undefined) {
fetchMediaImages(app.id)
.then(mediaImages => {
console.log(app.id, app.name, mediaImages);
for (const mediaImage of mediaImages) {
if (mediaImage.type === RetroStoreProto.MediaType.COMMAND ||
mediaImage.type === RetroStoreProto.MediaType.BASIC ||
mediaImage.type === RetroStoreProto.MediaType.DISK) {
validMediaImage = mediaImage;
playButton.disabled = false;
importButton.disabled = false;
break;
}
}
})
.catch(error => {
// TODO. Caught already?
console.error(error);
});
}
return appDiv;
}
} | the_stack |
import { relative, resolve, extname, emptyDir, isAbsolute, dirname, ensureDir, join } from '../deps_cli.ts';
import { directoryExists } from '../fs_util.ts';
import { ParseError, parseJsonc } from '../jsonc.ts';
import { computeHtml } from './design.ts';
import { Page, readPageFromFile } from './page.ts';
import { computeSidebar, SidebarInputItem } from './sidebar.ts';
import { SiteConfig } from './site_config.ts'
import { checkSiteConfig } from './site_config_validation.ts';
import { Bytes } from '../../common/bytes.ts';
export class SiteModel {
private readonly inputDir: string;
private readonly resources = new Map<string, ResourceInfo>(); // key = "resource path", e.g. /index.html for /index.md
private readonly localOrigin?: string;
private currentManifestPath: string | undefined;
constructor(inputDir: string, opts: { localOrigin?: string } = {}) {
const { localOrigin } = opts;
this.localOrigin = localOrigin;
if (!directoryExists(inputDir)) throw new Error(`Bad inputDir: ${inputDir}, must exist`);
if (!isAbsolute(inputDir)) throw new Error(`Bad inputDir: ${inputDir}, must be absolute`);
this.inputDir = inputDir;
}
async setInputFiles(files: InputFileInfo[]) {
const contentUpdateTime = Date.now();
// ensure resources exist
for (const file of files) {
const inputPath = file.path;
if (!isAbsolute(inputPath)) throw new Error(`Bad inputPath: ${inputPath}, must be absolute`);
const path = computeResourcePath(inputPath, this.inputDir);
let resource = this.resources.get(path);
if (!resource) {
const extension = extname(inputPath);
const includeInOutput = shouldIncludeInOutput(path, extension);
const canonicalPath = computeCanonicalResourcePath(path);
const contentRepoPath = computeContentRepoPath(inputPath, this.inputDir);
resource = { inputPath, extension, includeInOutput, canonicalPath, contentRepoPath };
this.resources.set(path, resource);
}
}
// console.log([...this.resources.keys()].sort().map(v => `${v} ${this.resources.get(v)!.canonicalPath}`).join('\n'));
// read config
const config = await computeConfig(this.resources);
// generate app manifest
const { manifestPath, manifestContents } = await computeManifest(config);
if (this.currentManifestPath !== manifestPath) {
this.resources.set(manifestPath, {
inputPath: join(this.inputDir, manifestPath),
extension: '.webmanifest',
includeInOutput: true,
canonicalPath: manifestPath,
contentRepoPath: '<generated>',
outputText: manifestContents,
});
if (this.currentManifestPath) {
this.resources.delete(this.currentManifestPath);
}
this.currentManifestPath = manifestPath;
}
// generate robots.txt
const robotsTxtPath = '/robots.txt';
const sitemapXmlPath = '/sitemap.xml';
this.resources.set(robotsTxtPath, {
inputPath: join(this.inputDir, robotsTxtPath),
extension: '.txt',
includeInOutput: true,
canonicalPath: robotsTxtPath,
contentRepoPath: '<generated>',
outputText: `User-agent: *\nDisallow:\nSitemap: ${this.localOrigin || config.siteMetadata.origin || ''}${sitemapXmlPath}\n`,
});
// generate sitemap.xml
const sitemapXmlContents = await computeSitemapXml(this.resources, config, this.localOrigin);
this.resources.set(sitemapXmlPath, {
inputPath: join(this.inputDir, sitemapXmlPath),
extension: '.xml',
includeInOutput: true,
canonicalPath: sitemapXmlPath,
contentRepoPath: '<generated>',
outputText: sitemapXmlContents,
});
// read frontmatter from all md
for (const [_, resource] of this.resources.entries()) {
if (resource.extension === '.md') {
resource.page = await readPageFromFile(resource.inputPath);
}
}
// construct sidebar
const sidebarInputItems: SidebarInputItem[] = [...this.resources.values()]
.filter(v => v.extension === '.md' && v.includeInOutput)
.map(v => ({
title: v.page!.titleResolved,
path: v.canonicalPath === '/' ? v.canonicalPath : replaceSuffix(v.canonicalPath, '/', ''),
hidden: v.page!.frontmatter.hidden,
hideChildren: v.page!.frontmatter.hideChildren,
order: v.page!.frontmatter.order,
}));
const sidebar = computeSidebar(sidebarInputItems);
// transform markdown into html
for (const [_, resource] of this.resources.entries()) {
if (resource.extension === '.md') {
const { canonicalPath: path, contentRepoPath } = resource;
const { inputDir } = this;
const page = resource.page!;
const { localOrigin } = this;
const outputHtml = await computeHtml({ inputDir, page, path, contentRepoPath, config, sidebar, contentUpdateTime, manifestPath, localOrigin, verbose: false, dumpEnv: false });
resource.outputText = outputHtml;
}
}
}
async writeOutput(outputDir: string) {
await checkConfigForOutput(this.resources);
if (!isAbsolute(outputDir)) throw new Error(`Bad outputDir: ${outputDir}, must be absolute`);
console.log(`writeOutput ${outputDir}`);
await emptyDir(outputDir);
const ensuredDirs = new Set();
for (const [_, resource] of this.resources.entries()) {
if (!resource.includeInOutput) continue;
const outputPath = computeOutputPath(resource.inputPath, this.inputDir, outputDir);
console.log(`Writing ${outputPath}`);
const outputPathDirectory = dirname(outputPath);
if (!ensuredDirs.has(outputPathDirectory)) {
console.log('ensureDir ' + outputPathDirectory);
await ensureDir(outputPathDirectory);
ensuredDirs.add(outputPathDirectory);
}
if (resource.outputText !== undefined) {
await Deno.writeTextFile(outputPath, resource.outputText);
} else {
await Deno.copyFile(resource.inputPath, outputPath);
}
}
}
async handle(request: Request): Promise<Response> {
const url = new URL(request.url);
const { pathname } = url;
const resource = findResource(pathname, this.resources);
if (resource) {
if (pathname.endsWith('.html')) {
url.pathname = replaceSuffix(pathname, '.html', '');
const headers: HeadersInit = { 'Location': url.toString() };
return new Response('', { status: 308, headers });
} else if (pathname.endsWith('/index')) {
url.pathname = replaceSuffix(pathname, '/index', '');
const headers: HeadersInit = { 'Location': url.toString() };
return new Response('', { status: 308, headers });
}
} else {
const notFoundResource = findResource('/404', this.resources);
if (notFoundResource) return await computeReponseForResource(notFoundResource, 404);
return new Response('not found', { status: 404 });
}
return await computeReponseForResource(resource, 200);
}
}
export interface InputFileInfo {
readonly path: string;
readonly version: string;
}
//
export function replaceSuffix(path: string, fromSuffix: string, toSuffix: string, opts: { required?: boolean } = { }): string {
const { required } = opts;
const endsWith = path.endsWith(fromSuffix);
if (!endsWith && !!required) throw new Error(`Bad path: ${path}, expected to end in suffix: ${fromSuffix}`);
return endsWith ? (path.substring(0, path.length - fromSuffix.length) + toSuffix) : path;
}
//
interface ResourceInfo {
readonly inputPath: string; // full fs path to source file
readonly extension: string; // with dot, e.g. .md
readonly includeInOutput: boolean;
readonly canonicalPath: string; // e.g. / for /index.html, and /foo for /foo.html
readonly contentRepoPath: string; // e.g. /index.md
page?: Page;
outputText?: string;
}
//
const EXTENSIONS_TO_INCLUDE_IN_OUTPUT = new Map([
// content-type from Cloudflare Pages
['.html', 'text/html; charset=utf-8'],
['.ico', 'image/x-icon'],
['.jpg', 'image/jpeg'],
['.json', 'application/json'],
['.md', 'text/html; charset=utf-8'],
['.png', 'image/png'],
['.svg', 'image/svg+xml'],
['.txt', 'text/plain'],
['.webmanifest', 'application/manifest+json'],
['.xml', 'text/xml'],
]);
function computeContentType(resource: ResourceInfo): string {
const contentType = EXTENSIONS_TO_INCLUDE_IN_OUTPUT.get(resource.extension);
if (contentType) return contentType;
throw new Error(`Unable to compute content-type for ${resource.canonicalPath}, extension=${resource.extension}`);
}
function shouldIncludeInOutput(path: string, extension: string): boolean {
if (path === '/config.json' || path === '/config.jsonc' || path.toLowerCase() === '/readme.html') return false;
return path === '/_redirects' || path === '/_headers' || EXTENSIONS_TO_INCLUDE_IN_OUTPUT.has(extension);
}
function computeOutputPath(inputFile: string, inputDir: string, outputDir: string) {
const relativePath = relative(inputDir, inputFile);
const outputPath = resolve(outputDir, relativePath);
return replaceSuffix(outputPath, '.md', '.html');
}
function computeResourcePath(inputFile: string, inputDir: string): string {
if (!inputFile.startsWith(inputDir)) throw new Error(`Bad inputFile: ${inputFile}, must reside under ${inputDir}`);
const relativePath = relative(inputDir, inputFile);
if (relativePath.startsWith('/')) throw new Error(`Unexpected relative path: ${relativePath}, inputFile=${inputFile}, inputDir=${inputDir}`);
return '/' + replaceSuffix(relativePath, '.md', '.html');
}
function computeContentRepoPath(inputFile: string, inputDir: string): string {
if (!inputFile.startsWith(inputDir)) throw new Error(`Bad inputFile: ${inputFile}, must reside under ${inputDir}`);
const relativePath = relative(inputDir, inputFile);
if (relativePath.startsWith('/')) throw new Error(`Unexpected relative path: ${relativePath}, inputFile=${inputFile}, inputDir=${inputDir}`);
return '/' + relativePath;
}
function computeCanonicalResourcePath(resourcePath: string): string {
if (resourcePath.endsWith('.html')) resourcePath = resourcePath.substring(0, resourcePath.length - '.html'.length);
if (resourcePath.endsWith('/index')) resourcePath = resourcePath.substring(0, resourcePath.length - 'index'.length);
return resourcePath;
}
async function computeConfig(resources: Map<string, ResourceInfo>): Promise<SiteConfig> {
for (const path of ['/config.jsonc', '/config.json']) {
const resource = resources.get(path);
if (resource) {
const contents = await Deno.readTextFile(resource.inputPath);
const errors: ParseError[] = [];
const config = parseJsonc(contents, errors, { allowTrailingComma: true });
return checkSiteConfig(config);
}
}
throw new Error(`Site config not found: /config.jsonc or /config.json`);
}
async function checkConfigForOutput(resources: Map<string, ResourceInfo>) {
const config = await computeConfig(resources);
if (!config.siteMetadata.origin) throw new Error(`Missing config.siteMetadata.origin, required when writing output`);
}
async function computeManifest(config: SiteConfig): Promise<{ manifestPath: string; manifestContents: string; }> {
const icons = config.siteMetadata.faviconSvg ? [{ src: config.siteMetadata.faviconSvg, type: 'image/svg+xml' }] : [];
const manifest: Record<string, unknown> = {
'short_name': config.siteMetadata.title,
name: config.siteMetadata.title,
description: config.siteMetadata.description,
icons: icons,
'theme_color': config.themeColorDark || config.themeColor,
'background_color': '#1d1f20',
display: 'standalone',
'start_url': '/',
lang: 'en-US',
dir: 'ltr',
};
if (config.siteMetadata.manifest) {
for (const [name, value] of Object.entries(config.siteMetadata.manifest)) {
manifest[name] = value;
}
}
const manifestContents = JSON.stringify(manifest, undefined, 2);
const manifestPath = `/app.${(await Bytes.ofUtf8(manifestContents).sha1()).hex()}.webmanifest`;
return { manifestPath, manifestContents };
}
function findResource(pathname: string, resources: Map<string, ResourceInfo>): ResourceInfo | undefined {
const rt = resources.get(pathname);
if (rt) return rt;
const canonical = computeCanonicalResourcePath(pathname);
return [...resources.values()].find(v => v.canonicalPath === canonical || v.canonicalPath === (canonical + '/'));
}
async function computeReponseForResource(resource: ResourceInfo, status: number ): Promise<Response> {
const headers: HeadersInit = { 'Content-Type': computeContentType(resource) }
if (resource.outputText) {
return new Response(resource.outputText, { headers });
}
const body: BodyInit = resource.outputText ? resource.outputText : await Deno.readFile(resource.inputPath);
return new Response(body, { status, headers });
}
function computeSitemapXml(resources: Map<string, ResourceInfo>, config: SiteConfig, localOrigin: string | undefined): string {
const lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
];
const notFoundResourceCanonicalPath = findResource('/404', resources)?.canonicalPath;
const canonicalPaths = [...resources.values()]
.filter(v => v.includeInOutput && (v.extension === '.html' || v.extension === '.md') && v.canonicalPath !== notFoundResourceCanonicalPath)
.map(v => v.canonicalPath)
.sort();
for (const canonicalPath of canonicalPaths) {
lines.push(' <url>');
lines.push(` <loc>${localOrigin || config.siteMetadata.origin || ''}${canonicalPath}</loc>`);
lines.push(' </url>');
}
lines.push('</urlset>');
return lines.join('\n');
} | the_stack |
import { IllegalArgumentError } from '../../errors/illegal-argument-error';
import { Actuator } from '../actuator/actuator';
import { Parser } from '../parser';
import { Join } from './join';
export type TSymlink = 'and' | 'or' | ''
export type TJoinType = 'inner' | 'left' | 'right' | 'cross'
export interface ColumnDescribeOption {
type: 'column' | 'raw';
column: string;
}
interface WhereDescribeOption {
type: 'value' | 'column' | 'sql' | 'in' | 'notIn' | 'null' | 'notNull';
column?: string;
operator?: string;
value?: any;
symlink: TSymlink;
}
interface HavingDescribeOption {
type: 'value';
column: string;
operator: string;
value: any;
symlink: TSymlink;
}
interface AggregateOption {
func: string;
column: string;
}
interface UnionOption {
builder: Builder;
isAll: boolean;
}
interface OrderOption {
type: 'column' | 'raw';
column: string;
direction?: string;
}
type BindingKeys = 'select' | 'from' | 'join' | 'where' | 'having' | 'order' | 'union'
export class Builder {
/**
* The distinct
*/
_distinct: boolean | string[] = false;
/**
* The aggregate desc
*/
_aggregate?: AggregateOption;
/**
* The columns
*/
_columns: ColumnDescribeOption[] = [];
/**
* the table name
*/
_table: string;
/**
* the table from alias
*/
_alias: string;
/**
* The where constraints
*/
_wheres: WhereDescribeOption[] = [];
/**
* The orders
*/
_orders: OrderOption[] = [];
/**
* The maximum number of records
*/
_limit?: number;
/**
* The number of records to skip
*/
_offset?: number;
/**
* The lock
*/
_lock: boolean | string;
/**
* The groups for group by
*/
_groups: string[] = [];
/**
* The joins
*/
_joins: Join[] = [];
/**
* The Having
*/
_havings: HavingDescribeOption[] = []
/**
* The unions
*/
_unions: UnionOption[] = [];
/**
* binding params
*/
params: any[] = [];
bindings: Map<BindingKeys, any[]> = new Map([
['select', []],
['from', []],
['join', []],
['where', []],
['having', []],
['order', []],
['union', []],
]);
/**
* grammar parser instance
*/
parser: Parser;
/**
* connection instance
*/
// collection: PoolConnection;
actuator: Actuator;
/**
* shlould log sql
*/
private shouldLogSql = false;
/**
* should dump sql
* will return sql use select inster update and delete
*/
private shouldDumpSql = false;
/**
* Create Builder instance
* @param collection
*/
constructor(actuator: Actuator, parser: Parser) {
// super();
this.actuator = actuator;
this.parser = parser;
}
/**
* Remove aggregate func
*/
removeAggregate() {
this._aggregate = undefined;
return this;
}
/**
* show columns
* @param columns
*/
select(...columns: (string | string[])[]) {
for (const column of columns) {
if (typeof column === 'string') {
this._columns.push({
type: 'column',
column,
});
} else if (Array.isArray(column)) {
for (const item of column) {
this._columns.push({
type: 'column',
column: item,
});
}
}
}
return this;
}
/**
* select sub query
* @param query
* @param as
*/
selectSub(query: Builder | ((query: Builder) => Builder | void), as: string) {
const _query = new Builder(this.actuator, this.parser);
if (typeof query === 'function') {
query(_query);
}
const sql = _query.toSql();
this.selectRaw(`(${sql}) \`${as}\``, _query.getBindings());
return this;
}
/**
* select raw
* @param raw
* @param bindings
*/
selectRaw(raw: string, bindings: any[] = []) {
this._columns.push({
type: 'raw',
column: raw,
});
this.addBinding('select', bindings);
return this;
}
/**
* alias colums
* @param columns
*/
fields(...columns: (string | string[])[]) {
return this.select(...columns);
}
/**
* alias colums
* @param columns
*/
columns(...columns: (string | string[])[]) {
return this.select(...columns);
}
/**
* Set the table target
* @param table
* @param as
*/
table(table: string, as?: string) {
// this._from = as ? `${table} as ${as}` : table;
let _table = table ?? '';
let _as = as;
if (table && ~table.indexOf(` as `)) {
[_table, _as] = table.split(` as `);
}
_table = _table.trim();
_as = _as?.trim();
if (_as) {
// this._from = `${_table} as ${_as}`;
this._alias = _as;
}
// else {
// this._from = _table;
// }
this._table = _table;
return this;
}
/**
* alias table
* @param as
*/
alias(as: string) {
this._alias = as;
return this;
}
/**
* where
* @param column
* @param operator
* @param value
* @param symlink
*/
where(
column: string | [string, any, any?, TSymlink?][],
operator?: any,
value?: any,
symlink: TSymlink = 'and'
) {
if (Array.isArray(column)) {
for (const _column of column) {
this.where(..._column);
}
return this;
}
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = 'value';
if (value !== undefined) {
this._wheres.push({ type, column, operator, value, symlink: _symlink });
// this.addParams(value);
this.addBinding('where', value);
} else {
this._wheres.push({ type, column, operator: '=', value: operator, symlink: _symlink });
this.addBinding('where', operator);
// this.addParams(operator);
}
return this;
}
/**
* where use or tymlink
* @param column
* @param operator
* @param value
*/
orWhere(
column: string | [string, any, any?][],
operator: any,
value?: any
) {
return this.where(column, operator, value, 'or');
}
/**
* raw where
* @param sql
* @param params
* @param symlink
*/
whereRaw(sql: string, params: any[] = [], symlink: TSymlink = 'and') {
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = 'sql';
this._wheres.push({ type, value: sql, symlink: _symlink});
this.addBinding('where', params);
// this.addParams(params);
return this;
}
/**
* or raw where
* @param sql
* @param params
*/
orWhereRaw(sql: string, params: any[] = []) {
return this.whereRaw(sql, params, 'or');
}
/**
* where for column
* @param column
* @param operator
* @param value
* @param symlink
*/
whereColumn(column: string, operator: string, value?: string, symlink: TSymlink = 'and') {
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = 'column';
if (value !== undefined) {
this._wheres.push({ type, column, operator, value, symlink: _symlink });
} else {
this._wheres.push({ type, column, operator: '=', value: operator, symlink: _symlink });
}
return this;
}
/**
* where in
* @param column
* @param value
* @param symlink
*/
whereIn(column: string, value: any[], symlink: TSymlink = 'and') {
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = 'in';
this._wheres.push({ type, column, value, symlink: _symlink });
this.addBinding('where', value);
return this;
}
/**
* or where in
* @param column
* @param value
*/
orWhereIn(column: string, value: any[]) {
return this.whereIn(column, value, 'or');
}
/**
* where not in
* @param column
* @param value
* @param symlink
*/
whereNotIn(column: string, value: any[], symlink: TSymlink = 'and') {
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = 'notIn';
this._wheres.push({ type, column, value, symlink: _symlink });
this.addBinding('where', value);
return this;
}
/**
* or where not in
* @param column
* @param value
*/
orWhereNotIn(column: string, value: any[]) {
return this.whereNotIn(column, value, 'or');
}
/**
* where null
* @param column
* @param symlink
* @param not
*/
whereNull(column: string, symlink: TSymlink = 'and', not = false) {
const _symlink = this._wheres.length > 0 ? symlink : '';
const type = not ? 'notNull' : 'null';
this._wheres.push({ type, column, symlink: _symlink });
return this;
}
/**
* where not null
* @param column
* @param symlink
*/
whereNotNull(column: string, symlink: TSymlink = 'and') {
this.whereNull(column, symlink, true);
return this;
}
/**
* or where null
* @param column
*/
orWhereNull(column: string) {
this.whereNull(column, 'or', false);
return this;
}
/**
* or where not null
* @param column
*/
orWhereNotNull(column: string) {
this.whereNull(column, 'or', true);
return this;
}
/**
* or where column
* @param column
* @param operator
* @param value
*/
orWhereColumn(column: string, operator: string, value?: string) {
return this.whereColumn(column, operator, value, 'or');
}
/**
* aggregate func
* @param type
* @param column
*/
async aggregate(type: string, column = '*') {
this._aggregate = {
func: type,
column,
};
this._limit = undefined;
this._offset = undefined;
const sql = this.toSql();
const params = this.getBindings();
const results = await this.actuator.select(sql, params);
const aggregate = results[0]?.aggregate;
if (aggregate === undefined) return
return Number(aggregate)
}
/**
* 聚合函数- count
* @param column
*/
async count(column = '*') {
const res = await this.aggregate('count', column);
return res ?? 0
}
/**
* 聚合函数 - max
* @param column
*/
async max(column: string) {
return this.aggregate('max', column);
}
/**
* 聚合函数 - min
* @param column
*/
async min(column: string) {
return this.aggregate('min', column);
}
/**
* 聚合函数 - sum
* @param column
*/
async sum(column: string) {
const res = await this.aggregate('sum', column);
return res ?? 0;
}
/**
* 聚合函数 - avg
* @param column
*/
async avg(column: string) {
return this.aggregate('avg', column);
}
/**
* order by
* @param column
* @param direction
*/
orderBy(column: string, direction = 'asc') {
const _direction = direction.toLowerCase();
if (!['asc', 'desc'].includes(_direction)) throw new IllegalArgumentError('Order direction must be "asc" or "desc"');
this._orders.push({
type: 'column',
column,
direction: _direction,
});
return this;
}
/**
* order by raw
* @param raw
* @returns
*/
orderByRaw(raw: string) {
this._orders.push({
type: 'raw',
column: raw,
});
return this;
}
/**
* limit
* @param value
*/
limit(value: number) {
if (value >= 0) this._limit = value;
return this;
}
/**
* limit 别名
* @param value
*/
take(value: number) {
return this.limit(value);
}
/**
* offset
* @param value
*/
offset(value: number) {
this._offset = value >= 0 ? value : 0;
return this;
}
/**
* offset 别名
* @param value
*/
skip(value: number) {
return this.offset(value);
}
/**
* 去重
* @param column
* @param columns
*/
distinct(column: string | boolean = false, ...columns: string[]) {
if (typeof column === 'boolean') {
this._distinct = column;
return this;
}
if (columns.length > 0) {
this._distinct = [column, ...columns];
return this;
}
this._distinct = true;
return this;
}
/**
* Lock the selected rows
* @param value
*/
lock(value: boolean | string) {
this._lock = value;
return this;
}
/**
* Share lock the selected rows
*/
sharedLock() {
return this.lock(false);
}
/**
* Lock the selected rows for updating
*/
lockForUpdate() {
return this.lock(true);
}
/**
* Add group by statement
* @param columns
*/
groupBy(...columns: string[] | string[][]) {
for (const column of columns) {
if (typeof column === 'string') {
this._groups.push(column);
} else if (Array.isArray(column)) {
this._groups.push(...column);
}
}
return this;
}
/**
* join
* @param table
* @param column
* @param operator
* @param value
* @param type
*/
join(table: string | ((join: Join & Builder) => Join | void), column?: string, operator?: any, value?: any, type: TJoinType = 'inner') {
const join = new Join(new Builder(this.actuator, this.parser), type);
if (typeof table === 'string' && column) {
this._joins.push(
join.table(table).on(column, operator, value)
);
this.addBinding('join', join.getBindings());
// this.addParams(join.getParams());
} else if (typeof table === 'function') {
table(join);
this._joins.push(join);
this.addBinding('join', join.getBindings());
// this.addParams(join.getParams());
}
return this;
}
/**
* left join
* @param table
* @param column
* @param operator
* @param value
*/
leftJoin(table: string | ((join: Join & Builder) => Join | void), column?: string, operator?: any, value?: any) {
return this.join(table, column, operator, value, 'left');
}
/**
* right join
* @param table
* @param column
* @param operator
* @param value
*/
rightJoin(table: string | ((join: Join & Builder) => Join | void), column?: string, operator?: any, value?: any) {
return this.join(table, column, operator, value, 'right');
}
/**
* having
* @param column
* @param operator
* @param value
* @param symlink
*/
having(column: string, operator: any, value?: any, symlink: TSymlink = 'and') {
const _symlink = this._havings.length > 0 ? symlink : '';
const type = 'value';
if (value !== undefined) {
this._havings.push({ type, column, operator, value, symlink: _symlink });
} else {
this._havings.push({ type, column, operator: '=', value: operator, symlink: _symlink });
}
return this;
}
/**
* union
* @param builder
* @param isAll
*/
union(builder: Builder | ((union: Builder) => Builder | void), isAll = false) {
let _builder = builder as Builder;
if (typeof builder === 'function') {
_builder = new Builder(this.actuator, this.parser);
builder(
_builder
);
}
this._unions.push({
builder: _builder,
isAll,
});
this.addBinding('union', this.getBindings());
// this.addParams(_builder.getParams());
return this;
}
/**
* union all
* @param builder
*/
unionAll(builder: Builder | ((union: Builder) => Builder)) {
return this.union(builder, true);
}
/**
* add binding param
* @param key
* @param value
*/
addBinding(key: BindingKeys, value: any) {
if (Array.isArray(value)) {
this.bindings.get(key)?.push(...value);
return this;
}
this.bindings.get(key)?.push(value);
return this;
}
/**
* get all binding params
*/
getBindings() {
const _keys = [...this.bindings.keys()];
// return Array.from(this.bindings).flat();
return this.getBindingsWithKeys(_keys);
}
/**
* gei binding params with keys
* @param keys
*/
getBindingsWithKeys(keys: BindingKeys[]) {
const _keys = [...this.bindings.keys()].filter(key => keys.includes(key));
const bindings: any[] = [];
for (const key of _keys) {
if (this.bindings.has(key)) {
bindings.push(
...this.bindings.get(key) ?? []
);
}
}
return bindings;
}
/**
* get binding params except keys
* @param keys
*/
getBindingsExceptKeys(keys: BindingKeys[]) {
const _keys = [...this.bindings.keys()].filter(key => !keys.includes(key));
const bindings: any[] = [];
for (const key of _keys) {
if (this.bindings.has(key)) {
bindings.push(
...this.bindings.get(key) ?? []
);
}
}
return bindings;
}
/**
* gen sql string
*/
toSql() {
return this.parser.parseSelect(this);
}
/**
* load sql and params
*/
logSql() {
this.shouldLogSql = true;
return this;
}
/**
* log sql alias
*/
log() {
this.shouldLogSql = true;
return this;
}
/**
* dump sql
*/
dumpSql() {
this.shouldDumpSql = true;
return this;
}
/**
* alias for dumpSql
*/
dump() {
return this.dumpSql();
}
/**
* query multiple records from database,
*/
async find() {
const sql = this.toSql();
const params = this.getBindings();
if (this.shouldLogSql) {
console.log('sql:', sql);
console.log('params:', params);
}
const results = await this.actuator.select(sql, params);
return results;
}
/**
* query multiple records and count from database,
*/
async findAndCount(): Promise<[any[], number]> {
const results: any[] = await this.find();
const count: number = await this.count();
return [results, count];
}
/**
* query first record from database
*/
async first(): Promise<Record<string, any> | undefined> {
const sql = this.take(1).toSql();
const params = this.getBindings();
if (this.shouldLogSql) {
console.log('sql:', sql);
console.log('params:', params);
}
const results = await this.actuator.select(sql, params);
if (!results[0]) return;
return {
...results[0]
} as Record<string, any>;
}
/**
* get binding parmas for update
* @param values
*/
getBindingsForUpdate(values: any[] = []) {
const cleanBindings = this.getBindingsExceptKeys([
'select',
'join'
]);
return [
...this.getBindingsWithKeys(['join']),
...values,
...cleanBindings
];
}
/**
* get binding params for delete
*/
getBindingsForDelete() {
const cleanBindings = this.getBindingsExceptKeys([
'select',
]);
return [
...cleanBindings
];
}
/**
* build final sql for debug
* @param sql
* @param params
*/
private buildDebugSql(sql: string, params: any[] = []) {
let _sql = sql;
let i = 0;
while (~_sql.indexOf('?')) {
_sql = _sql.replace(/(\?)/i, params[i]);
i++;
}
return _sql;
}
/**
* log debug sql
* @param sql
* @param params
*/
private logDebugSql(sql: string, params: any[] = []) {
const finalSql = this.buildDebugSql(sql, params);
console.log('Your SQL:\n');
console.log(finalSql);
}
/**
* commit transaction
*/
async commit() {
await this.actuator.commit();
}
/**
* rollback transaction
*/
async rollback() {
await this.actuator.rollback();
}
/**
* 批量插入
* @param data
*/
async insertAll(data: Record<string, any>[] = []) {
const params: any[] = [];
for (const item of data) {
params.push([
...Object.values(item)
]);
}
const sql = this.parser.parseInsert(this, data);
if (this.shouldLogSql) {
this.logDebugSql(sql, params);
}
if (this.shouldDumpSql) return this.buildDebugSql(sql, params);
return this.actuator.insert(
sql,
params
);
}
/**
* inser data
* @param data
*/
async insert(data: Record<string, any>) {
const params = [];
params.push(Object.values(data));
const sql = this.parser.parseInsert(this, [data]);
if (this.shouldLogSql) {
this.logDebugSql(sql, params);
}
if (this.shouldDumpSql) return this.buildDebugSql(sql, params);
return this.actuator.insert(
sql,
params
);
}
/**
* update data
* @param data
*/
async update(data: Record<string, any>) {
const columns = Object.keys(data);
const values = columns.map(column => data[column]);
const sql = this.parser.parseUpdate(this, columns);
const params = this.getBindingsForUpdate(values);
if (this.shouldLogSql) {
this.logDebugSql(sql, params);
}
if (this.shouldDumpSql) return this.buildDebugSql(sql, params);
return this.actuator.update(
sql,
params
);
}
/**
* 根据给定的值自增字段
* @param column
* @param amount
* @param extra
*/
async increment(column: string, amount = 1, extra?: Record<string, any>) {
const wrapedColumn = this.parser.wrapColum(column, this);
const columns = {
[`${column}`]: `${wrapedColumn} + ${amount}`,
...extra
};
return this.update(columns);
}
/**
* 根据给定的值自减字段
* @param column
* @param amount
* @param extra
*/
async decrement(column: string, amount = 1, extra?: Record<string, any>) {
const wrapedColumn = this.parser.wrapColum(column, this);
const columns = {
[`${column}`]: `${wrapedColumn} - ${amount}`,
...extra
};
return this.update(columns);
}
/**
* delete by id
* @param id
*/
async delete(id?: number | string) {
if (id) {
this.where('id', '=', id);
}
const sql = this.parser.parseDelete(this);
const params = this.getBindingsForDelete();
if (this.shouldLogSql) {
this.logDebugSql(sql, params);
}
if (this.shouldDumpSql) return this.buildDebugSql(sql, params);
return this.actuator.delete(
sql,
params
);
}
} | the_stack |
import * as _ from 'lodash'
import { simpleOrders } from '../__mock__/simpleOrder'
import { getPairBySymbol } from '../../src/utils/pair'
import { Server } from '../../src/lib/server'
import { helpCompareStr, getTimestamp } from '../../src/utils/helper'
import { toBN, isBigNumber } from '../../src/utils/math'
import { Side, Pair } from '../../src/types'
import {
generateDexOrderWithoutSalt,
getSignedOrder,
orderBNToString,
orderStringToBN,
getSimpleOrder,
translateOrderBookToSimple,
getFillTakerTokenAmountBN,
getOrderFillRequest,
getFillTakerTokenAmountBNByUpToOrders,
} from '../../src/utils/dex'
import { personalECSignHex, personalECSign } from '../../src/utils/sign'
import { fromUnitToDecimalBN, fromUnitToDecimal } from '../../src/utils/format'
import { orders, orderBook } from '../__mock__/order'
import { sntWethPairData } from '../__mock__/pair'
import { localServerUrl, wallet, zeroExConfig, localConfig } from '../__mock__/config'
import { signatureUtils } from '0x.js/lib/src/utils/signature_utils'
import { ZeroEx } from '0x.js'
import { FEE_RECIPIENT } from '../../src/constants'
let pairs = []
let pair = null
const server = new Server(localServerUrl, wallet)
beforeAll(async () => {
pairs = await server.getPairList()
pair = getPairBySymbol({
base: 'SNT',
quote: 'WETH',
}, pairs)
return pairs
})
describe('test dex simple utils', () => {
it('test getSimpleOrder', () => {
const order = orders[0]
const signedOrder = order.signedOrder
const simpleOrder = getSimpleOrder({
pair,
order: {
...signedOrder,
exchangeContractAddress: zeroExConfig.exchangeContractAddress,
makerTokenAmount: toBN(signedOrder.makerTokenAmount).toString(),
takerTokenAmount: toBN(signedOrder.takerTokenAmount).toString(),
makerFee: toBN(signedOrder.makerFee).toString(),
takerFee: toBN(signedOrder.takerFee).toString(),
expirationUnixTimestampSec: toBN(signedOrder.expirationUnixTimestampSec).toString(),
salt: toBN(signedOrder.salt).toString(),
},
})
expect(simpleOrder.price).toEqual(order.simpleOrder.price)
expect(simpleOrder.amount).toEqual(order.simpleOrder.amount)
expect(simpleOrder.expirationUnixTimestampSec).toEqual(order.simpleOrder.expirationUnixTimestampSec)
})
describe('test translateOrderBookToSimple', () => {
orderBook.bids.concat(orderBook.asks).forEach(o => {
it(`test order orderId: ${o.orderId} - ${o.tradeType} - ${o.rate} - ${o.amountRemaining}`, () => {
const simpleOrders = translateOrderBookToSimple({
pair,
wallet,
orderbookItems: [o],
})
const simpleOrder = simpleOrders[0]
expect(simpleOrder.side).toEqual(o.tradeType === 'bid' ? 'BUY' : 'SELL')
expect(simpleOrder.isMaker).toEqual(helpCompareStr(wallet.address, o.payload.maker))
expect(simpleOrder.expirationUnixTimestampSec).toEqual(+o.payload.expirationUnixTimestampSec)
expect(simpleOrder.rawOrder).toEqual(JSON.stringify(o.payload))
// TODO price / amount process
// maybe server calculate wrong
// expect(simpleOrder.price).toEqual(o.rate)
// expect(toBN(simpleOrder.amount).toString()).toEqual(o.amountRemaining)
})
})
})
describe('test getFillTakerTokenAmountBN', () => {
orderBook.bids.concat(orderBook.asks).forEach(o => {
it(`test order orderId: ${o.orderId} - ${o.tradeType === 'bid' ? 'SELL' : 'BUY'} - ${o.rate} - ${o.amountRemaining}`, () => {
const simpleOrders = translateOrderBookToSimple({
pair,
wallet,
orderbookItems: [o],
})
const simpleOrder = simpleOrders[0]
const fillTakerTokenAmountBN = getFillTakerTokenAmountBN(simpleOrder.side === 'BUY' ? 'SELL' : 'BUY', simpleOrder.amount, simpleOrder.price, pair)
expect(fillTakerTokenAmountBN.toString()).toEqual(
(
simpleOrder.side === 'BUY' ?
fromUnitToDecimalBN(simpleOrder.amount, pair.base.decimal) :
fromUnitToDecimalBN(toBN(simpleOrder.amount).times(simpleOrder.price).toNumber(), pair.quote.decimal)
).toString(),
)
})
})
})
describe('test getFillTakerTokenAmountBNByUpToOrders', () => {
it('check SELL', () => {
const baseAmount = 10000
const orders = simpleOrders.filter(o => o.side === 'BUY')
const fillTakerTokenAmountBN = getFillTakerTokenAmountBNByUpToOrders('SELL', baseAmount, orders, sntWethPairData)
expect(isBigNumber(fillTakerTokenAmountBN)).toEqual(true)
expect(fillTakerTokenAmountBN.toString()).toEqual(fromUnitToDecimal(baseAmount, sntWethPairData.base.decimal, 10))
})
it('should get listed orders takerTokenAmount when set baseAmount 1000000000 and is buy sell orders', () => {
const baseAmount = 1000000000
const orders = simpleOrders.filter(o => o.side === 'SELL')
const fillTakerTokenAmountBN = getFillTakerTokenAmountBNByUpToOrders('BUY', baseAmount, orders, sntWethPairData)
let remainedAmountBN = toBN(baseAmount)
let takerTokenAmountBN = toBN(0)
let quoteAmountBN = toBN(0)
orders.some(so => {
const orderPrice = so.price
const orderAmount = so.amount
quoteAmountBN = quoteAmountBN.plus(getFillTakerTokenAmountBN('BUY', orderAmount, orderPrice, sntWethPairData))
if (remainedAmountBN.gt(toBN(orderAmount))) {
takerTokenAmountBN = takerTokenAmountBN.plus(getFillTakerTokenAmountBN('BUY', orderAmount, orderPrice, sntWethPairData))
remainedAmountBN = remainedAmountBN.minus(toBN(orderAmount))
} else {
takerTokenAmountBN = takerTokenAmountBN.plus(getFillTakerTokenAmountBN('BUY', remainedAmountBN, orderPrice, sntWethPairData))
return true
}
})
expect(quoteAmountBN.toString()).toEqual(takerTokenAmountBN.toString())
expect(fillTakerTokenAmountBN.toString()).toEqual(takerTokenAmountBN.toString())
})
it('should get orders[0] quoteAmount as takerTokenAmount when set baseAmount 0.1 and is buy sell orders', () => {
const baseAmount = 0.1
const orders = simpleOrders.filter(o => o.side === 'SELL')
const fillTakerTokenAmountBN = getFillTakerTokenAmountBNByUpToOrders('BUY', baseAmount, orders, sntWethPairData)
let remainedAmountBN = toBN(baseAmount)
let takerTokenAmountBN = toBN(0)
let quoteAmountBN = getFillTakerTokenAmountBN('BUY', baseAmount, orders[0].price, sntWethPairData)
orders.some(so => {
const orderPrice = so.price
const orderAmount = so.amount
if (remainedAmountBN.gt(toBN(orderAmount))) {
takerTokenAmountBN = takerTokenAmountBN.plus(getFillTakerTokenAmountBN('BUY', orderAmount, orderPrice, sntWethPairData))
remainedAmountBN = remainedAmountBN.minus(toBN(orderAmount))
} else {
takerTokenAmountBN = takerTokenAmountBN.plus(getFillTakerTokenAmountBN('BUY', remainedAmountBN, orderPrice, sntWethPairData))
return true
}
})
expect(quoteAmountBN.toString()).toEqual(takerTokenAmountBN.toString())
expect(fillTakerTokenAmountBN.toString()).toEqual(takerTokenAmountBN.toString())
})
})
})
describe('test dex flow by dex utils', () => {
const baseQuote = {
base: 'SNT',
quote: 'WETH',
}
const testData = simpleOrders
const pair = sntWethPairData as Pair.ExchangePair
testData.map(simple => {
return {
...baseQuote,
...simple,
}
}).forEach(simpleOrder => {
// simpleOrder
// generateDexOrderWithoutSalt
// getSignedOrder
// orderBNToString
// orderStringToBN
// getSimpleOrder
// string order to orderbook item
// translateOrderBookToSimple
// getFillTakerTokenAmountBN
// getOrderFillRequest
describe(`test item ${simpleOrder.side} - ${simpleOrder.amount} - ${simpleOrder.price}`, () => {
const orderWithoutSalt = generateDexOrderWithoutSalt({
config: localConfig,
simpleOrder,
pair: sntWethPairData,
})
it('test generateDexOrderWithoutSalt', () => {
const { side, amount, price } = simpleOrder
const isBuy = side === 'BUY'
const { maker, takerTokenAddress, makerTokenAddress, makerTokenAmount, takerTokenAmount, expirationUnixTimestampSec, exchangeContractAddress, feeRecipient } = orderWithoutSalt
const makerAmountBN = isBuy ? fromUnitToDecimalBN(toBN(amount).times(price), pair.quote.decimal) : fromUnitToDecimalBN(amount, pair.base.decimal)
const takerAmountBN = isBuy ? fromUnitToDecimalBN(amount, pair.base.decimal) : fromUnitToDecimalBN(toBN(amount).times(price), pair.quote.decimal)
expect(feeRecipient).toBe(FEE_RECIPIENT)
expect(localConfig.wallet.address.toLowerCase()).toEqual(maker)
expect(takerTokenAddress).toEqual((isBuy ? pair.base.contractAddress : pair.quote.contractAddress).toLowerCase())
expect(makerTokenAddress).toEqual((isBuy ? pair.quote.contractAddress : pair.base.contractAddress).toLowerCase())
if (simpleOrder.expirationUnixTimestampSec) {
expect(+expirationUnixTimestampSec).toEqual(simpleOrder.expirationUnixTimestampSec)
} else {
expect(+expirationUnixTimestampSec).toBeLessThanOrEqual(getTimestamp() + 86400 * 365)
expect(+expirationUnixTimestampSec).toBeGreaterThanOrEqual(getTimestamp() + 86400 * 365 - 2)
}
expect(exchangeContractAddress).toEqual(localConfig.zeroEx.exchangeContractAddress.toLowerCase())
expect(makerAmountBN.eq(makerTokenAmount)).toBe(true)
expect(takerAmountBN.eq(takerTokenAmount)).toBe(true)
})
const signedOrder = getSignedOrder(orderWithoutSalt, localConfig)
it('test getSignedOrder', () => {
const orderHash = ZeroEx.getOrderHashHex(signedOrder)
expect(signatureUtils.isValidSignature(orderHash, signedOrder.ecSignature, localConfig.wallet.address.toLowerCase())).toBe(true)
})
const orderString = orderBNToString(signedOrder)
it('test orderBNToString', () => {
[
'maker',
'taker',
'makerTokenAmount',
'takerTokenAmount',
'makerTokenAddress',
'takerTokenAddress',
'expirationUnixTimestampSec',
'exchangeContractAddress',
'feeRecipient',
'makerFee',
'takerFee',
'salt',
].forEach((key) => {
expect(orderString[key]).toEqual(signedOrder[key].toString())
})
expect(_.isEqual(signedOrder.ecSignature, orderString.ecSignature)).toBe(true)
})
const orderBN = orderStringToBN(orderString)
it('test orderStringToBN', () => {
[
'maker',
'taker',
'makerTokenAddress',
'takerTokenAddress',
'exchangeContractAddress',
'feeRecipient',
].forEach((key) => {
expect(_.isString(orderBN[key])).toBe(true)
expect(orderBN[key]).toEqual(signedOrder[key])
});
[
'expirationUnixTimestampSec',
'makerTokenAmount',
'takerTokenAmount',
'makerFee',
'takerFee',
'salt',
].forEach((key) => {
expect(isBigNumber(orderBN[key])).toBe(true)
expect(orderBN[key].toString()).toBe(signedOrder[key].toString())
})
expect(_.isEqual(signedOrder.ecSignature, orderString.ecSignature)).toBe(true)
})
const gotSimpleOrder = getSimpleOrder({
order: orderString,
pair,
})
it('test getSimpleOrder', () => {
['price', 'amount', 'side', 'expirationUnixTimestampSec'].forEach(key => {
if (key !== 'expirationUnixTimestampSec' || simpleOrder.expirationUnixTimestampSec) {
expect(gotSimpleOrder[key]).toEqual(simpleOrder[key])
} else {
expect(gotSimpleOrder[key]).toBeLessThanOrEqual(getTimestamp() + 86400 * 365)
expect(gotSimpleOrder[key]).toBeGreaterThan(getTimestamp() + 86400 * 365 - 5)
}
})
})
const orderBookItem = {
rate: simpleOrder.price,
tradeType: simpleOrder.side === 'BUY' ? 'bid' : 'ask',
amountRemaining: simpleOrder.amount.toString(),
payload: orderString,
}
const translatedSimpleOrderFromOrderBook = translateOrderBookToSimple({
orderbookItems: [orderBookItem],
pair,
wallet,
})[0]
it('test translateOrderBookToSimple', () => {
['price', 'amount', 'side', 'expirationUnixTimestampSec'].forEach(key => {
if (key !== 'expirationUnixTimestampSec' || simpleOrder.expirationUnixTimestampSec) {
expect(translatedSimpleOrderFromOrderBook[key]).toEqual(simpleOrder[key])
} else {
expect(translatedSimpleOrderFromOrderBook[key]).toBeLessThanOrEqual(getTimestamp() + 86400 * 365)
expect(translatedSimpleOrderFromOrderBook[key]).toBeGreaterThan(getTimestamp() + 86400 * 365 - 5)
}
})
expect(translatedSimpleOrderFromOrderBook.rawOrder).toEqual(JSON.stringify(orderString))
})
const fillTakerTokenAmountBN = getFillTakerTokenAmountBN(
translatedSimpleOrderFromOrderBook.side === 'BUY' ? 'SELL' : 'BUY',
translatedSimpleOrderFromOrderBook.amount,
translatedSimpleOrderFromOrderBook.price,
pair,
)
it('test getFillTakerTokenAmountBN', () => {
expect(isBigNumber(fillTakerTokenAmountBN)).toBe(true)
expect(fillTakerTokenAmountBN.toNumber()).toEqual(signedOrder.takerTokenAmount.toNumber())
expect(fillTakerTokenAmountBN.eq(signedOrder.takerTokenAmount)).toBe(true)
})
it('test getOrderFillRequest', () => {
const orderFillReqest = getOrderFillRequest({
...baseQuote,
side: translatedSimpleOrderFromOrderBook.side === 'BUY' ? 'SELL' : 'BUY',
price: translatedSimpleOrderFromOrderBook.price,
amount: translatedSimpleOrderFromOrderBook.amount,
rawOrder: translatedSimpleOrderFromOrderBook.rawOrder,
}, pairs)
const { signedOrder, takerTokenFillAmount } = orderFillReqest
expect(_.isEqual(orderBNToString(signedOrder), orderString)).toBe(true)
expect(isBigNumber(takerTokenFillAmount)).toBe(true)
expect(takerTokenFillAmount.toNumber()).toEqual(signedOrder.takerTokenAmount.toNumber())
expect(takerTokenFillAmount.eq(signedOrder.takerTokenAmount)).toBe(true)
})
})
})
}) | the_stack |
module RefPhysics {
function sFloor(n: number) {
var s = n >= 0 ? 1 : -1;
return Math.floor(n * s) * s;
}
export class StateManager {
private sounds: Sounds.SoundEffect[];
public level: Levels.Level = null;
private controller: Game.Controller = null;
//Game-state, should be refactored
public currentXPosition: number;
public currentYPosition: number;
public currentZPosition: number;
public gravityAcceleration: number;
private slideAmount: number;
private slidingAccel: number;
private xMovementBase: number;
public yVelocity: number;
public zVelocity: number;
public fuelRemaining: number;
public oxygenRemaining: number;
private expectedXPosition: number;
private expectedYPosition: number;
private expectedZPosition: number;
public craftState: number;
public isDead: boolean;
private isOnGround: boolean;
private isOnDecelPad: boolean;
private isOnSlidingTile: boolean;
private isGoingUp: boolean = false;
private hasRunJumpOMaster: boolean = false;
public jumpOMasterInUse: boolean = false;
public jumpOMasterVelocityDelta: number = 0.0;
private offsetAtWhichNotInsideTile: number;
private jumpedFromYPosition: number;
public didWin: boolean = false;
public Log: string = '';
public lastJumpZ = 0.0;
constructor(managers: Managers.ManagerSet, level: Levels.Level, controller: Game.Controller) {
this.level = level;
this.controller = controller;
this.sounds = managers.Sounds.getMultiEffect('SFX.SND');
this.resetStateVars();
}
private resetStateVars(): void {
this.gravityAcceleration = -Math.floor(this.level.Gravity * 0x1680 / 0x190) / 0x80
this.currentZPosition = 3.0;
this.currentXPosition = 0x8000 / 0x80;
this.currentYPosition = 0x2800 / 0x80;
this.slideAmount = 0;
this.xMovementBase = 0;
this.yVelocity = 0;
this.zVelocity = 0;
this.fuelRemaining = 0x7530;
this.oxygenRemaining = 0x7530;
this.craftState = 0;
this.isDead = false;
this.isOnGround = true;
this.isOnDecelPad = false;
this.isOnSlidingTile = false;
this.isGoingUp = false;
this.offsetAtWhichNotInsideTile = 0;
this.jumpedFromYPosition = 0;
}
private currentPosToPosition(): Position {
return { getXPosition: () => this.currentXPosition, getYPosition: () => this.currentYPosition, getZPosition: () => this.currentZPosition };
}
private getPos(x: number, y: number, z: number): Position {
return { getXPosition: () => x, getYPosition: () => y, getZPosition: () => z };
}
private sanitizeFP32(n: number): number {
return Math.floor(n * 0x10000) / 0x10000;
}
private sanitizeFP16(n: number): number {
return Math.floor(n * 0x80) / 0x80;
}
private sanitizeVars(): void {
this.currentXPosition = Math.round(this.currentXPosition * 0x80) / 0x80;
this.currentYPosition = Math.round(this.currentYPosition * 0x80) / 0x80;
this.currentZPosition = Math.round(this.currentZPosition * 0x10000) / 0x10000;
this.expectedXPosition = Math.round(this.expectedXPosition * 0x80) / 0x80;
this.expectedYPosition = Math.round(this.expectedYPosition * 0x80) / 0x80;
this.expectedZPosition = Math.round(this.expectedZPosition * 0x10000) / 0x10000;
}
public runFrame(): void {
var controls = this.controller.update(this.currentPosToPosition());
this.sanitizeVars();
var canControl = this.craftState !== 4 && this.craftState !== 5;
//LOC 2308
this.logBP2308(controls); //DEAD
/*
if (this.currentZPosition >= 0x40 + 0x63a5 / 0x10000) {
debugger;
}*/
var cell = this.level.getCell(this.currentXPosition, this.currentYPosition, this.currentZPosition);
var isAboveNothing = cell.isEmpty();
var touchEffect: Levels.TouchEffect = Levels.TouchEffect.None;
this.isOnSlidingTile = false;
this.isOnDecelPad = false;
if (this.isOnGround) {
var y = this.currentYPosition;
if (Math.floor(y) == 0x2800 / 0x80 && cell.Tile != null) {
touchEffect = cell.Tile.Effect;
} else if (Math.floor(y) > 0x2800 / 0x80 && cell.Cube != null && cell.Cube.Height == y) {
touchEffect = cell.Cube.Effect;
}
this.logBP2369(controls, touchEffect);
this.applyTouchEffect(touchEffect);
this.isOnSlidingTile = touchEffect === Levels.TouchEffect.Slide;
this.isOnDecelPad = touchEffect === Levels.TouchEffect.Decelerate;
}
if (this.currentZPosition >= this.level.getLength()) {
//TODO: Game ending. Are we in a tunnel?
}
//LOC 2405
if (Math.abs(this.expectedYPosition - this.currentYPosition) > 0.01) {
if (this.slideAmount == 0 || this.offsetAtWhichNotInsideTile >= 2) {
var yvel = Math.abs(this.yVelocity);
if (yvel > (this.level.Gravity * 0x104 / 8 / 0x80)) {
if (this.yVelocity < 0) {
this.sounds[1].play();
}
this.yVelocity = -0.5 * this.yVelocity;
} else {
this.yVelocity = 0;
}
} else {
this.yVelocity = 0;
}
}
//LOC 249E
this.zVelocity += (canControl ? controls.AccelInput : 0) * 0x4B / 0x10000;
this.clampGlobalZVelocity();
//LOC 250F
if (!this.isOnSlidingTile) {
var canControl1 = (this.isGoingUp || isAboveNothing) && this.xMovementBase === 0 && this.yVelocity > 0 && (this.currentYPosition - this.jumpedFromYPosition) < 30;
var canControl2 = !this.isGoingUp && !isAboveNothing;
if (canControl1 || canControl2) {
this.xMovementBase = (canControl ? controls.TurnInput * 0x1D / 0x80 : 0);
}
}
//LOC 2554
if (!this.isGoingUp && !isAboveNothing && controls.JumpInput && this.level.Gravity < 0x14 && canControl) {
this.yVelocity = 0x480 / 0x80;
this.isGoingUp = true;
this.jumpedFromYPosition = this.currentYPosition;
this.lastJumpZ = this.currentZPosition;
}
//LOC 2590
//Something to do with the craft hitting max-height.
if (this.isGoingUp && !this.hasRunJumpOMaster && this.currentYPosition >= 110) {
this.runJumpOMaster(controls);
this.hasRunJumpOMaster = true;
}
//LOC 25C9
if (this.currentYPosition >= 0x28) {
this.yVelocity += this.gravityAcceleration;
this.yVelocity = sFloor(this.yVelocity * 0x80) / 0x80;
} else if (this.yVelocity > -105 / 0x80) {
this.yVelocity = -105 / 0x80;
}
//LOC 2619
this.expectedZPosition = this.isDead ? this.currentZPosition : this.currentZPosition + this.zVelocity;
var motionVel = this.zVelocity;
if (!this.isOnDecelPad) {
motionVel += 0x618 / 0x10000
}
var xMotion = sFloor(this.xMovementBase * 0x80) * sFloor(motionVel * 0x10000) / 0x10000 + this.slideAmount; //SHould we divide by some factor or is that just to account for 16vs8-bit Fixed-precision? 1A2:266B under loc 264C
this.expectedXPosition = this.isDead ? this.currentXPosition : this.currentXPosition + xMotion;
this.expectedYPosition = this.isDead ? this.currentYPosition : this.currentYPosition + this.yVelocity;
//LOC 2699
var minX = 0x2F80 / 0x80, maxX = 0xD080 / 0x80;
var currentX = this.currentXPosition, newX = this.expectedXPosition;
if ((currentX < minX && newX > maxX) || (newX < minX && currentX > maxX)) {
this.expectedXPosition = currentX;
}
//LOC 26BE
this.sanitizeVars();
this.logBP26C7(controls); //CAFE
this.moveShipAndConstraint();
this.sanitizeVars();
this.logBP26CD(controls); //FEED
if (this.currentZPosition != this.expectedZPosition && this.isInsideTile(this.currentXPosition, this.currentYPosition, this.expectedZPosition)) {
var bumpOff = 0x3a0 / 0x80;
if (!this.isInsideTile(this.currentXPosition - bumpOff, this.currentYPosition, this.expectedZPosition)) {
this.currentXPosition -= bumpOff;
this.expectedZPosition = this.currentZPosition;
this.sounds[2].play();
} else if (!this.isInsideTile(this.currentXPosition + bumpOff, this.currentYPosition, this.expectedZPosition)) {
this.currentXPosition += bumpOff;
this.expectedZPosition = this.currentZPosition;
this.sounds[2].play();
}
}
//LOC 2787
if (Math.abs(this.currentZPosition - this.expectedZPosition) > 0.01) {
if (this.zVelocity < 1.0 / 3.0 * 0x2aaa / 0x10000) {
this.zVelocity = 0.0;
this.sounds[2].play();
} else if (!this.isDead) {
this.isDead = true;
this.craftState = 1; //Exploded
this.sounds[0].play();
}
}
//LOC 2820
if (Math.abs(this.currentXPosition - this.expectedXPosition) > 0.01) {
this.xMovementBase = 0.0;
if (this.slideAmount !== 0.0) {
this.expectedXPosition = this.currentXPosition;
this.slideAmount = 0.0;
}
this.zVelocity -= 0x97 / 0x10000;
this.clampGlobalZVelocity();
}
//LOC 28BB
this.isOnGround = false;
if (this.yVelocity < 0 && this.expectedYPosition != this.currentYPosition) {
this.zVelocity += this.jumpOMasterVelocityDelta;
this.jumpOMasterVelocityDelta = 0.0;
this.hasRunJumpOMaster = false;
this.jumpOMasterInUse = false;
this.isGoingUp = false;
this.isOnGround = true;
this.slidingAccel = 0;
for (var i: number = 1; i <= 0xE; i++) {
if (!this.isInsideTile(this.currentXPosition + i, this.currentYPosition - 1.0 / 0x80, this.currentZPosition)) {
this.slidingAccel++;
this.offsetAtWhichNotInsideTile = i;
break;
}
}
for (var i: number = 1; i <= 0xE; i++) {
if (!this.isInsideTile(this.currentXPosition - i, this.currentYPosition - 1.0 / 0x80, this.currentZPosition)) {
this.slidingAccel--;
this.offsetAtWhichNotInsideTile = i;
break;
}
}
if (this.slidingAccel != 0) {
this.slideAmount += 0x11 * this.slidingAccel / 0x80;
} else {
this.slideAmount = 0;
}
}
//LOC 2A23 -- Deplete Oxygen
this.oxygenRemaining -= 0x7530 / (0x24 * this.level.Oxygen);
if (this.oxygenRemaining <= 0) {
this.oxygenRemaining = 0;
this.craftState = 5;
}
//LOC 2A4E -- Deplete fuel
this.fuelRemaining -= this.zVelocity * 0x7530 / this.level.Fuel;
if (this.fuelRemaining <= 0) {
this.fuelRemaining = 0;
this.craftState = 4;
}
if (this.currentZPosition >= this.level.getLength() - 0.5 && this.isInsideTunnel(this.currentXPosition, this.currentYPosition, this.currentZPosition)) {
this.didWin = true;
}
}
private applyTouchEffect(effect: Levels.TouchEffect) {
switch (effect) {
case Levels.TouchEffect.Accelerate:
this.zVelocity += 0x12F / 0x10000;
break;
case Levels.TouchEffect.Decelerate:
this.zVelocity -= 0x12F / 0x10000;
break;
case Levels.TouchEffect.Kill:
this.isDead = true;
break;
case Levels.TouchEffect.RefillOxygen:
if (this.craftState === 0) {
if (this.fuelRemaining < 0x6978 || this.oxygenRemaining < 0x6978) {
this.sounds[4].play();
}
this.fuelRemaining = 0x7530;
this.oxygenRemaining = 0x7530;
}
break;
}
this.clampGlobalZVelocity();
}
private clampGlobalZVelocity(): void {
this.zVelocity = this.clampZVelocity(this.zVelocity);
}
private clampZVelocity(z: number): number {
return Math.min(Math.max(0.0, z), 0x2AAA / 0x10000);
}
private isInsideTileY(yPos: number, distFromCenter: number, cell: Levels.Cell): boolean {
distFromCenter = Math.round(distFromCenter);
if (distFromCenter > 37) {
return false;
}
var tunCeils = [
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1E, 0x1E,
0x1E, 0x1D, 0x1D, 0x1D, 0x1C, 0x1B, 0x1A, 0x19,
0x18, 0x16, 0x14, 0x12, 0x11, 0xE];
var tunLows = [
0x10, 0x10, 0x10, 0x10, 0x0F, 0x0E, 0x0D, 0x0B,
0x08, 0x07, 0x06, 0x05, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
var y2 = yPos - 68;
if (cell.Tunnel != null && cell.Cube == null) {
return y2 > tunLows[distFromCenter] && y2 < tunCeils[distFromCenter];
} else if (cell.Tunnel == null && cell.Cube != null) {
return yPos < cell.Cube.Height;
} else if (cell.Tunnel != null && cell.Cube != null) {
return y2 > tunLows[distFromCenter] && yPos < cell.Cube.Height;
} else {
return false;
}
}
private isInsideTile(xPos: number, yPos: number, zPos: number): boolean {
var leftTile = this.level.getCell(xPos - 14, yPos, zPos);
var rightTile = this.level.getCell(xPos + 14, yPos, zPos);
if (!leftTile.isEmpty() || !rightTile.isEmpty()) {
if (yPos < 80 && yPos > 0x1e80 / 0x80) {
return true;
}
if (yPos < 0x2180 / 0x80) {
return false;
}
var centerTile = this.level.getCell(xPos, yPos, zPos);
var distanceFromCenter = 23 - (xPos - 49) % 46;
var var_A = -46;
if (distanceFromCenter < 0) {
distanceFromCenter = 1 - distanceFromCenter;
var_A = -var_A;
}
if (this.isInsideTileY(yPos, distanceFromCenter, centerTile)) {
return true;
}
centerTile = this.level.getCell(xPos + var_A, yPos, zPos);
if (this.isInsideTileY(yPos, 47 - distanceFromCenter, centerTile)) {
return true;
}
}
return false;
}
private isInsideTunnelY(yPos: number, distFromCenter: number, cell: Levels.Cell): boolean {
distFromCenter = Math.round(distFromCenter);
if (distFromCenter > 37) {
return false;
}
var tunCeils = [
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x1F, 0x1F, 0x1F, 0x1F, 0x1F, 0x1E, 0x1E,
0x1E, 0x1D, 0x1D, 0x1D, 0x1C, 0x1B, 0x1A, 0x19,
0x18, 0x16, 0x14, 0x12, 0x11, 0xE];
var tunLows = [
0x10, 0x10, 0x10, 0x10, 0x0F, 0x0E, 0x0D, 0x0B,
0x08, 0x07, 0x06, 0x05, 0x03, 0x03, 0x03, 0x03,
0x03, 0x03, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
var y2 = yPos - 68;
return cell.Tunnel != null && cell.Tile != null && y2 < tunLows[distFromCenter] && yPos >= 80;
}
private isInsideTunnel(xPos: number, yPos: number, zPos: number): boolean {
var leftTile = this.level.getCell(xPos - 14, yPos, zPos);
var rightTile = this.level.getCell(xPos + 14, yPos, zPos);
if (!leftTile.isEmpty() || !rightTile.isEmpty()) {
var centerTile = this.level.getCell(xPos, yPos, zPos);
var distanceFromCenter = 23 - (xPos - 49) % 46;
var var_A = -46;
if (distanceFromCenter < 0) {
distanceFromCenter = 1 - distanceFromCenter;
var_A = -var_A;
}
if (this.isInsideTunnelY(yPos, distanceFromCenter, centerTile)) {
return true;
}
centerTile = this.level.getCell(xPos + var_A, yPos, zPos);
if (this.isInsideTunnelY(yPos, 47 - distanceFromCenter, centerTile)) {
return true;
}
}
return false;
}
private moveShipAndConstraint(): void {
if (this.currentXPosition == this.expectedXPosition &&
this.currentYPosition == this.expectedYPosition &&
this.currentZPosition == this.expectedZPosition) {
return;
}
var iter = 1;
var interp16 = (a: number, b: number) => this.sanitizeFP16((b - a) * iter / 5 + a);
var interp32 = (a: number, b: number) => this.sanitizeFP32((b - a) * iter / 5 + a);
for (iter = 1; iter <= 5; iter++) {
if (this.isInsideTile(interp16(this.currentXPosition, this.expectedXPosition), interp16(this.currentYPosition, this.expectedYPosition), interp32(this.currentZPosition, this.expectedZPosition))) {
break;
}
}
iter--; //We care about the list iter we were *NOT* inside a tile
this.currentXPosition = interp16(this.currentXPosition, this.expectedXPosition);
this.currentYPosition = interp16(this.currentYPosition, this.expectedYPosition);
this.currentZPosition = interp32(this.currentZPosition, this.expectedZPosition);
var zGran = 0x1000 / 0x10000;
while (zGran != 0) {
//LOC 18F2
if (this.expectedZPosition - this.currentZPosition >= zGran && !this.isInsideTile(this.currentXPosition, this.currentYPosition, this.currentZPosition + zGran)) {
this.currentZPosition += zGran;
} else {
zGran /= 0x10;
zGran = Math.floor(zGran * 0x10000) / 0x10000;
}
}
this.currentZPosition = this.sanitizeFP32(this.currentZPosition);
var xGran = this.expectedXPosition > this.currentXPosition ? (0x7D / 0x80) : (-0x7D / 0x80);
while (Math.abs(xGran) > 0) {
if (Math.abs(this.expectedXPosition - this.currentXPosition) >= Math.abs(xGran) && !this.isInsideTile(this.currentXPosition + xGran, this.currentYPosition, this.currentZPosition)) {
this.currentXPosition += xGran;
} else {
xGran = sFloor(xGran / 5.0 * 0x80) / 0x80;
}
}
this.currentXPosition = this.sanitizeFP16(this.currentXPosition);
var yGran = this.expectedYPosition > this.currentYPosition ? (0x7D / 0x80) : (-0x7D / 0x80);
while (Math.abs(yGran) > 0) {
if (Math.abs(this.expectedYPosition - this.currentYPosition) >= Math.abs(yGran) && !this.isInsideTile(this.currentXPosition, this.currentYPosition + yGran, this.currentZPosition)) {
this.currentYPosition += yGran;
} else {
yGran = sFloor(yGran / 5.0 * 0x80) / 0x80;
}
}
this.currentYPosition = this.sanitizeFP16(this.currentYPosition);
}
private runJumpOMaster(controls: Game.ControllerState): void {
if (this.willLandOnTile(controls, this.currentXPosition, this.currentYPosition, this.currentZPosition, this.xMovementBase, this.yVelocity, this.zVelocity)) {
return;
}
var zVelocity = this.zVelocity;
var xMov = this.xMovementBase;
var i: number;
for (i = 1; i <= 6; i++) {
this.xMovementBase = this.sanitizeFP16(xMov + xMov * i / 10);
if (this.willLandOnTile(controls, this.currentXPosition, this.currentYPosition, this.currentZPosition, this.xMovementBase, this.yVelocity, this.zVelocity)) {
break;
}
this.xMovementBase = this.sanitizeFP16(xMov - xMov * i / 10);
if (this.willLandOnTile(controls, this.currentXPosition, this.currentYPosition, this.currentZPosition, this.xMovementBase, this.yVelocity, this.zVelocity)) {
break;
}
this.xMovementBase = xMov;
var zv2 = this.sanitizeFP32(zVelocity + zVelocity * i / 10);
this.zVelocity = this.clampZVelocity(zv2);
if (this.zVelocity == zv2) {
if (this.willLandOnTile(controls, this.currentXPosition, this.currentYPosition, this.currentZPosition, this.xMovementBase, this.yVelocity, this.zVelocity)) {
break;
}
}
zv2 = this.sanitizeFP32(zVelocity - zVelocity * i / 10);
this.zVelocity = this.clampZVelocity(zv2);
if (this.zVelocity == zv2) {
if (this.willLandOnTile(controls, this.currentXPosition, this.currentYPosition, this.currentZPosition, this.xMovementBase, this.yVelocity, this.zVelocity)) {
break;
}
}
this.zVelocity = zVelocity;
}
this.jumpOMasterVelocityDelta = zVelocity - this.zVelocity;
if (i <= 6) {
this.jumpOMasterInUse = true;
}
}
private isOnNothing(xPosition: number, zPosition: number) {
var cell = this.level.getCell(xPosition, 0, zPosition);
return cell.isEmpty() || (cell.Tile != null && cell.Tile.Effect == Levels.TouchEffect.Kill);
}
private willLandOnTile(controls: Game.ControllerState, xPos: number, yPos: number, zPos: number, xVelocity: number, yVelocity: number, zVelocity: number): boolean {
while (true) {
var currentX = xPos;
var currentSlideAmount = this.slideAmount;
var currentZ = zPos;
yVelocity += this.gravityAcceleration;
zPos += zVelocity;
var xRate = zVelocity + 0x618 / 0x10000;
var xMov = xVelocity * xRate * 128 + currentSlideAmount;
xPos += xMov;
if (xPos < 0x2F80 / 0x80 || xPos > 0xD080 / 0x80) {
return false;
}
yPos += yVelocity;
zVelocity = this.clampZVelocity(zVelocity + controls.AccelInput * 0x4B / 0x10000);
if (yPos <= 0x2800 / 0x80) {
return !this.isOnNothing(currentX, currentZ) && !this.isOnNothing(xPos, zPos);
}
}
}
private logBP2308(controls: Game.ControllerState) {
this.logString('BP2308_IDENT=dead');
this.logLongList(controls);
}
private logBP2369(controls: Game.ControllerState, te: Levels.TouchEffect) {
this.logString('BP2369_IDENT=beef');
}
private logBP26C7(controls: Game.ControllerState) {
this.logString('BP26C7_IDENT=cafe');
this.logLongList(controls);
}
private logBP26CD(controls: Game.ControllerState) {
this.logString('BP26CD_IDENT=feed');
this.logLongList(controls);
}
private logLongList(controls: Game.ControllerState) {
this.logInt('InAccel', controls.AccelInput);
this.logInt('InTurn', controls.TurnInput);
this.logInt('InJump', controls.JumpInput ? 1 : 0);
this.logFP16('CurrentX', this.currentXPosition);
this.logFP16('CurrentY', this.currentYPosition);
this.logFP32('CurrentZHigh', 'CurrentZLow', this.currentZPosition);
this.logFP16('XMovementBase', this.xMovementBase); //Should this be FP 16?
this.logFP16('YVelocity', this.yVelocity);
this.logFP32LH('ZVelocity', this.zVelocity);
this.logFP16('ExpectedX', this.expectedXPosition);
this.logFP16('ExpectedY', this.expectedYPosition);
this.logFP32('ExpectedZHigh', 'ExpectedZLow', this.expectedZPosition);
}
private toHexBytes(n: number): string {
return n.toString(16).toLowerCase();
}
private logFP16(name: string, n: number) {
n = Math.floor(n * 0x80);
if (n < 0) {
n = 0x10000 + n;
}
this.logString(name.toUpperCase() + '=' + this.toHexBytes(n));
}
private logFP32(nameHigh: string, nameLow: string, n: number) {
var high = Math.floor(n), low = Math.floor((n - high) * 0x10000);
this.logString(nameHigh.toUpperCase() + '=' + this.toHexBytes(high));
this.logString(nameLow.toUpperCase() + '=' + this.toHexBytes(low));
}
private logFP32LH(name: string, n: number) {
n = Math.floor(n * 0x10000);
this.logString(name.toUpperCase() + '=' + this.toHexBytes(n));
}
private logInt(name: string, n: number) {
if (n < 0) {
n = 0xffff;
}
this.logString(name.toUpperCase() + '=' + this.toHexBytes(n));
}
private logString(s: string): void { //TODO: Implement
this.Log += s + '\n';
}
}
} | the_stack |
* @packageDocumentation
* @module std
*/
//================================================================
import { List } from "../container/List";
import { InvalidArgument } from "../exception/InvalidArgument";
import { OutOfRange } from "../exception/OutOfRange";
import { ITimedLockable } from "../base/thread/ITimedLockable";
import { LockType } from "../internal/thread/LockType";
import { sleep_for } from "./global";
/**
* Counting semaphore.
*
* @author Jeongho Nam - https://github.com/samchon
*/
export class Semaphore<Max extends number = number>
{
private queue_: List<IResolver>;
private acquiring_: number;
private max_: Max;
/* ---------------------------------------------------------
CONSTRUCTORS
--------------------------------------------------------- */
/**
* Initializer Constructor.
*
* @param max Number of maximum sections acquirable.
*/
public constructor(max: Max)
{
this.queue_ = new List();
this.acquiring_ = 0;
this.max_ = max;
}
/**
* Get number of maximum sections lockable.
*
* @return Number of maximum sections lockable.
*/
public max(): Max
{
return this.max_;
}
/* ---------------------------------------------------------
ACQUIRANCES
--------------------------------------------------------- */
/**
* Acquires a section.
*
* Acquires a section until be {@link release released}. If all of the sections in the
* semaphore already have been acquired by others, the function call would be blocked until
* one of them returns its acquisition by calling the {@link release} method.
*
* In same reason, if you don't call the {@link release} function after you business, the
* others who want to {@link acquire} a section from the semaphore would be fall into the
* forever sleep. Therefore, never forget to calling the {@link release} function or utilize
* the {@link UniqueLock.lock} function instead with {@link Semaphore.get_lockable} to ensure
* the safety.
*/
public acquire(): Promise<void>
{
return new Promise<void>(resolve =>
{
if (this.acquiring_ < this.max_)
{
++this.acquiring_;
resolve();
}
else
{
this.queue_.push_back({
handler: resolve,
lockType: LockType.HOLD
});
}
});
}
/**
* Tries to acquire a section.
*
* Attempts to acquire a section without blocking. If succeeded to acquire a section from the
* semaphore immediately, it returns `true` directly. Otherwise all of the sections in the
* semaphore are full, the function gives up the trial immediately and returns `false`
* directly.
*
* Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do
* not call the {@link release} function after your business, the others who want to
* {@link acquire} a section from the semaphore would be fall into the forever sleep.
* Therefore, never forget to calling the {@link release} function or utilize the
* {@link UniqueLock.try_lock} function instead with {@link Semaphore.get_lockable} to ensure
* the safety.
*
* @return Whether succeeded to acquire or not.
*/
public async try_acquire(): Promise<boolean>
{
// ALL OR NOTHING
if (this.acquiring_ < this.max_)
{
++this.acquiring_;
return true;
}
else
return false;
}
/**
* Tries to acquire a section until timeout.
*
* Attempts to acquire a section from the semaphore until timeout. If succeeded to acquire a
* section until the timeout, it returns `true`. Otherwise failed to acquiring a section in
* given the time, the function gives up the trial and returns `false`.
*
* Failed to acquiring a section in the given time (returns `false`), it means that there're
* someone who have already {@link acquire acquired} sections and do not return them over the
* time expiration.
*
* Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do
* not call the {@link release} function after your business, the others who want to
* {@link acquire} a section from the semaphore would be fall into the forever sleep.
* Therefore, never forget to calling the {@link release} function or utilize the
* {@link UniqueLock.try_acquire_for} function instead with {@link Semaphore.get_lockable} to
* ensure the safety.
*
* @param ms The maximum miliseconds for waiting.
* @return Whether succeded to acquire or not.
*/
public async try_acquire_for(ms: number): Promise<boolean>
{
return new Promise<boolean>(resolve =>
{
if (this.acquiring_ < this.max_)
{
++this.acquiring_;
resolve(true);
}
else
{
// RESERVE ACQUIRE
const it: List.Iterator<IResolver> = this.queue_.insert(this.queue_.end(),
{
handler: resolve,
lockType: LockType.KNOCK
});
// AUTOMATIC RELEASE AFTER TIMEOUT
sleep_for(ms).then(() =>
{
// NOT YET, THEN DO RELEASE
if (it.value.handler !== null)
this._Cancel(it);
});
}
});
}
/**
* Tries to acquire a section until timeout.
*
* Attempts to acquire a section from the semaphore until time expiration. If succeeded to
* acquire a section until the time expiration, it returns `true`. Otherwise failed to
* acquiring a section in the given time, the function gives up the trial and returns `false`.
*
* Failed to acquiring a section in the given time (returns `false`), it means that there're
* someone who have already {@link acquire acquired} sections and do not return them over the
* time expiration.
*
* Note that, if you succeeded to acquire a section from the semaphore (returns `true) but do
* not call the {@link release} function after your business, the others who want to
* {@link acquire} a section from the semaphore would be fall into the forever sleep.
* Therefore, never forget to calling the {@link release} function or utilize the
* {@link UniqueLock.try_acquire_until} function instead with {@link Semaphore.get_lockable}
* to ensure the safety.
*
* @param at The maximum time point to wait.
* @return Whether succeded to acquire or not.
*/
public try_acquire_until(at: Date): Promise<boolean>
{
// COMPUTE MILLISECONDS TO WAIT
const now: Date = new Date();
const ms: number = at.getTime() - now.getTime();
return this.try_acquire_for(ms);
}
/* ---------------------------------------------------------
RELEASES
--------------------------------------------------------- */
/**
* Release sections.
*
* When you call this {@link release} method and there're someone who are currently blocked
* by attemping to {@link acquire} a section from this semaphore, *n* of them
* (FIFO; first-in-first-out) would {@link acquire} those {@link release released} sections
* and continue their executions.
*
* Otherwise, there's not anyone who is {@link acquire acquiring} the section or number of
* the blocked are less than *n*, the {@link OutOfRange} error would be thrown.
*
* > As you know, when you succeeded to {@link acquire} a section, you don't have to forget
* > to calling this {@link release} method after your business. If you forget it, it would
* > be a terrible situation for the others who're attempting to {@link acquire} a section
* > from this semaphore.
* >
* > However, if you utilize the {@link UniqueLock} with {@link Semaphore.get_lockable}, you
* > don't need to consider about this {@link release} method. Just define your business into
* > a callback function as a parameter of methods of the {@link UniqueLock}, then this
* > {@link release} method would be automatically called by the {@link UniqueLock} after the
* > business.
*
* @param n Number of sections to be released. Default is 1.
* @throw {@link OutOfRange} when *n* is greater than currently {@link acquire acquired} sections.
*/
public async release(n: number = 1): Promise<void>
{
//----
// VALIDATION
//----
if (n < 1)
throw new InvalidArgument(`Error on std.Semaphore.release(): parametric n is less than 1 -> (n = ${n}).`);
else if (n > this.max_)
throw new OutOfRange(`Error on std.Semaphore.release(): parametric n is greater than max -> (n = ${n}, max = ${this.max_}).`);
else if (n > this.acquiring_)
throw new OutOfRange(`Error on std.Semaphore.release(): parametric n is greater than acquiring -> (n = ${n}, acquiring = ${this.acquiring_}).`);
//----
// RELEASE
//----
const resolverList: IResolver[] = [];
while (this.queue_.empty() === false && resolverList.length < n)
{
// COPY IF HANDLER EXISTS
const resolver: IResolver = this.queue_.front();
if (resolver.handler !== null)
resolverList.push({ ...resolver });
// DESTRUCT
this.queue_.pop_front();
resolver.handler = null;
}
// COMPUTE REMAINED ACQUIRANCES
this.acquiring_ -= (n - resolverList.length);
// CALL HANDLERS
for (const resolver of resolverList)
if (resolver.lockType === LockType.HOLD)
resolver.handler!();
else
resolver.handler!(true);
}
private _Cancel(it: List.Iterator<IResolver>): void
{
// POP THE LISTENER
const handler: Function = it.value.handler!;
// DESTRUCTION
it.value.handler = null;
this.queue_.erase(it);
// RETURNS FAILURE
handler(false);
}
}
/**
*
*/
export namespace Semaphore
{
/**
* Capsules a {@link Semaphore} to be suitable for the {@link UniqueLock}.
*
* @param semaphore Target semaphore to capsule.
* @return Lockable instance suitable for the {@link UniqueLock}
*/
export function get_lockable<SemaphoreT extends Pick<Semaphore, "acquire"|"try_acquire"|"try_acquire_for"|"try_acquire_until"|"release">>
(semaphore: SemaphoreT): ITimedLockable
{
return new Lockable(semaphore);
}
/**
* @internal
*/
export class Lockable<SemaphoreT extends Pick<Semaphore, "acquire"|"try_acquire"|"try_acquire_for"|"try_acquire_until"|"release">>
implements ITimedLockable
{
private semahpore_: SemaphoreT;
public constructor(semaphore: SemaphoreT)
{
this.semahpore_ = semaphore;
}
public lock(): Promise<void>
{
return this.semahpore_.acquire();
}
public unlock(): Promise<void>
{
return this.semahpore_.release();
}
public try_lock(): Promise<boolean>
{
return this.semahpore_.try_acquire();
}
public try_lock_for(ms: number): Promise<boolean>
{
return this.semahpore_.try_acquire_for(ms);
}
public try_lock_until(at: Date): Promise<boolean>
{
return this.semahpore_.try_acquire_until(at);
}
}
}
interface IResolver
{
handler: Function | null;
lockType: LockType;
} | the_stack |
import { ArchivedConversationsHandlerService } from 'src/chat21-core/providers/abstract/archivedconversations-handler.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { IonContent, ModalController } from '@ionic/angular';
import { ActivatedRoute, Router, NavigationExtras } from '@angular/router';
// config
import { environment } from '../../../environments/environment';
// models
import { ConversationModel } from 'src/chat21-core/models/conversation';
import { UserModel } from 'src/chat21-core/models/user';
// utils
import { isInArray, checkPlatformIsMobile, presentModal, closeModal, convertMessage, isGroup, } from '../../../chat21-core/utils/utils';
import { EventsService } from '../../services/events-service';
import PerfectScrollbar from 'perfect-scrollbar'; // https://github.com/mdbootstrap/perfect-scrollbar
// services
import { ConversationsHandlerService } from 'src/chat21-core/providers/abstract/conversations-handler.service';
import { ChatManager } from 'src/chat21-core/providers/chat-manager';
import { NavProxyService } from '../../services/nav-proxy.service';
import { TiledeskService } from '../../services/tiledesk/tiledesk.service';
import { ConversationDetailPage } from '../conversation-detail/conversation-detail.page';
import { ContactsDirectoryPage } from '../contacts-directory/contacts-directory.page';
import { ProfileInfoPage } from '../profile-info/profile-info.page';
import { MessagingAuthService } from 'src/chat21-core/providers/abstract/messagingAuth.service';
import { CustomTranslateService } from 'src/chat21-core/providers/custom-translate.service';
import { ImageRepoService } from 'src/chat21-core/providers/abstract/image-repo.service';
import { TiledeskAuthService } from 'src/chat21-core/providers/tiledesk/tiledesk-auth.service';
import { AppConfigProvider } from '../../services/app-config';
// Logger
import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service';
import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance';
@Component({
selector: 'app-conversations-list',
templateUrl: './conversations-list.page.html',
styleUrls: ['./conversations-list.page.scss'],
})
export class ConversationListPage implements OnInit {
@ViewChild('ioncontentconvlist', { static: false }) ionContentConvList: IonContent;
private subscriptions: Array<string>;
public tenant: string;
public loggedUserUid: string;
public conversations: Array<ConversationModel> = [];
public archivedConversations: Array<ConversationModel> = [];
public uidConvSelected: string;
public conversationSelected: ConversationModel;
public uidReciverFromUrl: string;
public showPlaceholder = true;
public numberOpenConv = 0;
public loadingIsActive = true;
public supportMode = environment.supportMode;
public convertMessage = convertMessage;
private isShowMenuPage = false;
private logger: LoggerService = LoggerInstance.getInstance();
translationMapConversation: Map<string, string>;
stylesMap: Map<string, string>;
public conversationType = 'active'
headerTitle: string;
constructor(
private router: Router,
private route: ActivatedRoute,
private navService: NavProxyService,
public events: EventsService,
public modalController: ModalController,
// public databaseProvider: DatabaseProvider,
public conversationsHandlerService: ConversationsHandlerService,
public archivedConversationsHandlerService: ArchivedConversationsHandlerService,
public chatManager: ChatManager,
public messagingAuthService: MessagingAuthService,
public imageRepoService: ImageRepoService,
private translateService: CustomTranslateService,
public tiledeskService: TiledeskService,
public tiledeskAuthService: TiledeskAuthService,
public appConfigProvider: AppConfigProvider
) {
this.listenToAppCompConvsLengthOnInitConvs();
this.listenToLogoutEvent();
this.listenToSwPostMessage();
}
// -----------------------------------------------
// @ Lifehooks
// -----------------------------------------------
ngOnInit() {
}
ionViewWillEnter() {
this.logger.log('[CONVS-LIST-PAGE] ionViewWillEnter uidConvSelected', this.uidConvSelected);
this.listnerStart();
}
ionViewDidEnter() { }
listenToSwPostMessage() {
this.logger.log('[CONVS-LIST-PAGE] listenToNotificationCLick - CALLED: ');
const that = this;
if (navigator && navigator.serviceWorker) {
navigator.serviceWorker.addEventListener('message', function (event) {
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - Received a message from service worker event data: ', event.data);
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - Received a message from service worker event data data: ', event.data['data']);
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - Received a message from service worker event data data typeof: ', typeof event.data['data']);
let uidConvSelected = ''
if (event.data && event.data['conversWith']) {
uidConvSelected = event.data['conversWith'];
}
else {
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - DIFFERENT MSG');
return;
}
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - Received a message from service worker event dataObjct uidConvSelected: ', uidConvSelected);
that.logger.log('[CONVS-LIST-PAGE] FIREBASE-NOTIFICATION listenToNotificationCLick - Received a message from service worker that.conversations: ', that.conversations);
const conversationSelected = that.conversations.find(item => item.uid === uidConvSelected);
if (conversationSelected) {
that.conversationSelected = conversationSelected;
that.logger.log('[CONVS-LIST-PAGE] listenToNotificationCLick- Received a message from service worker event conversationSelected: ', that.conversationSelected);
that.navigateByUrl('active', uidConvSelected)
}
});
}
}
private listnerStart() {
const that = this;
this.chatManager.BSStart.subscribe((data: any) => {
this.logger.log('[CONVS-LIST-PAGE] ***** BSStart Current user *****', data);
if (data) {
that.initialize();
}
});
}
// ------------------------------------------------------------------ //
// Init convrsation handler
// ------------------------------------------------------------------ //
initConversationsHandler() {
this.conversations = this.conversationsHandlerService.conversations;
this.logger.log('[CONVS-LIST-PAGE] - CONVERSATIONS ', this.conversations)
// save conversationHandler in chatManager
this.chatManager.setConversationsHandler(this.conversationsHandlerService);
this.showPlaceholder = false;
}
initArchivedConversationsHandler() {
const keysConversation = ['CLOSED'];
this.translationMapConversation = this.translateService.translateLanguage(keysConversation);
this.archivedConversationsHandlerService.subscribeToConversations(() => {
this.logger.log('[CONVS-LIST-PAGE]-CONVS - conversations archived length ', this.archivedConversations.length)
});
this.archivedConversations = this.archivedConversationsHandlerService.archivedConversations;
this.logger.log('[CONVS-LIST-PAGE] archived conversation', this.archivedConversations)
// save archivedConversationsHandlerService in chatManager
this.chatManager.setArchivedConversationsHandler(this.archivedConversationsHandlerService);
this.logger.log('[CONVS-LIST-PAGE]-CONVS SubscribeToConversations - conversations archived length ', this.archivedConversations.length)
if (!this.archivedConversations || this.archivedConversations.length === 0) {
this.loadingIsActive = false;
}
}
// ----------------------------------------------------------------------------------------------------
// To display "No conversation yet" MESSAGE in conversazion list
// this.loadingIsActive is set to false only if on init there are not conversation
// otherwise loadingIsActive remains set to true and the message "No conversation yet" is not displayed
// to fix this
// - for the direct conversation
// ----------------------------------------------------------------------------------------------------
listenToAppCompConvsLengthOnInitConvs() {
this.events.subscribe('appcompSubscribeToConvs:loadingIsActive', (loadingIsActive) => {
this.logger.log('[CONVS-LIST-PAGE]-CONVS loadingIsActive', loadingIsActive);
if (loadingIsActive === false) {
this.loadingIsActive = false
}
});
}
listenToLogoutEvent() {
this.events.subscribe('profileInfoButtonClick:logout', (hasclickedlogout) => {
this.logger.info('[CONVS-LIST-PAGE] - listenToLogoutEvent - hasclickedlogout', hasclickedlogout);
this.conversations = []
this.conversationsHandlerService.conversations = [];
this.uidConvSelected = null;
this.logger.log('[CONVS-LIST-PAGE] - listenToLogoutEvent - CONVERSATIONS ', this.conversations)
this.logger.log('[CONVS-LIST-PAGE] - listenToLogoutEvent - uidConvSelected ', this.uidConvSelected)
if (hasclickedlogout === true) {
this.loadingIsActive = false
}
});
}
// ------------------------------------------------------------------
// SUBSCRIPTIONS
// ------------------------------------------------------------------
initSubscriptions() {
this.logger.log('[CONVS-LIST-PAGE] - CALLING - initSubscriptions ')
let key = '';
key = 'loggedUser:logout';
if (!isInArray(key, this.subscriptions)) {
this.subscriptions.push(key);
this.events.subscribe(key, this.subscribeLoggedUserLogout);
}
// key = 'readAllMessages';
// if (!isInArray(key, this.subscriptions)) {
// this.subscriptions.push(key);
// this.events.subscribe(key, this.readAllMessages);
// }
key = 'profileInfoButtonClick:changed';
if (!isInArray(key, this.subscriptions)) {
this.subscriptions.push(key);
this.events.subscribe(key, this.subscribeProfileInfoButtonClicked);
}
// this.conversationsHandlerService.readAllMessages.subscribe((conversationId: string) => {
// this.logger.log('[CONVS-LIST-PAGE] ***** readAllMessages *****', conversationId);
// this.readAllMessages(conversationId);
// });
this.conversationsHandlerService.conversationAdded.subscribe((conversation: ConversationModel) => {
// this.logger.log('[CONVS-LIST-PAGE] ***** conversationsAdded *****', conversation);
// that.conversationsChanged(conversations);
if (conversation) {
this.onImageLoaded(conversation)
this.onConversationLoaded(conversation)
}
});
this.conversationsHandlerService.conversationChanged.subscribe((conversation: ConversationModel) => {
// this.logger.log('[CONVS-LIST-PAGE] ***** subscribeConversationChanged *****', conversation);
// that.conversationsChanged(conversations)
if (conversation) {
this.onImageLoaded(conversation)
this.onConversationLoaded(conversation)
}
});
this.conversationsHandlerService.conversationRemoved.subscribe((conversation: ConversationModel) => {
this.logger.log('[CONVS-LIST-PAGE] ***** conversationsRemoved *****', conversation);
});
this.archivedConversationsHandlerService.archivedConversationAdded.subscribe((conversation: ConversationModel) => {
this.logger.log('[CONVS-LIST-PAGE] ***** archivedConversationAdded *****', conversation);
// that.conversationsChanged(conversations);
if (conversation) {
this.onImageLoaded(conversation)
this.onConversationLoaded(conversation)
}
});
}
// ------------------------------------------------------------------------------------
// @ SUBSCRIBE TO LOGGED USER LOGOUT ??????????? SEEMS NOT USED ?????????????????
// ------------------------------------------------------------------------------------
subscribeLoggedUserLogout = () => {
this.conversations = [];
this.uidConvSelected = null;
this.logger.log('[CONVS-LIST-PAGE] - subscribeLoggedUserLogout conversations ', this.conversations);
this.logger.log('[CONVS-LIST-PAGE] - subscribeLoggedUserLogout uidConvSelected ', this.uidConvSelected);
}
// ------------------------------------------------------------------------------------
// @ SUBSCRIBE TO CONVERSATION CHANGED ??????????? SEEMS NOT USED ?????????????????
// ------------------------------------------------------------------------------------
conversationsChanged = (conversations: ConversationModel[]) => {
this.numberOpenConv = this.conversationsHandlerService.countIsNew();
this.logger.log('[CONVS-LIST-PAGE] - conversationsChanged - NUMB OF CONVERSATIONS: ', this.numberOpenConv);
// console.log('conversationsChanged »»»»»»»»» uidConvSelected', that.conversations[0], that.uidConvSelected);
if (this.uidConvSelected && !this.conversationSelected) {
const conversationSelected = this.conversations.find(item => item.uid === this.uidConvSelected);
if (conversationSelected) {
this.conversationSelected = conversationSelected;
this.setUidConvSelected(this.uidConvSelected);
}
}
}
/**
* ::: subscribeChangedConversationSelected :::
* evento richiamato quando si seleziona un utente nell'elenco degli user
* apro dettaglio conversazione
*/
subscribeChangedConversationSelected = (user: UserModel, type: string) => {
this.logger.log('[CONVS-LIST-PAGE] ************** subscribeUidConvSelectedChanged navigateByUrl', user, type);
this.uidConvSelected = user.uid;
this.logger.log('[CONVS-LIST-PAGE] ************** uidConvSelected ', this.uidConvSelected);
// this.conversationsHandlerService.uidConvSelected = user.uid;
const conversationSelected = this.conversations.find(item => item.uid === this.uidConvSelected);
if (conversationSelected) {
this.logger.log('[CONVS-LIST-PAGE] --> uidConvSelected: ', this.conversationSelected, this.uidConvSelected);
this.conversationSelected = conversationSelected;
}
// this.router.navigateByUrl('conversation-detail/' + user.uid + '?conversationWithFullname=' + user.fullname);
}
/**
* ::: subscribeProfileInfoButtonClicked :::
* evento richiamato quando si seleziona bottone profile-info-modal
*/
subscribeProfileInfoButtonClicked = (event: string) => {
this.logger.log('[CONVS-LIST-PAGE] ************** subscribeProfileInfoButtonClicked: ', event);
if (event === 'displayArchived') {
this.initArchivedConversationsHandler();
// this.openArchivedConversationsModal()
this.conversationType = 'archived'
// let storedArchivedConv = localStorage.getItem('activeConversationSelected');
const keys = ['LABEL_ARCHIVED'];
this.headerTitle = this.translateService.translateLanguage(keys).get(keys[0]);
} else if (event === 'displayContact') {
this.conversationType = 'archived'
const keys = ['LABEL_CONTACTS'];
this.headerTitle = this.translateService.translateLanguage(keys).get(keys[0]);
}
}
onBackButtonFN(event) {
this.conversationType = 'active'
// let storedActiveConv = localStorage.getItem('activeConversationSelected');
// // console.log('ConversationListPage - storedActiveConv: ', storedActiveConv);
// if (storedActiveConv) {
// let storedActiveConvObjct = JSON.parse(storedActiveConv)
// console.log('ConversationListPage - storedActiveConv Objct: ', storedActiveConvObjct);
// this.navigateByUrl('active', storedActiveConvObjct.uid)
// } else {
// // da implementare se nn c'è stata nessuna conv attive selezionata
// }
}
// ------------------------------------------------------------------//
// END SUBSCRIPTIONS
// ------------------------------------------------------------------//
// :: handler degli eventi in output per i componenti delle modali
// ::::: vedi ARCHIVED-CONVERSATION-LIST --> MODALE
// initHandlerEventEmitter() {
// this.onConversationSelectedHandler.subscribe(conversation => {
// console.log('ConversationListPage - onversaation selectedddd', conversation)
// this.onConversationSelected(conversation)
// })
// this.onImageLoadedHandler.subscribe(conversation => {
// this.onImageLoaded(conversation)
// })
// this.onConversationLoadedHandler.subscribe(conversation => {
// this.onConversationLoaded(conversation)
// })
// }
// ------------------------------------------------------------------//
// BEGIN FUNCTIONS
// ------------------------------------------------------------------//
/**
* ::: initialize :::
*/
initialize() {
const appconfig = this.appConfigProvider.getConfig();
this.tenant = appconfig.firebaseConfig.tenant;
this.logger.log('[CONVS-LIST-PAGE] - initialize -> firebaseConfig tenant ', this.tenant);
this.loggedUserUid = this.tiledeskAuthService.getCurrentUser().uid;
this.subscriptions = [];
this.initConversationsHandler();
this.initVariables();
this.initSubscriptions();
// this.initHandlerEventEmitter();
}
/**
* ::: initVariables :::
* al caricamento della pagina:
* setto BUILD_VERSION prendendo il valore da PACKAGE
* recupero conversationWith -
* se vengo da dettaglio conversazione o da users con conversazione attiva ???? sarà sempre undefined da spostare in ionViewDidEnter
* recupero tenant
* imposto recipient se esiste nei parametri passati nell'url
* imposto uidConvSelected recuperando id ultima conversazione aperta dallo storage
*/
// --------------------------------------------------------
// It only works on BSStart.subscribe! it is useful or can be eliminated
// --------------------------------------------------------
initVariables() {
this.logger.log('[CONVS-LIST-PAGE] uidReciverFromUrl:: ' + this.uidReciverFromUrl);
this.logger.log('[CONVS-LIST-PAGE] loggedUserUid:: ' + this.loggedUserUid);
this.logger.log('[CONVS-LIST-PAGE] tenant:: ' + this.tenant);
if (this.route.component['name'] !== "ConversationListPage") {
if (this.route && this.route.snapshot && this.route.snapshot.firstChild) {
const IDConv = this.route.snapshot.firstChild.paramMap.get('IDConv');
this.logger.log('[CONVS-LIST-PAGE] conversationWith 2: ', IDConv);
if (IDConv) {
this.setUidConvSelected(IDConv);
} else {
this.logger.log('[CONVS-LIST-PAGE] conversationWith 2 (else): ', IDConv);
}
}
}
}
/**
* ::: setUidConvSelected :::
*/
setUidConvSelected(uidConvSelected: string, conversationType?: string,) {
this.logger.log('[CONVS-LIST-PAGE] setuidCOnvSelected', uidConvSelected)
this.uidConvSelected = uidConvSelected;
// this.conversationsHandlerService.uidConvSelected = uidConvSelected;
if (uidConvSelected) {
let conversationSelected;
if (conversationType === 'active') {
conversationSelected = this.conversations.find(item => item.uid === this.uidConvSelected);
} else if (conversationType === 'archived') {
conversationSelected = this.archivedConversations.find(item => item.uid === this.uidConvSelected);
}
if (conversationSelected) {
this.logger.log('[CONVS-LIST-PAGE] conversationSelected', conversationSelected);
this.logger.log('[CONVS-LIST-PAGE] la conv ', this.conversationSelected, ' has already been loaded');
this.conversationSelected = conversationSelected;
this.logger.log('[CONVS-LIST-PAGE] setUidConvSelected: ', this.conversationSelected);
}
}
}
onConversationSelected(conversation: ConversationModel) {
//console.log('returnSelectedConversation::', conversation)
if (conversation.archived) {
this.navigateByUrl('archived', conversation.uid)
this.logger.log('[CONVS-LIST-PAGE] onConversationSelected archived conversation.uid ', conversation.uid)
} else {
this.navigateByUrl('active', conversation.uid)
this.logger.log('[CONVS-LIST-PAGE] onConversationSelected active conversation.uid ', conversation.uid)
}
}
onImageLoaded(conversation: any) {
// this.logger.log('[CONVS-LIST-PAGE] onImageLoaded', conversation)
let conversation_with_fullname = conversation.sender_fullname;
let conversation_with = conversation.sender;
if (conversation.sender === this.loggedUserUid) {
conversation_with = conversation.recipient;
conversation_with_fullname = conversation.recipient_fullname;
} else if (isGroup(conversation)) {
// conversation_with_fullname = conv.sender_fullname;
// conv.last_message_text = conv.last_message_text;
conversation_with = conversation.recipient;
conversation_with_fullname = conversation.recipient_fullname;
}
if (!conversation_with.startsWith("support-group")) {
conversation.image = this.imageRepoService.getImagePhotoUrl(conversation_with)
}
}
onConversationLoaded(conversation: ConversationModel) {
this.logger.log('[CONVS-LIST-PAGE] onConversationLoaded ', conversation)
this.logger.log('[CONVS-LIST-PAGE] onConversationLoaded is new? ', conversation.is_new)
// if (conversation.is_new === false) {
// this.ionContentConvList.scrollToTop(0);
// }
const keys = ['YOU', 'SENT_AN_IMAGE', 'SENT_AN_ATTACHMENT'];
const translationMap = this.translateService.translateLanguage(keys);
// Fixes the bug: if a snippet of code is pasted and sent it is not displayed correctly in the convesations list
var regex = /<br\s*[\/]?>/gi;
if (conversation && conversation.last_message_text) {
conversation.last_message_text = conversation.last_message_text.replace(regex, "")
//FIX-BUG: 'YOU: YOU: YOU: text' on last-message-text in conversation-list
if (conversation.sender === this.loggedUserUid && !conversation.last_message_text.includes(': ')) {
// this.logger.log('[CONVS-LIST-PAGE] onConversationLoaded', conversation)
if (conversation.type !== "image" && conversation.type !== "file") {
conversation.last_message_text = translationMap.get('YOU') + ': ' + conversation.last_message_text;
} else if (conversation.type === "image") {
// this.logger.log('[CONVS-LIST-PAGE] HAS SENT AN IMAGE');
// this.logger.log("[CONVS-LIST-PAGE] translationMap.get('YOU')")
const SENT_AN_IMAGE = conversation['last_message_text'] = translationMap.get('SENT_AN_IMAGE')
conversation.last_message_text = translationMap.get('YOU') + ': ' + SENT_AN_IMAGE;
} else if (conversation.type === "file") {
// this.logger.log('[CONVS-LIST-PAGE] HAS SENT FILE')
const SENT_AN_ATTACHMENT = conversation['last_message_text'] = translationMap.get('SENT_AN_ATTACHMENT')
conversation.last_message_text = translationMap.get('YOU') + ': ' + SENT_AN_ATTACHMENT;
}
} else {
if (conversation.type === "image") {
// this.logger.log('[CONVS-LIST-PAGE] HAS SENT AN IMAGE');
// this.logger.log("[CONVS-LIST-PAGE] translationMap.get('YOU')")
const SENT_AN_IMAGE = conversation['last_message_text'] = translationMap.get('SENT_AN_IMAGE')
conversation.last_message_text = SENT_AN_IMAGE;
}
else if (conversation.type === "file") {
// this.logger.log('[CONVS-LIST-PAGE] HAS SENT FILE')
const SENT_AN_ATTACHMENT = conversation['last_message_text'] = translationMap.get('SENT_AN_ATTACHMENT')
conversation.last_message_text = SENT_AN_ATTACHMENT;
}
}
}
}
// isMarkdownLink(last_message_text) {
// this.logger.log('[CONVS-LIST-PAGE] isMarkdownLink 1')
// var regex = /^(^|[\n\r])\s*1\.\s.*\s+1\.\s$/
// let matchRegex = false
// if (regex.test(last_message_text)) {
// this.logger.log('[CONVS-LIST-PAGE] isMarkdownLink 2')
// matchRegex = true
// return matchRegex
// }
// }
navigateByUrl(converationType: string, uidConvSelected: string) {
this.logger.log('[CONVS-LIST-PAGE] navigateByUrl uidConvSelected: ', uidConvSelected);
this.logger.log('[CONVS-LIST-PAGE] navigateByUrl run this.setUidConvSelected');
this.logger.log('[CONVS-LIST-PAGE] navigateByUrl this.uidConvSelected ', this.uidConvSelected);
this.logger.log('[CONVS-LIST-PAGE] navigateByUrl this.conversationSelected ', this.conversationSelected)
this.setUidConvSelected(uidConvSelected, converationType);
if (checkPlatformIsMobile()) {
this.logger.log('[CONVS-LIST-PAGE] PLATFORM_MOBILE 1', this.navService);
let pageUrl = 'conversation-detail/' + this.uidConvSelected + '/' + this.conversationSelected.conversation_with_fullname + '/' + converationType;
this.logger.log('[CONVS-LIST-PAGE] pageURL', pageUrl)
this.router.navigateByUrl(pageUrl);
} else {
this.logger.log('[CONVS-LIST-PAGE] PLATFORM_DESKTOP 2', this.navService);
let pageUrl = 'conversation-detail/' + this.uidConvSelected;
if (this.conversationSelected && this.conversationSelected.conversation_with_fullname) {
pageUrl = 'conversation-detail/' + this.uidConvSelected + '/' + this.conversationSelected.conversation_with_fullname + '/' + converationType;
}
this.logger.log('[CONVS-LIST-PAGE] setUidConvSelected navigateByUrl--->: ', pageUrl);
this.router.navigateByUrl(pageUrl);
}
}
// ---------------------------------------------------------
// Opens the list of contacts for direct convs
// ---------------------------------------------------------
openContactsDirectory(event: any) {
const TOKEN = this.tiledeskAuthService.getTiledeskToken();
this.logger.log('[CONVS-LIST-PAGE] openContactsDirectory', TOKEN);
if (checkPlatformIsMobile()) {
presentModal(this.modalController, ContactsDirectoryPage, { token: TOKEN });
} else {
this.navService.push(ContactsDirectoryPage, { token: TOKEN });
}
}
closeContactsDirectory() {
try {
closeModal(this.modalController);
} catch (err) {
this.logger.error('[CONVS-LIST-PAGE] closeContactsDirectory -> error:', err);
}
}
// ---------------------------------------------------------
// Opens logged user profile modal
// ---------------------------------------------------------
openProfileInfo(event: any) {
const TOKEN = this.messagingAuthService.getToken();
this.logger.log('[CONVS-LIST-PAGE] open ProfileInfoPage TOKEN ', TOKEN);
if (checkPlatformIsMobile()) {
presentModal(this.modalController, ProfileInfoPage, { token: TOKEN })
} else {
this.navService.push(ProfileInfoPage, { token: TOKEN })
}
}
// ----------------------------------------------------------------------------------------------
// onCloseConversation
// https://github.com/chat21/chat21-cloud-functions/blob/master/docs/api.md#delete-a-conversation
// ----------------------------------------------------------------------------------------------
onCloseConversation(conversation: ConversationModel) {
// -------------------------------------------------------------------------------------
// Fix the display of the message "No conversation yet" when a conversation is archived
// but there are others in the list (happens when loadingIsActive is set to false because
// when is called the initConversationsHandler method there is not conversations)
// -------------------------------------------------------------------------------------
this.loadingIsActive = false;
// console.log('CONVS - CONV-LIST-PAGE onCloseConversation CONVS: ', conversation)
this.logger.log('[CONVS-LIST-PAGE] onCloseConversation loadingIsActive: ', this.loadingIsActive)
const conversationId = conversation.uid;
this.logger.log('[CONVS-LIST-PAGE] onCloseConversation conversationId: ', conversationId)
const conversationWith_segments = conversationId.split('-');
this.logger.log('[CONVS-LIST-PAGE] - conversationId_segments: ', conversationWith_segments);
// Removes the last element of the array if is = to the separator
if (conversationWith_segments[conversationWith_segments.length - 1] === '') {
conversationWith_segments.pop();
}
if (conversationWith_segments.length === 4) {
const lastArrayElement = conversationWith_segments[conversationWith_segments.length - 1]
this.logger.log('[CONVS-LIST-PAGE] - lastArrayElement ', lastArrayElement);
this.logger.log('[CONVS-LIST-PAGE] - lastArrayElement length', lastArrayElement.length);
if (lastArrayElement.length !== 32) {
conversationWith_segments.pop();
}
}
if (conversationId.startsWith("support-group")) {
let project_id = ''
if (conversationWith_segments.length === 4) {
project_id = conversationWith_segments[2];
const tiledeskToken = this.tiledeskAuthService.getTiledeskToken();
this.archiveSupportGroupConv(tiledeskToken, project_id, conversationId);
} else {
this.getProjectIdByConversationWith(conversationId)
}
} else {
this.conversationsHandlerService.archiveConversation(conversationId)
}
}
getProjectIdByConversationWith(conversationId: string) {
const tiledeskToken = this.tiledeskAuthService.getTiledeskToken();
this.tiledeskService.getProjectIdByConvRecipient(tiledeskToken, conversationId).subscribe(res => {
this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT RES', res);
if (res) {
const project_id = res.id_project
this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT project_id', project_id);
this.archiveSupportGroupConv(tiledeskToken, project_id, conversationId);
}
}, (error) => {
this.logger.error('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT - ERROR ', error);
}, () => {
this.logger.log('[INFO-CONTENT-COMP] - GET PROJECTID BY CONV RECIPIENT * COMPLETE *');
});
}
archiveSupportGroupConv(tiledeskToken, project_id, conversationId) {
this.logger.log('[CONVS-LIST-PAGE] - onCloseConversation projectId: ', project_id)
this.tiledeskService.closeSupportGroup(tiledeskToken, project_id, conversationId).subscribe(res => {
this.logger.log('[CONVS-LIST-PAGE] - onCloseConversation closeSupportGroup RES', res);
}, (error) => {
this.logger.error('[CONVS-LIST-PAGE] - onCloseConversation closeSupportGroup - ERROR ', error);
}, () => {
this.logger.log('[CONVS-LIST-PAGE] - onCloseConversation closeSupportGroup * COMPLETE *');
this.logger.log('[CONVS-LIST-PAGE] - onCloseConversation (closeSupportGroup) CONVS ', this.conversations)
this.logger.log('[CONVS-LIST-PAGE] - onCloseConversation (closeSupportGroup) CONVS LENGHT ', this.conversations.length)
});
}
public generateFake(count: number): Array<number> {
const indexes = [];
for (let i = 0; i < count; i++) {
indexes.push(i);
}
return indexes;
}
// ------------------------------------------------------------------
// !!! Not used methods !!!
// ------------------------------------------------------------------
// /**
// * ::: openArchivedConversationsPage :::
// * Open the archived conversations page
// * (metodo richiamato da html)
// */
// openArchivedConversationsPage() {
// this.logger.log('[CONVS-LIST-PAGE] openArchivedConversationsPage');
// }
// // info page
// returnCloseInfoPage() {
// this.logger.log('[CONVS-LIST-PAGE] returnCloseInfoPage');
// // this.isShowMenuPage = false;
// this.initialize();
// }
// private navigatePage() {
// this.logger.log('[CONVS-LIST-PAGE] navigatePage:: >>>> conversationSelected ', this.conversationSelected);
// let urlPage = 'detail/';
// if (this.conversationSelected) {
// // urlPage = 'conversation-detail/' + this.uidConvSelected;
// urlPage = 'conversation-detail/' + this.uidConvSelected + '/' + this.conversationSelected.conversation_with_fullname;
// // this.openDetailsWithState(this.conversationSelected);
// }
// // else {
// // this.router.navigateByUrl('detail');
// // }
// const navigationExtras: NavigationExtras = {
// state: {
// conversationSelected: this.conversationSelected
// }
// };
// this.navService.openPage(urlPage, ConversationDetailPage, navigationExtras);
// }
// openDetailsWithState(conversationSelected) {
// console.log('openDetailsWithState:: >>>> conversationSelected ', conversationSelected);
// let navigationExtras: NavigationExtras = {
// state: {
// conversationSelected: conversationSelected
// }
// };
// this.router.navigate(['conversation-detail/' + this.uidConvSelected], navigationExtras);
// }
// /**
// * ::: subscribeLoggedUserLogin :::
// * effettuato il login:
// * 1 - imposto loggedUser
// * 2 - dismetto modale
// * 3 - inizializzo elenco conversazioni
// */
// subscribeLoggedUserLogin = (user: any) => {
// console.log('3 ************** subscribeLoggedUserLogin', user);
// this.loggedUser = user;
// try {
// closeModal(this.modalController);
// } catch (err) {
// console.error('-> error:', err);
// }
// this.initialize();
// }
/**
* ::: conversationsChanged :::
* evento richiamato su add, change, remove dell'elenco delle conversazioni
* 1 - aggiorno elenco conversazioni
* 2 - aggiorno il conto delle nuove conversazioni
* 4 - se esiste un uidReciverFromUrl (passato nell'url)
* e se esiste una conversazione con lo stesso id di uidReciverFromUrl
* imposto questa come conversazione attiva (operazione da fare una sola volta al caricamento delle conversazioni)
* e la carico nella pagina di dettaglio e azzero la variabile uidReciverFromUrl!!!
* 5 - altrimenti se esiste una conversazione con lo stesso id della conversazione attiva
* e la pagina di dettaglio è vuota (placeholder), carico la conversazione attiva (uidConvSelected) nella pagina di dettaglio
* (operazione da fare una sola volta al caricamento delle conversazioni)
*/
// ------------------------------------------------------------------------------------
// ::: readAllMessages ::: ??????????? SEEMS NOT USED ?????????????????
// when all chat messages are displayed,
// that is when in the conversation detail I go to the bottom of the page,
// the readAllMessages event is triggered and is intercepted in the conversation list
// and modify the current conversation by bringing is_new to false
// ------------------------------------------------------------------------------------
// readAllMessages = (uid: string) => {
// this.logger.log('[CONVS-LIST-PAGE] readAllMessages', uid);
// const conversationSelected = this.conversations.find(item => item.uid === this.uidConvSelected);
// if (conversationSelected) {
// conversationSelected.is_new = false;
// conversationSelected.status = '0';
// conversationSelected.selected = true;
// }
// }
} | the_stack |
namespace LiteMol.Extensions.DensityStreaming {
'use strict';
import Rx = Bootstrap.Rx
import Entity = Bootstrap.Entity
import Transformer = Bootstrap.Entity.Transformer
import Utils = Bootstrap.Utils
import Interactivity = Bootstrap.Interactivity
const ToastKey = '__ShowDynamicDensity-toast';
type Box = { a: number[], b: number[] };
type Channel = Core.Formats.Density.Data
export class Behaviour implements Bootstrap.Behaviour.Dynamic {
private obs: Rx.IDisposable[] = [];
private server: string;
private behaviour: Entity.Behaviour.Any;
private groups = {
requested: Core.Utils.FastSet.create<string>(),
shown: Core.Utils.FastSet.create<string>(),
locked: Core.Utils.FastSet.create<string>(),
toBeRemoved: Core.Utils.FastSet.create<string>()
};
private download: Bootstrap.Task.Running<ArrayBuffer> | undefined = void 0;
private selectionBox: Box | undefined = void 0;
private modelBoundingBox: Box | undefined = void 0;
private channels: { [name: string]: Channel } | undefined = void 0;
private cache = Bootstrap.Utils.LRUCache.create<{ [name: string]: Channel }>(25);
private performance = new Core.Utils.PerformanceMonitor();
private wasCached = false;
private types: FieldType[];
private areBoxesSame(b: Box) {
if (!this.selectionBox) return false;
for (let i = 0; i < 3; i++) {
if (b.a[i] !== this.selectionBox.a[i] || b.b[i] !== this.selectionBox.b[i]) return false;
}
return true;
}
private getModelBoundingBox(): Box {
if (this.modelBoundingBox) return this.modelBoundingBox;
const sourceMolecule = Utils.Molecule.findMolecule(this.behaviour)!;
const { bottomLeft: a, topRight: b } = Utils.Molecule.getBox(sourceMolecule.props.molecule.models[0], sourceMolecule.props.molecule.models[0].data.atoms.indices, this.params.showEverythingExtent);
this.modelBoundingBox = { a, b};
return this.modelBoundingBox;
}
private stop() {
if (this.download) {
this.download.tryAbort();
this.download = void 0;
}
}
private remove(ref: string) {
for (const e of this.context.select(ref)) Bootstrap.Tree.remove(e);
this.groups.toBeRemoved.delete(ref);
}
private clear() {
this.stop();
this.groups.requested.forEach(g => this.groups.toBeRemoved.add(g));
this.groups.locked.forEach(g => this.groups.toBeRemoved.add(g));
this.groups.shown.forEach(g => { if (!this.groups.locked.has(g)) this.remove(g); });
this.groups.shown.clear();
this.channels = void 0;
}
private groupDone(ref: string, ok: boolean) {
this.groups.requested.delete(ref);
if (this.groups.toBeRemoved.has(ref)) {
this.remove(ref);
} else if (ok) {
this.groups.shown.add(ref);
}
}
private checkResult(data: Core.Formats.CIF.File) {
const server = data.dataBlocks.filter(b => b.header === 'SERVER')[0];
if (!server) return false;
const cat = server.getCategory('_density_server_result');
if (!cat) return false;
if (cat.getColumn('is_empty').getString(0) === 'yes' || cat.getColumn('has_error').getString(0) === 'yes') {
return false;
}
return true;
}
private apply(b: Bootstrap.Tree.Transform.Builder) {
return Bootstrap.Tree.Transform.apply(this.context, b).run();
}
private finish() {
this.performance.end('query');
this.context.logger.info(`[Density] Streaming done in ${this.performance.formatTime('query')}${this.wasCached ? ' (cached)' : ''}.`);
}
private async createXray() {
try {
if (!this.channels) return;
this.syncStyles();
const twoF = this.channels!['2FO-FC'];
const oneF = this.channels!['FO-FC'];
const action = Bootstrap.Tree.Transform.build();
const ref = Utils.generateUUID();
this.groups.requested.add(ref);
const group = action.add(this.behaviour, Transformer.Basic.CreateGroup, { label: 'Density' }, { ref, isHidden: true })
const styles = this.params;
group.then(Transformer.Density.CreateFromData, { id: '2Fo-Fc', data: twoF }, { ref: ref + '2Fo-Fc-data' })
group.then(Transformer.Density.CreateFromData, { id: 'Fo-Fc', data: oneF }, { ref: ref + 'Fo-Fc-data' });
await this.apply(action);
const a = this.apply(Bootstrap.Tree.Transform.build().add(ref + '2Fo-Fc-data', Transformer.Density.CreateVisual, { style: styles['2Fo-Fc'] }, { ref: ref + '2Fo-Fc' }));
const b = this.apply(Bootstrap.Tree.Transform.build().add(ref + 'Fo-Fc-data', Transformer.Density.CreateVisual, { style: styles['Fo-Fc(+ve)'] }, { ref: ref + 'Fo-Fc(+ve)' }));
const c = this.apply(Bootstrap.Tree.Transform.build().add(ref + 'Fo-Fc-data', Transformer.Density.CreateVisual, { style: styles['Fo-Fc(-ve)'] }, { ref: ref + 'Fo-Fc(-ve)' }));
await a;
await b;
await c;
this.finish();
this.groupDone(ref, true);
} catch (e) {
this.context.logger.error('[Density] ' + e);
}
}
private createEm() {
try {
if (!this.channels) return;
this.syncStyles();
const emd = this.channels!['EM'];
const action = Bootstrap.Tree.Transform.build();
const ref = Utils.generateUUID();
this.groups.requested.add(ref);
const styles = this.params;
action.add(this.behaviour, Transformer.Basic.CreateGroup, { label: 'Density' }, { ref, isHidden: true })
.then(Transformer.Density.CreateFromData, { id: 'EM', data: emd })
.then(Transformer.Density.CreateVisual, { style: styles['EM'] }, { ref: ref + 'EM' });
Bootstrap.Tree.Transform.apply(this.context, action).run()
.then(() => { this.finish(); this.groupDone(ref, true); })
.catch(() => this.groupDone(ref, false));
} catch (e) {
this.context.logger.error('[Density] ' + e);
}
}
private extendSelectionBox(): Box {
const { a, b } = this.selectionBox!;
const r = this.params.radius;
return {
a: a.map(v => v - r),
b: b.map(v => v + r),
}
}
private isSameMolecule(info: Interactivity.Info.Selection) {
const sourceMolecule = Utils.Molecule.findMolecule(this.behaviour);
const infoMolecule = Utils.Molecule.findMolecule(info.source);
return sourceMolecule === infoMolecule;
}
private static getChannel(data: Core.Formats.CIF.File, name: string): Channel | undefined {
const block = data.dataBlocks.filter(b => b.header === name)[0];
if (!block) {
return void 0;
}
const density = Core.Formats.Density.CIF.parse(block);
if (density.isError) return void 0;
return density.result;
}
private noChannels() {
this.context.logger.warning('Density Streaming: No data.');
return void 0;
}
private parseChannels(data: ArrayBuffer) {
const cif = Core.Formats.CIF.Binary.parse(data);
if (cif.isError || !this.checkResult(cif.result)) return this.noChannels();
if (this.params.source === 'EM') {
const ch = Behaviour.getChannel(cif.result, 'EM');
if (!ch) return this.noChannels();
return { 'EM': ch };
} else {
const twoF = Behaviour.getChannel(cif.result, '2FO-FC');
if (!twoF) return this.noChannels();
const oneF = Behaviour.getChannel(cif.result, 'FO-FC');
if (!oneF) return this.noChannels();
return { '2FO-FC': twoF, 'FO-FC': oneF };
}
}
private query(box?: Box) {
this.clear();
let url =
`${this.server}`
+ `/${this.params.source}`
+ `/${this.params.id}`;
if (box) {
const { a, b } = box;
url += `/box`
+ `/${a.map(v => Math.round(1000 * v) / 1000).join(',')}`
+ `/${b.map(v => Math.round(1000 * v) / 1000).join(',')}`;
} else {
url += `/cell`;
}
url += `?detail=${this.params.detailLevel}`;
this.performance.start('query');
const channels = Bootstrap.Utils.LRUCache.get(this.cache, url);
if (channels) {
this.clear();
this.channels = channels;
this.wasCached = true;
if (this.params.source === 'EM') this.createEm();
else this.createXray();
return;
}
this.download = Utils.ajaxGetArrayBuffer(url, 'Density').runWithContext(this.context);
this.download.result.then(data => {
this.clear();
this.channels = this.parseChannels(data) as Behaviour['channels'];
if (!this.channels) return;
this.wasCached = false;
Bootstrap.Utils.LRUCache.set(this.cache, url, this.channels);
if (this.params.source === 'EM') this.createEm();
else this.createXray();
});
}
private tryUpdateSelectionDataBox(info: Interactivity.Info) {
const i = info as Interactivity.Info.Selection;
if (!Interactivity.Molecule.isMoleculeModelInteractivity(info) || !this.isSameMolecule(i)) {
const changed = this.selectionBox !== void 0;
this.selectionBox = void 0;
return changed;
}
const model = Utils.Molecule.findModel(i.source)!;
let elems = i.elements;
const m = model.props.model;
if (i.elements!.length === 1) {
elems = Utils.Molecule.getResidueIndices(m, i.elements![0]);
}
const { bottomLeft:a, topRight:b } = Utils.Molecule.getBox(m, elems!, 0);
const box: Box = { a, b };
if (this.areBoxesSame(box)) {
return false;
} else {
this.selectionBox = box;
return true;
}
}
private async update() {
Bootstrap.Command.Toast.Hide.dispatch(this.context, { key: ToastKey });
if (this.params.displayType === 'Everything') {
if (this.params.source === 'EM') {
if (this.params.forceBox) this.query(this.getModelBoundingBox());
else this.query();
} else {
this.query(this.getModelBoundingBox());
}
} else {
if (this.selectionBox) {
this.query(this.extendSelectionBox());
} else {
this.clear();
}
}
}
private toSigma(type: FieldType) {;
const index = this.params.header.channels.indexOf(IsoInfo[type].dataKey);
const valuesInfo = this.params.header.sampling[0].valuesInfo[index];
const value = this.params.isoValues[type]!;
return (value - valuesInfo.mean) / valuesInfo.sigma;
}
private syncStyles() {
const taskType: Bootstrap.Task.Type = this.params.displayType === 'Everything'
? 'Background' : (this.params.radius > 15 ? 'Background' : 'Silent');
const isSigma = this.params.isoValueType === Bootstrap.Visualization.Density.IsoValueType.Sigma;
for (const t of this.types) {
const oldStyle = this.params[t]!;
const oldParams = oldStyle.params;
const isoValue = isSigma
? this.params.isoValues[t]!
: this.toSigma(t);
this.params[t] = { ...oldStyle, taskType, params: { ...oldParams, isoValueType: Bootstrap.Visualization.Density.IsoValueType.Sigma, isoValue } };
}
}
private updateVisual(v: Entity.Density.Visual, style: Bootstrap.Visualization.Density.Style) {
return Entity.Transformer.Density.CreateVisual.create({ style }, { ref: v.ref }).update(this.context, v).run();
}
private async invalidateStyles() {
if (this.groups.shown.size === 0) return;
this.syncStyles();
const styles = this.params;
// cache the refs and lock them
const refs: string[] = [];
this.groups.shown.forEach(r => {
refs.push(r);
this.groups.locked.add(r);
});
// update all the existing visuals.
for (const t of this.types) {
const s = styles[t];
if (!s) continue;
const vs = this.context.select(Bootstrap.Tree.Selection.byRef(...refs.map(r => r + t)));
for (const v of vs) {
await this.updateVisual(v as Entity.Density.Visual, s);
}
}
// unlock and delete if the request is pending
for (const r of refs) {
this.groups.locked.delete(r);
if (this.groups.toBeRemoved.has(r)) this.remove(r);
}
}
async invalidateParams(newParams: CreateStreamingParams): Promise<void> {
const oldParams = this.params;
if (oldParams.displayType !== newParams.displayType
|| oldParams.detailLevel !== newParams.detailLevel
|| oldParams.radius !== newParams.radius) {
this.params = newParams;
this.update();
return;
}
this.params = newParams;
await this.invalidateStyles();
}
dispose() {
this.clear();
Bootstrap.Command.Toast.Hide.dispatch(this.context, { key: ToastKey });
for (const o of this.obs) o.dispose();
this.obs = [];
}
register(behaviour: Entity.Behaviour.Any) {
this.behaviour = behaviour;
const message = this.params.source === 'X-ray'
? 'Streaming enabled, click on a residue or an atom to view the data.'
: `Streaming enabled, showing full surface. To view higher detail, use 'Around Selection' mode.`;
Bootstrap.Command.Toast.Show.dispatch(this.context, { key: ToastKey, title: 'Density', message, timeoutMs: 30 * 1000 });
this.obs.push(this.context.behaviours.select.subscribe(e => {
if (this.tryUpdateSelectionDataBox(e)) {
if (this.params.displayType === 'Around Selection') {
this.update();
}
}
}));
if (this.params.displayType === 'Everything') this.update();
}
constructor(public context: Bootstrap.Context, public params: CreateStreamingParams) {
this.server = params.server;
if (this.server[this.server.length - 1] === '/') this.server = this.server.substr(0, this.server.length - 1);
if (params.source === 'EM') {
this.types = ['EM'];
} else {
this.types = ['2Fo-Fc', 'Fo-Fc(+ve)', 'Fo-Fc(-ve)'];
}
}
}
} | the_stack |
import { d3, initChart } from './c3-helper'
describe('c3 chart shape bar', function() {
'use strict'
var chart, args
beforeEach(function(done) {
chart = initChart(chart, args, done)
})
describe('Path boxes', function() {
beforeAll(function() {
args = {
data: {
columns: [['data1', 30]],
type: 'bar'
},
bar: {
width: {
max: 40
}
}
}
})
it('bars should have expected Path Box', function() {
var expected = {
x: 279,
y: 40,
width: 40,
height: 387
}
var shapes = chart.internal.main
.selectAll('.' + chart.internal.CLASS.shapes)
.selectAll('.' + chart.internal.CLASS.shape)
shapes.each(function() {
var pathBox = chart.internal.getPathBox(this)
expect(pathBox.x).toBeCloseTo(expected.x, -1)
expect(pathBox.y).toBeCloseTo(expected.y, -1)
expect(pathBox.width).toBeCloseTo(expected.width, -1)
expect(pathBox.height).toBeCloseTo(expected.height, -1)
})
})
})
describe('with groups', function() {
describe('with indexed data', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, -100, 400, -150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
groups: [['data1', 'data2']],
type: 'bar'
}
}
})
it('should be stacked', function() {
var expectedBottom = [275, 293, 365, 281, 395, 290]
chart.internal.main
.selectAll('.c3-bars-data1 .c3-bar')
.each(function(d, i) {
var rect = d3
.select(this)
.node()
.getBoundingClientRect()
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1)
})
})
})
describe('with timeseries data', function() {
beforeAll(function() {
args = {
data: {
x: 'date',
columns: [
[
'date',
'2012-12-24',
'2012-12-25',
'2012-12-26',
'2012-12-27',
'2012-12-28',
'2012-12-29'
],
['data1', 30, 200, -100, 400, -150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
groups: [['data1', 'data2']],
type: 'bar'
},
axis: {
x: {
type: 'timeseries'
}
}
}
})
it('should be stacked', function() {
var expectedBottom = [275, 293, 365, 281, 395, 290]
chart.internal.main
.selectAll('.c3-bars-data1 .c3-bar')
.each(function(d, i) {
var rect = d3
.select(this)
.node()
.getBoundingClientRect()
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1)
})
})
})
describe('with category data', function() {
beforeAll(function() {
args = {
data: {
x: 'date',
columns: [
[
'date',
'2012-12-24',
'2012-12-25',
'2012-12-26',
'2012-12-27',
'2012-12-28',
'2012-12-29'
],
['data1', 30, 200, -100, 400, -150, 250],
['data2', 50, 20, 10, 40, 15, 25]
],
groups: [['data1', 'data2']],
type: 'bar'
},
axis: {
x: {
type: 'category'
}
}
}
})
it('should be stacked', function() {
var expectedBottom = [275, 293, 365, 281, 395, 290]
chart.internal.main
.selectAll('.c3-bars-data1 .c3-bar')
.each(function(d, i) {
var rect = d3
.select(this)
.node()
.getBoundingClientRect()
expect(rect.bottom).toBeCloseTo(expectedBottom[i], -1)
})
})
})
})
describe('internal.isWithinBar', function() {
describe('with normal axis', function() {
beforeAll(function() {
args = {
data: {
columns: [
['data1', 30, 200, 100, 400, -150, 250],
['data2', 50, 20, 10, 40, 15, 25],
['data3', -150, 120, 110, 140, 115, 125]
],
type: 'bar'
},
axis: {
rotated: false
}
}
})
it('should not be within bar', function() {
var bar = d3.select('.c3-target-data1 .c3-bar-0').node()
expect(chart.internal.isWithinBar([0, 0], bar)).toBeFalsy()
})
it('should be within bar', function() {
var bar = d3.select('.c3-target-data1 .c3-bar-0').node()
expect(chart.internal.isWithinBar([31, 280], bar)).toBeTruthy()
})
it('should not be within bar of negative value', function() {
var bar = d3.select('.c3-target-data3 .c3-bar-0').node()
expect(chart.internal.isWithinBar([68, 280], bar)).toBeFalsy()
})
it('should be within bar of negative value', function() {
var bar = d3.select('.c3-target-data3 .c3-bar-0').node()
expect(chart.internal.isWithinBar([68, 350], bar)).toBeTruthy()
})
})
describe('with rotated axis', function() {
beforeAll(function() {
args.axis.rotated = true
})
it('should not be within bar', function() {
var bar = d3.select('.c3-target-data1 .c3-bar-0').node()
expect(chart.internal.isWithinBar([0, 0], bar)).toBeFalsy()
})
it('should be within bar', function() {
var bar = d3.select('.c3-target-data1 .c3-bar-0').node()
expect(chart.internal.isWithinBar([190, 20], bar)).toBeTruthy()
})
it('should be within bar of negative value', function() {
var bar = d3.select('.c3-target-data3 .c3-bar-0').node()
expect(chart.internal.isWithinBar([68, 50], bar)).toBeTruthy()
})
})
})
describe('bar spacing', function() {
var createArgs = function(spacing) {
return {
size: {
width: 500
},
data: {
columns: [
['data1', 30, 200, 100],
['data2', 50, 20, 10],
['data3', 150, 120, 110],
['data4', 12, 24, 20]
],
type: 'bar',
groups: [['data1', 'data4']]
},
bar: {
space: spacing
}
}
}
var getBBox = function(selector) {
return d3
.select(selector)
.node()
.getBBox()
}
var getBarContainerWidth = function() {
return parseInt(getBBox('.c3-chart-bars').width)
}
var getBarContainerOffset = function() {
return parseInt(getBBox('.c3-chart-bars').x)
}
var getBarBBox = function(name, idx) {
return getBBox('.c3-target-' + name + ' .c3-bar-' + (idx || 0))
}
var getBarWidth = function(name, idx) {
return parseInt(getBarBBox(name, idx).width)
}
var getBarOffset = function(name1, name2, idx) {
var bbox1 = getBarBBox(name1, idx)
var bbox2 = getBarBBox(name2, idx)
return Math.floor(bbox2.x - (bbox1.x + bbox1.width))
}
it('should set bar spacing to 0', function() {
args = createArgs(0)
expect(true).toBeTruthy()
})
it('should display the bars without any spacing', function() {
// all bars should have the same width
expect(getBarWidth('data1', 0)).toEqual(30)
expect(getBarWidth('data2', 0)).toEqual(30)
expect(getBarWidth('data3', 0)).toEqual(30)
expect(getBarWidth('data1', 1)).toEqual(30)
expect(getBarWidth('data2', 1)).toEqual(30)
expect(getBarWidth('data3', 1)).toEqual(30)
expect(getBarWidth('data1', 2)).toEqual(30)
expect(getBarWidth('data2', 2)).toEqual(30)
expect(getBarWidth('data3', 2)).toEqual(30)
// all offsets should be the same
expect(getBarOffset('data1', 'data2', 0)).toEqual(0)
expect(getBarOffset('data2', 'data3', 0)).toEqual(0)
expect(getBarOffset('data1', 'data2', 1)).toEqual(0)
expect(getBarOffset('data2', 'data3', 1)).toEqual(0)
expect(getBarOffset('data1', 'data2', 2)).toEqual(0)
expect(getBarOffset('data2', 'data3', 2)).toEqual(0)
// default width/offset of the container for this chart
expect(getBarContainerWidth()).toEqual(396)
expect(getBarContainerOffset()).toEqual(31)
})
it('should set bar spacing to 0.25', function() {
args = createArgs(0.25)
expect(true).toBeTruthy()
})
it('should display the bars with a spacing ratio of 0.25', function() {
// with bar_space of 0.25, the space between bars is
// expected to be 25% of the original bar's width
// which is ~7
// expect all bars to be the same width
expect(getBarWidth('data1', 0)).toEqual(22)
expect(getBarWidth('data2', 0)).toEqual(22)
expect(getBarWidth('data3', 0)).toEqual(22)
expect(getBarWidth('data1', 1)).toEqual(22)
expect(getBarWidth('data2', 1)).toEqual(22)
expect(getBarWidth('data3', 1)).toEqual(22)
expect(getBarWidth('data1', 2)).toEqual(22)
expect(getBarWidth('data2', 2)).toEqual(22)
expect(getBarWidth('data3', 2)).toEqual(22)
// all offsets should be the same
expect(getBarOffset('data1', 'data2', 0)).toEqual(7)
expect(getBarOffset('data2', 'data3', 0)).toEqual(7)
expect(getBarOffset('data1', 'data2', 1)).toEqual(7)
expect(getBarOffset('data2', 'data3', 1)).toEqual(7)
expect(getBarOffset('data1', 'data2', 2)).toEqual(7)
expect(getBarOffset('data2', 'data3', 2)).toEqual(7)
// expect the container to shrink a little because of
// the offsets from the first/last chart
// we add/subtract 1 because of approximation due to rounded values
expect(getBarContainerWidth()).toEqual(396 - 7 - 1)
expect(getBarContainerOffset()).toEqual(31 + (Math.floor(7 / 2) + 1))
})
it('should set bar spacing to 0.5', function() {
args = createArgs(0.5)
expect(true).toBeTruthy()
})
it('should display the bars with a spacing ratio of 0.5', function() {
// with bar_space of 0.5, the space between bars is
// expected to be 50% of the original bar's width
// which is ~15
// expect all bars to be the same width
expect(getBarWidth('data1', 0)).toEqual(15)
expect(getBarWidth('data2', 0)).toEqual(15)
expect(getBarWidth('data3', 0)).toEqual(15)
expect(getBarWidth('data1', 1)).toEqual(15)
expect(getBarWidth('data2', 1)).toEqual(15)
expect(getBarWidth('data3', 1)).toEqual(15)
expect(getBarWidth('data1', 2)).toEqual(15)
expect(getBarWidth('data2', 2)).toEqual(15)
expect(getBarWidth('data3', 2)).toEqual(15)
// all offsets should be the same
expect(getBarOffset('data1', 'data2', 0)).toEqual(15)
expect(getBarOffset('data2', 'data3', 0)).toEqual(15)
expect(getBarOffset('data1', 'data2', 1)).toEqual(15)
expect(getBarOffset('data2', 'data3', 1)).toEqual(15)
expect(getBarOffset('data1', 'data2', 2)).toEqual(15)
expect(getBarOffset('data2', 'data3', 2)).toEqual(15)
// expect the container to shrink a little because of
// the offsets from the first/last chart
expect(getBarContainerWidth()).toEqual(396 - 15)
expect(getBarContainerOffset()).toEqual(31 + Math.floor(15 / 2))
})
})
}) | the_stack |
// Some lines of code are from Elyra Code Snippet.
/*
* Copyright 2018-2020 IBM Corporation
* 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 a* limitations under the License.
*/
import { ReactWidget, UseSignal } from '@jupyterlab/apputils';
import { JupyterFrontEnd } from '@jupyterlab/application';
import { IEditorServices } from '@jupyterlab/codeeditor';
import { Widget } from '@lumino/widgets';
import { Message } from '@lumino/messaging';
import { Signal } from '@lumino/signaling';
import { IDragEvent } from '@lumino/dragdrop';
import { MimeData } from '@lumino/coreutils';
import { CodeSnippetService, ICodeSnippet } from './CodeSnippetService';
import { CodeSnippetDisplay } from './CodeSnippetDisplay';
import { CodeSnippetInputDialog } from './CodeSnippetInputDialog';
import React from 'react';
import { Notebook } from '@jupyterlab/notebook';
/**
* A class used to indicate a snippet item.
*/
const CODE_SNIPPET_ITEM = 'jp-codeSnippet-item';
/**
* The mimetype used for Jupyter cell data.
*/
const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells';
/**
* A class used to indicate a drop target.
*/
const DROP_TARGET_CLASS = 'jp-codeSnippet-dropTarget';
const CODE_SNIPPET_EDITOR = 'jp-codeSnippet-editor';
const CODE_SNIPPET_DRAG_HOVER = 'jp-codeSnippet-drag-hover';
const commands = {
OPEN_CODE_SNIPPET_EDITOR: `${CODE_SNIPPET_EDITOR}:open`,
};
/**
* A widget for Code Snippets.
*/
export class CodeSnippetWidget extends ReactWidget {
getCurrentWidget: () => Widget;
// private _codeSnippetWidgetModel: CodeSnippetWidgetModel;
renderCodeSnippetsSignal: Signal<this, ICodeSnippet[]>;
app: JupyterFrontEnd;
codeSnippetManager: CodeSnippetService;
private editorServices: IEditorServices;
constructor(
getCurrentWidget: () => Widget,
app: JupyterFrontEnd,
editorServices: IEditorServices
) {
super();
this.app = app;
this.editorServices = editorServices;
this.getCurrentWidget = getCurrentWidget;
this.renderCodeSnippetsSignal = new Signal<this, ICodeSnippet[]>(this);
this.codeSnippetManager = CodeSnippetService.getCodeSnippetService();
this.moveCodeSnippet = this.moveCodeSnippet.bind(this);
this.openCodeSnippetEditor = this.openCodeSnippetEditor.bind(this);
this.updateCodeSnippetWidget = this.updateCodeSnippetWidget.bind(this);
this.node.setAttribute('data-lm-dragscroll', 'true');
}
updateCodeSnippetWidget(): void {
const newSnippets = this.codeSnippetManager.snippets;
this.renderCodeSnippetsSignal.emit(newSnippets);
}
onAfterShow(msg: Message): void {
this.updateCodeSnippetWidget();
}
openCodeSnippetEditor(args: any): void {
this.app.commands.execute(commands.OPEN_CODE_SNIPPET_EDITOR, args);
}
/**
* Handle the DOM events for the widget.
*
* @param event - The DOM event sent to the widget.
*
* #### Notes
* This method implements the DOM `EventListener` interface and is
* called in response to events on the notebook panel's node. It should
* not be called directly by user code.
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'lm-dragenter':
this._evtDragEnter(event as IDragEvent);
break;
case 'lm-dragleave':
this._evtDragLeave(event as IDragEvent);
break;
case 'lm-dragover':
this._evtDragOver(event as IDragEvent);
break;
case 'lm-drop':
this._evtDrop(event as IDragEvent);
break;
default:
break;
}
}
/**
* A message handler invoked on an `'after-attach'` message.
* @param msg
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
const node = this.node;
node.addEventListener('lm-dragenter', this);
node.addEventListener('lm-dragleave', this);
node.addEventListener('lm-dragover', this);
node.addEventListener('lm-drop', this);
}
/**
* Handle `before-detach` messages for the widget.
* @param msg
*/
protected onBeforeDetach(msg: Message): void {
const node = this.node;
node.removeEventListener('lm-dragenter', this);
node.removeEventListener('lm-dragleave', this);
node.removeEventListener('lm-dragover', this);
node.removeEventListener('lm-drop', this);
}
/**
* Find the snippet containing the target html element.
*
* #### Notes
* Returns undefined if the cell is not found.
*/
private _findSnippet(node: HTMLElement): HTMLElement {
// Trace up the DOM hierarchy to find the root cell node.
// Then find the corresponding child and select it.
let n: HTMLElement | null = node;
while (n && n !== this.node) {
if (n.classList.contains(CODE_SNIPPET_ITEM)) {
return n;
}
n = n.parentElement;
}
return undefined;
}
/**
* Handle the `'lm-dragenter'` event for the widget.
*/
private _evtDragEnter(event: IDragEvent): void {
if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
return;
}
event.preventDefault();
event.stopPropagation();
const target = event.target as HTMLElement;
if (!event.mimeData.hasData('snippet/id')) {
const snippetId = target.id.slice(CODE_SNIPPET_DRAG_HOVER.length);
event.mimeData.setData('snippet/id', parseInt(snippetId));
}
const snippet = this._findSnippet(target);
if (snippet === undefined) {
return;
}
const snippetNode = snippet as HTMLElement;
snippetNode.classList.add(DROP_TARGET_CLASS);
}
/**
* Handle the `'lm-dragleave'` event for the widget.
*/
private _evtDragLeave(event: IDragEvent): void {
if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) {
return;
}
event.preventDefault();
event.stopPropagation();
const elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
if (elements.length) {
(elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS);
}
}
/**
* Handle the `'lm-dragover'` event for the widget.
*/
private _evtDragOver(event: IDragEvent): void {
const data = this.findCellData(event.mimeData);
if (data === undefined) {
return;
}
event.preventDefault();
event.stopPropagation();
event.dropAction = event.proposedAction;
const elements = this.node.getElementsByClassName(DROP_TARGET_CLASS);
if (elements.length) {
(elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS);
}
const target = event.target as HTMLElement;
const snippet = this._findSnippet(target);
if (snippet === undefined) {
return;
}
const snippetNode = snippet as HTMLElement;
snippetNode.classList.add(DROP_TARGET_CLASS);
}
private findCellData(mime: MimeData): string[] {
const code = mime.getData('text/plain');
return code.split('\n');
}
/**
* Handle the `'lm-drop'` event for the widget.
*/
private async _evtDrop(event: IDragEvent): Promise<void> {
const data = this.findCellData(event.mimeData);
if (data === undefined) {
return;
}
event.preventDefault();
event.stopPropagation();
if (event.proposedAction === 'none') {
event.dropAction = 'none';
return;
}
let target = event.target as HTMLElement;
while (target && target.parentElement) {
if (target.classList.contains(DROP_TARGET_CLASS)) {
target.classList.remove(DROP_TARGET_CLASS);
break;
}
target = target.parentElement;
}
const snippet = this._findSnippet(target);
// if target is CodeSnippetWidget, then snippet is undefined
let idx;
if (snippet !== undefined) {
idx = parseInt(snippet.id.slice(CODE_SNIPPET_ITEM.length));
} else {
idx = this.codeSnippetManager.snippets.length;
}
/**
* moving snippets inside the snippet panel
*/
const source = event.source;
if (source instanceof CodeSnippetDisplay) {
event.dropAction = 'move';
if (event.mimeData.hasData('snippet/id')) {
const srcIdx = event.mimeData.getData('snippet/id') as number;
this.moveCodeSnippet(srcIdx, idx);
}
} else {
const notebook: Notebook =
event.mimeData.getData('internal:cells')[0].parent;
const language = notebook.model.defaultKernelLanguage;
// Handle the case where we are copying cells
event.dropAction = 'copy';
CodeSnippetInputDialog(this, data, language, idx);
}
// Reorder snippet just to make sure id's are in order.
this.codeSnippetManager.orderSnippets().then((res: boolean) => {
if (!res) {
console.log('Error in ordering snippets');
return;
}
});
}
// move code snippet within code snippet explorer
private moveCodeSnippet(srcIdx: number, targetIdx: number): void {
this.codeSnippetManager
.moveSnippet(srcIdx, targetIdx)
.then((res: boolean) => {
if (!res) {
console.log('Error in moving snippet');
return;
}
});
const newSnippets = this.codeSnippetManager.snippets;
this.renderCodeSnippetsSignal.emit(newSnippets);
}
render(): React.ReactElement {
return (
<UseSignal signal={this.renderCodeSnippetsSignal} initialArgs={[]}>
{(_, codeSnippets): React.ReactElement => (
<div>
<CodeSnippetDisplay
codeSnippets={codeSnippets}
codeSnippetManager={this.codeSnippetManager}
app={this.app}
getCurrentWidget={this.getCurrentWidget}
openCodeSnippetEditor={this.openCodeSnippetEditor}
editorServices={this.editorServices}
updateCodeSnippetWidget={this.updateCodeSnippetWidget}
/>
</div>
)}
</UseSignal>
);
}
} | the_stack |
import { IDocumentStore } from "../../src/Documents/IDocumentStore";
import { disposeTestDocumentStore, testContext } from "../Utils/TestUtil";
import { Company } from "../Assets/Entities";
import { assertThat, assertThrows } from "../Utils/AssertExtensions";
import { RevisionsConfiguration } from "../../src/Documents/Operations/RevisionsConfiguration";
import { RevisionsCollectionConfiguration } from "../../src/Documents/Operations/RevisionsCollectionConfiguration";
import { ConfigureRevisionsOperation } from "../../src/Documents/Operations/Revisions/ConfigureRevisionsOperation";
describe("ForceRevisionCreation", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("forceRevisionCreationForSingleUnTrackedEntityByID", async () => {
let companyId: string;
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
companyId = company.id;
await session.saveChanges();
}
{
const session = store.openSession();
session.advanced.revisions.forceRevisionCreationFor(companyId);
await session.saveChanges();
const revisionsCount = (await session.advanced.revisions.getFor(companyId, { documentType: Company })).length;
assertThat(revisionsCount)
.isEqualTo(1);
}
});
it("forceRevisionCreationForMultipleUnTrackedEntitiesByID", async () => {
let companyId1: string;
let companyId2: string;
{
const session = store.openSession();
const company1 = Object.assign(new Company(), {
name: "HR1"
});
const company2 = Object.assign(new Company(), {
name: "HR2"
});
await session.store(company1);
await session.store(company2);
companyId1 = company1.id;
companyId2 = company2.id;
await session.saveChanges();
}
{
const session = store.openSession();
session.advanced.revisions.forceRevisionCreationFor(companyId1);
session.advanced.revisions.forceRevisionCreationFor(companyId2);
await session.saveChanges();
const revisionsCount1 = (await session.advanced.revisions.getFor<Company>(companyId1)).length;
const revisionsCount2 = (await session.advanced.revisions.getFor<Company>(companyId2)).length;
assertThat(revisionsCount1)
.isEqualTo(1);
assertThat(revisionsCount2)
.isEqualTo(1);
}
});
it("cannotForceRevisionCreationForUnTrackedEntityByEntity", async () => {
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await assertThrows(() => {
session.advanced.revisions.forceRevisionCreationFor(company)
}, err => {
assertThat(err.name)
.isEqualTo("InvalidOperationException");
assertThat(err.message)
.contains("Cannot create a revision for the requested entity because it is Not tracked by the session");
});
}
});
it("forceRevisionCreationForNewDocumentByEntity", async () => {
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
session.advanced.revisions.forceRevisionCreationFor(company);
let revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
await session.saveChanges();
revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isEqualTo(1);
}
});
it("cannotForceRevisionCreationForNewDocumentBeforeSavingToServerByEntity", async () => {
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
session.advanced.revisions.forceRevisionCreationFor(company);
await assertThrows(() => session.saveChanges(), err => {
assertThat(err.name)
.isEqualTo("RavenException");
assertThat(err.message)
.contains("Can't force revision creation - the document was not saved on the server yet");
});
const revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
}
});
it("forceRevisionCreationForTrackedEntityWithNoChangesByEntity", async () => {
let companyId = "";
{
const session = store.openSession();
// 1. store document
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
companyId = company.id;
const revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
}
{
const session = store.openSession();
// 2. Load & Save without making changes to the document
const company = await session.load<Company>(companyId, Company);
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
const revisionsCount = (await session.advanced.revisions.getFor<Company>(companyId)).length;
assertThat(revisionsCount)
.isEqualTo(1);
}
});
it("forceRevisionCreationForTrackedEntityWithChangesByEntity", async () => {
let companyId = "";
// 1. store document
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
companyId = company.id;
const revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
}
// 2. Load, Make changes & Save
{
const session = store.openSession();
const company = await session.load<Company>(companyId, Company);
company.name = "HR V2";
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(company.id);
const revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
// Assert revision contains the value 'Before' the changes...
// ('Before' is the default force revision creation strategy)
assertThat(revisions[0].name)
.isEqualTo("HR");
}
});
it("forceRevisionCreationForTrackedEntityWithChangesByID", async () => {
let companyId = "";
// 1. Store document
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
companyId = company.id;
const revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
}
{
const session = store.openSession();
// 2. Load, Make changes & Save
const company = await session.load<Company>(companyId, Company);
company.name = "HR V2";
session.advanced.revisions.forceRevisionCreationFor(company.id);
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(company.id);
const revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
// Assert revision contains the value 'Before' the changes...
assertThat(revisions[0].name)
.isEqualTo("HR");
}
});
it("forceRevisionCreationMultipleRequests", async () => {
let companyId = "";
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
companyId = company.id;
const revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
}
{
const session = store.openSession();
session.advanced.revisions.forceRevisionCreationFor(companyId);
const company = await session.load<Company>(companyId, Company);
company.name = "HR V2";
session.advanced.revisions.forceRevisionCreationFor(company);
// The above request should not throw - we ignore duplicate requests with SAME strategy
await assertThrows(() => session.advanced.revisions.forceRevisionCreationFor(company.id, "None"), err => {
assertThat(err.name)
.isEqualTo("InvalidOperationException");
assertThat(err.message)
.contains("A request for creating a revision was already made for document");
});
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(company.id);
const revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
assertThat(revisions[0].name)
.isEqualTo("HR");
}
});
it("forceRevisionCreationAcrossMultipleSessions", async () => {
let companyId = "";
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
await session.saveChanges();
companyId = company.id;
let revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isZero();
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isEqualTo(1);
// Verify that another 'force' request will not create another revision
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isEqualTo(1);
}
{
const session = store.openSession();
const company = await session.load<Company>(companyId, Company);
company.name = "HR V2";
await session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
let revisions = await session.advanced.revisions.getFor<Company>(company.id);
let revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
// Assert revision contains the value 'Before' the changes...
assertThat(revisions[0].name)
.isEqualTo("HR");
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
revisions = await session.advanced.revisions.getFor<Company>(company.id);
revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(2);
// Assert revision contains the value 'Before' the changes...
assertThat(revisions[0].name)
.isEqualTo("HR V2");
}
{
const session = store.openSession();
const company = await session.load<Company>(companyId, Company);
company.name = "HR V3";
await session.saveChanges();
}
{
const session = store.openSession();
session.advanced.revisions.forceRevisionCreationFor(companyId);
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(companyId);
const revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(3);
assertThat(revisions[0].name)
.isEqualTo("HR V3");
}
});
it("forceRevisionCreationWhenRevisionConfigurationIsSet", async () => {
// Define revisions settings
const configuration = new RevisionsConfiguration();
const companiesConfiguration = Object.assign(new RevisionsCollectionConfiguration(), {
purgeOnDelete: true,
minimumRevisionsToKeep: 5
} as Partial<RevisionsCollectionConfiguration>);
configuration.collections = new Map<string, RevisionsCollectionConfiguration>();
configuration.collections.set("Companies", companiesConfiguration);
const result = await store.maintenance.send(new ConfigureRevisionsOperation(configuration));
let companyId = "";
{
const session = store.openSession();
const company = Object.assign(new Company(), {
name: "HR"
});
await session.store(company);
companyId = company.id;
await session.saveChanges();
let revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isEqualTo(1); // one revision because configuration is set
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
revisionsCount = (await session.advanced.revisions.getFor<Company>(company.id)).length;
assertThat(revisionsCount)
.isEqualTo(1); // no new revision created - already exists due to configuration settings
session.advanced.revisions.forceRevisionCreationFor(company);
await session.saveChanges();
company.name = "HR V2";
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(companyId);
revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(2);
assertThat(revisions[0].name)
.isEqualTo("HR V2");
}
{
const session = store.openSession();
session.advanced.revisions.forceRevisionCreationFor(companyId);
await session.saveChanges();
const revisions = await session.advanced.revisions.getFor<Company>(companyId);
const revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(2);
assertThat(revisions[0].name)
.isEqualTo("HR V2");
}
});
it("hasRevisionsFlagIsCreatedWhenForcingRevisionForDocumentThatHasNoRevisionsYet", async () => {
let company1Id = "";
let company2Id = "";
{
const session = store.openSession();
const company1 = Object.assign(new Company(), {
name: "HR1"
});
const company2 = Object.assign(new Company(), {
name: "HR2"
});
await session.store(company1);
await session.store(company2);
await session.saveChanges();
company1Id = company1.id;
company2Id = company2.id;
let revisionsCount = (await session.advanced.revisions.getFor<Company>(company1.id)).length;
assertThat(revisionsCount)
.isZero();
revisionsCount = (await session.advanced.revisions.getFor<Company>(company2.id)).length;
assertThat(revisionsCount)
.isZero();
}
{
const session = store.openSession();
// Force revision with no changes on document
session.advanced.revisions.forceRevisionCreationFor(company1Id);
// Force revision with changes on document
session.advanced.revisions.forceRevisionCreationFor(company2Id);
const company2 = await session.load<Company>(company2Id, Company);
company2.name = "HR2 New Name";
await session.saveChanges();
}
{
const session = store.openSession();
let revisions = await session.advanced.revisions.getFor<Company>(company1Id);
let revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
assertThat(revisions[0].name)
.isEqualTo("HR1");
revisions = await session.advanced.revisions.getFor<Company>(company2Id);
revisionsCount = revisions.length;
assertThat(revisionsCount)
.isEqualTo(1);
assertThat(revisions[0].name)
.isEqualTo("HR2");
// Assert that HasRevisions flag was created on both documents
let company = await session.load<Company>(company1Id, Company);
let metadata = session.advanced.getMetadataFor(company);
assertThat(metadata["@flags"])
.isEqualTo("HasRevisions");
company = await session.load<Company>(company2Id);
metadata = session.advanced.getMetadataFor(company);
assertThat(metadata["@flags"])
.isEqualTo("HasRevisions");
}
});
}); | the_stack |
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
* and run json-schema-to-typescript to regenerate this file.
*/
/**
* Any valid `callable` in PHP.
*/
export type Callable = any;
/**
* Timestamp in MySQL DATETIME format (`YYYY-MM-DD hh:mm:ss`).
*/
export type WP_Date_Time = string;
/**
* The name of an individual primitive capability or meta capability.
*/
export type WP_User_Cap_Name = string;
/**
* Timestamp in IETF RFC 3339 date-time format minus the timezone identifier (`YYYY-MM-DDThh:mm:ss`).
*/
export type WP_REST_API_Date_Time = string;
/**
* A collection of comment objects in a REST API context.
*/
export type WP_REST_API_Comments = WP_REST_API_Comment[];
/**
* A collection of post objects in a REST API context.
*/
export type WP_REST_API_Posts = WP_REST_API_Post[];
/**
* A collection of media attachment objects in a REST API context.
*/
export type WP_REST_API_Attachments = WP_REST_API_Attachment[];
/**
* A collection of reusable block objects in a REST API context.
*/
export type WP_REST_API_Blocks = WP_REST_API_Block[];
/**
* A collection of block directory search results in a REST API context.
*/
export type WP_REST_API_Block_Directory_Items = WP_REST_API_Block_Directory_Item[];
/**
* A collection of block type objects in a REST API context.
*/
export type WP_REST_API_Block_Types = WP_REST_API_Block_Type[];
/**
* A collection of revision objects in a REST API context.
*/
export type WP_REST_API_Revisions = WP_REST_API_Revision[];
/**
* A collection of term objects in a REST API context.
*/
export type WP_REST_API_Terms = WP_REST_API_Term[];
/**
* A post tag object in a REST API context.
*/
export type WP_REST_API_Tag = WP_REST_API_Term;
/**
* A collection of post tag objects in a REST API context.
*/
export type WP_REST_API_Tags = WP_REST_API_Tag[];
/**
* A post category object in a REST API context.
*/
export type WP_REST_API_Category = WP_REST_API_Term;
/**
* A collection of post category objects in a REST API context.
*/
export type WP_REST_API_Categories = WP_REST_API_Category[];
/**
* UTC timestamp in IETF RFC 3339 date-time format (`YYYY-MM-DDThh:mm:ss+00:00`).
*/
export type WP_REST_API_Date_Time_UTC = string;
/**
* A collection of user objects in a REST API context.
*/
export type WP_REST_API_Users = WP_REST_API_User[];
/**
* A collection of search result objects in a REST API context.
*/
export type WP_REST_API_Search_Results = WP_REST_API_Search_Result[];
/**
* A collection of user application passwords in a REST API context.
*/
export type WP_REST_API_Application_Passwords = WP_REST_API_Application_Password[];
/**
* WordPress is open source software you can use to create a beautiful website, blog, or app.
*/
export interface WP {
Block: WP_Block;
Comment: WP_Comment;
Error: WP_Error;
Error_With_Error: WP_Error_With_Error;
Error_Without_Error: WP_Error_Without_Error;
Locale: WP_Locale;
Network: WP_Network;
Post: WP_Post;
Post_Type: WP_Post_Type;
Query: WP_Query;
Role: WP_Role;
Site: WP_Site;
Taxonomy: WP_Taxonomy;
Term: WP_Term;
User: WP_User;
REST_API: {
Comment: WP_REST_API_Comment;
Comments: WP_REST_API_Comments;
Post: WP_REST_API_Post;
Posts: WP_REST_API_Posts;
Attachment: WP_REST_API_Attachment;
Attachments: WP_REST_API_Attachments;
Block: WP_REST_API_Block;
Blocks: WP_REST_API_Blocks;
Block_Directory_Item: WP_REST_API_Block_Directory_Item;
Block_Directory_Items: WP_REST_API_Block_Directory_Items;
Block_Type: WP_REST_API_Block_Type;
Block_Types: WP_REST_API_Block_Types;
Revision: WP_REST_API_Revision;
Rendered_Block: WP_REST_API_Rendered_Block;
Revisions: WP_REST_API_Revisions;
Status: WP_REST_API_Status;
Statuses: WP_REST_API_Statuses;
Term: WP_REST_API_Term;
Terms: WP_REST_API_Terms;
Tag: WP_REST_API_Tag;
Tags: WP_REST_API_Tags;
Category: WP_REST_API_Category;
Categories: WP_REST_API_Categories;
User: WP_REST_API_User;
Users: WP_REST_API_Users;
Search_Result: WP_REST_API_Search_Result;
Search_Results: WP_REST_API_Search_Results;
Settings: WP_REST_API_Settings;
Taxonomy: WP_REST_API_Taxonomy;
Taxonomies: WP_REST_API_Taxonomies;
Type: WP_REST_API_Type;
Types: WP_REST_API_Types;
Application_Password: WP_REST_API_Application_Password;
Application_Passwords: WP_REST_API_Application_Passwords;
Error: WP_REST_API_Error;
};
}
/**
* Class representing a parsed instance of a block.
*/
export interface WP_Block {
/**
* Original parsed array representation of block.
*/
parsed_block: WP_Block_Parsed;
/**
* Name of block.
*/
name: string;
/**
* Block type associated with the instance.
*/
block_type: WP_Block_Type;
/**
* Block context values.
*/
context: {
[k: string]: unknown;
};
/**
* List of inner blocks (of this same class).
*/
inner_blocks: unknown[];
/**
* Resultant HTML from inside block comment delimiters after removing inner blocks.
*/
inner_html: string;
/**
* List of string fragments and null markers where inner blocks were found.
*/
inner_content: (string | null)[];
}
/**
* Original parsed array representation of block.
*/
export interface WP_Block_Parsed {
/**
* Name of block.
*/
blockName: string;
attrs: {
[k: string]: any;
};
/**
* List of inner blocks (of this same class).
*/
innerBlocks: WP_Block_Parsed[];
/**
* Resultant HTML from inside block comment delimiters after removing inner blocks.
*/
innerHTML: string;
/**
* List of string fragments and null markers where inner blocks were found.
*/
innerContent: (string | null)[];
}
/**
* Core class representing a block type.
*/
export interface WP_Block_Type {
/**
* Block API version.
*/
api_version: number;
/**
* Block type key.
*/
name: string;
/**
* Human-readable block type label.
*/
title: string;
/**
* Block type category classification, used in search interfaces to arrange block types by category.
*/
category: string | null;
/**
* Setting parent lets a block require that it is only available when nested within the specified blocks.
*/
parent: string[] | null;
/**
* Block type icon.
*/
icon: string | null;
/**
* A detailed block type description.
*/
description: string;
/**
* Additional keywords to produce block type as result in search interfaces.
*/
keywords: string[];
/**
* The translation textdomain.
*/
textdomain: string | null;
/**
* Alternative block styles.
*/
styles: unknown[];
/**
* Block variations.
*/
variations?: unknown[];
/**
* Supported features.
*/
supports: {
[k: string]: unknown;
} | null;
/**
* Structured data for the block preview.
*/
example: unknown[] | null;
/**
* Block type render callback.
*/
render_callback: Callable | null;
/**
* Block type attributes property schemas.
*/
attributes:
| []
| {
[k: string]: unknown;
}
| null;
/**
* Context values inherited by blocks of this type.
*/
uses_context: string[];
/**
* Context provided by blocks of this type.
*/
provides_context: {
[k: string]: string;
} | null;
/**
* Block type editor script handle.
*/
editor_script: string | null;
/**
* Block type front end script handle.
*/
script: string | null;
/**
* Block type editor style handle.
*/
editor_style: string | null | false;
/**
* Block type front end style handle.
*/
style: string | null | false;
skip_inner_blocks?: boolean;
}
/**
* Core class used to organize comments as instantiated objects with defined members.
*/
export interface WP_Comment {
/**
* Comment ID.
*
* A numeric string, for compatibility reasons.
*/
comment_ID: string;
/**
* ID of the post the comment is associated with.
*
* A numeric string, for compatibility reasons.
*/
comment_post_ID: string;
/**
* Comment author name.
*/
comment_author: string;
/**
* Comment author email address.
*/
comment_author_email: string | "";
/**
* Comment author URL.
*/
comment_author_url: string | "";
/**
* Comment author IP address (IPv4 format).
*/
comment_author_IP: string | "";
/**
* Comment date in YYYY-MM-DD HH:MM:SS format.
*/
comment_date: WP_Date_Time;
/**
* Comment GMT date in YYYY-MM-DD HH::MM:SS format.
*/
comment_date_gmt: WP_Date_Time;
/**
* Comment content.
*/
comment_content: string;
/**
* Comment karma count.
*
* A numeric string, for compatibility reasons.
*/
comment_karma: string;
/**
* Comment approval status.
*/
comment_approved: "0" | "1" | "spam" | "trash";
/**
* Comment author HTTP user agent.
*/
comment_agent: string;
/**
* Comment type.
*/
comment_type: WP_Comment_Type_Name | string;
/**
* Parent comment ID.
*
* A numeric string, for compatibility reasons.
*/
comment_parent: string;
/**
* Comment author ID.
*
* A numeric string, for compatibility reasons.
*/
user_id: string;
}
/**
* WordPress Error class.
*
* Container for checking for WordPress errors and error messages. Many core WordPress functions pass this class in the event of an error.
*/
export interface WP_Error {
/**
* Stores the list of errors.
*/
errors: [] | WP_Error_Messages;
/**
* Stores the list of data for error codes.
*/
error_data: [] | WP_Error_Data;
}
/**
* The messages for the errors contained within the error object.
*
* Each error is represented by a property keyed by the error code, and containing an array of message strings for that code. Any given error code usually contains only one message, but can contain more.
*/
export interface WP_Error_Messages {
[k: string]: string[];
}
/**
* The data for the errors contained within the error object.
*
* Each error is represented by a property keyed by the error code, and containing error data for that code. Any given error code can contain only one piece of error data, but the data can be of any type.
*/
export interface WP_Error_Data {
[k: string]: any;
}
/**
* WordPress Error class.
*
* Represents a WP_Error object that contains at least one error.
*/
export interface WP_Error_With_Error {
/**
* Stores the list of errors.
*/
errors: WP_Error_Messages;
/**
* Stores the list of data for error codes.
*/
error_data: WP_Error_Data;
}
/**
* Empty WordPress Error class.
*
* Represents a WP_Error object that contains no errors.
*/
export interface WP_Error_Without_Error {
/**
* Stores the list of errors.
*/
errors: [];
/**
* Stores the list of data for error codes.
*/
error_data: [];
}
/**
* Core class used to store translated data for a locale.
*/
export interface WP_Locale {
/**
* Stores the translated strings for the full weekday names.
*/
weekday: string[];
/**
* Stores the translated strings for the one character weekday names.
*/
weekday_initial: {
[k: string]: string;
};
/**
* Stores the translated strings for the abbreviated weekday names.
*/
weekday_abbrev: {
[k: string]: string;
};
/**
* Stores the translated strings for the full month names.
*/
month: {
[k: string]: string;
};
/**
* Stores the translated strings for the month names in genitive case, if the locale specifies.
*/
month_genitive: {
[k: string]: string;
};
/**
* Stores the translated strings for the abbreviated month names.
*/
month_abbrev: {
[k: string]: string;
};
/**
* Stores the translated strings for 'am', 'pm', 'AM', and 'PM'.
*/
meridiem: {
am: string;
pm: string;
AM: string;
PM: string;
};
/**
* The text direction of the locale language.
*/
text_direction: "ltr" | "rtl";
/**
* The thousands separator and decimal point values used for localizing numbers.
*/
number_format: {
thousands_sep: string;
decimal_point: string;
};
}
/**
* Core class used for interacting with a multisite network.
*/
export interface WP_Network {
/**
* Domain of the network.
*/
domain: string;
/**
* Path of the network.
*/
path: string;
/**
* Domain used to set cookies for this network.
*/
cookie_domain: string;
/**
* Name of this network.
*
* Named "site" vs. "network" for legacy reasons.
*/
site_name: string;
}
/**
* Core class used to implement the WP_Post object.
*/
export interface WP_Post {
/**
* Post ID.
*/
ID: number;
/**
* ID of post author.
*
* A numeric string, for compatibility reasons.
*/
post_author: string;
/**
* The post's local publication time.
*/
post_date: WP_Date_Time;
/**
* The post's GMT publication time.
*/
post_date_gmt: WP_Date_Time;
/**
* The post's content.
*/
post_content: string;
/**
* The post's title.
*/
post_title: string;
/**
* The post's excerpt.
*/
post_excerpt: string;
/**
* The post's status.
*/
post_status: WP_Post_Status_Name | string;
/**
* Whether comments are allowed.
*/
comment_status: WP_Post_Comment_Status_Name;
/**
* Whether pings are allowed.
*/
ping_status: WP_Post_Comment_Status_Name;
/**
* The post's password in plain text.
*/
post_password: "" | string;
/**
* The post's slug.
*/
post_name: string;
/**
* URLs queued to be pinged.
*/
to_ping: "" | string;
/**
* URLs that have been pinged.
*/
pinged: "" | string;
/**
* The post's local modified time.
*/
post_modified: WP_Date_Time;
/**
* The post's GMT modified time.
*/
post_modified_gmt: WP_Date_Time;
/**
* A utility DB field for post content.
*/
post_content_filtered: string;
/**
* ID of a post's parent post.
*/
post_parent: number;
/**
* The unique identifier for a post, not necessarily a URL, used as the feed GUID.
*/
guid: string;
/**
* A field used for ordering posts.
*/
menu_order: number;
/**
* The post's type, like post or page.
*/
post_type: WP_Post_Type_Name | string;
/**
* An attachment's mime type.
*/
post_mime_type: string | "";
/**
* Cached comment count.
*
* A numeric string, for compatibility reasons.
*/
comment_count: string;
/**
* Stores the post object's sanitization level.
*/
filter: WP_Object_Filter_Context | null;
}
/**
* Core class used for interacting with post types.
*/
export interface WP_Post_Type {
/**
* Post type key.
*/
name: WP_Post_Type_Name | string;
/**
* Name of the post type shown in the menu. Usually plural.
*/
label: string;
/**
* Labels object for this post type.
*/
labels: WP_Post_Type_Labels;
/**
* A short descriptive summary of what the post type is.
*/
description: string;
/**
* Whether a post type is intended for use publicly either via the admin interface or by front-end users.
*/
public: boolean;
/**
* Whether the post type is hierarchical.
*/
hierarchical: boolean;
/**
* Whether to exclude posts with this post type from front end search results.
*/
exclude_from_search: boolean;
/**
* Whether queries can be performed on the front end for the post type as part of `parse_request()`.
*/
publicly_queryable: boolean;
/**
* Whether to generate and allow a UI for managing this post type in the admin.
*/
show_ui: boolean;
/**
* Where to show the post type in the admin menu.
*/
show_in_menu: boolean | string;
/**
* Makes this post type available for selection in navigation menus.
*/
show_in_nav_menus: boolean;
/**
* Makes this post type available via the admin bar.
*/
show_in_admin_bar: boolean;
/**
* The position in the menu order the post type should appear.
*/
menu_position: number | null;
/**
* The URL or reference to the icon to be used for this menu. Can include a URL, a base64-encoded SVG using a data URI, the name of a Dashicons helper class, or 'none'. Can include null for post types without a UI.
*/
menu_icon: string | "none" | null;
/**
* The string to use to build the read, edit, and delete capabilities.
*/
capability_type: string;
/**
* Whether to use the internal default meta capability handling.
*/
map_meta_cap: boolean;
/**
* Provide a callback function that sets up the meta boxes for the edit form.
*/
register_meta_box_cb: Callable | null;
/**
* An array of taxonomy identifiers that will be registered for the post type.
*/
taxonomies: (WP_Taxonomy_Name | string)[];
/**
* Whether there should be post type archives, or if a string, the archive slug to use.
*/
has_archive: boolean | string;
/**
* Sets the query_var key for this post type.
*/
query_var: string | boolean;
/**
* Whether to allow this post type to be exported.
*/
can_export: boolean;
/**
* Whether to delete posts of this type when deleting a user.
*/
delete_with_user: boolean | null;
/**
* Array of blocks to use as the default initial state for an editor session.
*/
template: unknown[];
/**
* Whether the block template should be locked if $template is set.
*/
template_lock: false | "all" | "insert";
/**
* Whether this post type is a native or 'built-in' post_type.
*/
_builtin: boolean;
/**
* URL segment to use for edit link of this post type.
*/
_edit_link: string;
/**
* Post type capabilities.
*/
cap: WP_Post_Type_Caps;
/**
* Triggers the handling of rewrites for this post type.
*/
rewrite: WP_Post_Type_Rewrite | boolean;
/**
* The features supported by the post type.
*/
supports?: {
[k: string]: unknown;
};
/**
* Whether this post type should appear in the REST API.
*/
show_in_rest: boolean;
/**
* The base path for this post type's REST API endpoints.
*/
rest_base: string | boolean;
/**
* The controller for this post type's REST API endpoints.
*/
rest_controller_class: string | false;
/**
* The controller instance for this post type's REST API endpoints.
*/
rest_controller: {
[k: string]: unknown;
};
}
/**
* Post type labels.
*/
export interface WP_Post_Type_Labels {
name: string;
singular_name: string;
add_new: string;
add_new_item: string;
edit_item: string;
new_item: string;
view_item: string;
view_items: string;
search_items: string;
not_found: string;
not_found_in_trash: string;
parent_item_colon: string | null;
all_items: string;
archives: string;
attributes: string;
insert_into_item: string;
uploaded_to_this_item: string;
featured_image: string;
set_featured_image: string;
remove_featured_image: string;
use_featured_image: string;
filter_items_list: string;
filter_by_date: string;
items_list_navigation: string;
items_list: string;
item_published: string;
item_published_privately: string;
item_reverted_to_draft: string;
item_scheduled: string;
item_updated: string;
item_link: string;
item_link_description: string;
menu_name: string;
name_admin_bar: string;
}
/**
* Post type capabilities.
*/
export interface WP_Post_Type_Caps {
edit_post: WP_User_Cap_Name;
read_post: WP_User_Cap_Name;
delete_post: WP_User_Cap_Name;
edit_posts: WP_User_Cap_Name;
edit_others_posts: WP_User_Cap_Name;
delete_posts: WP_User_Cap_Name;
publish_posts: WP_User_Cap_Name;
read_private_posts: WP_User_Cap_Name;
read?: WP_User_Cap_Name;
delete_private_posts?: WP_User_Cap_Name;
delete_published_posts?: WP_User_Cap_Name;
delete_others_posts?: WP_User_Cap_Name;
edit_private_posts?: WP_User_Cap_Name;
edit_published_posts?: WP_User_Cap_Name;
create_posts: WP_User_Cap_Name;
}
/**
* Post type rewrite rule definition.
*/
export interface WP_Post_Type_Rewrite {
/**
* Customize the permastruct slug.
*/
slug: string;
/**
* Whether the permastruct should be prepended with WP_Rewrite::$front.
*/
with_front: boolean;
/**
* Whether the feed permastruct should be built for this post type.
*/
feeds: boolean;
/**
* Whether the permastruct should provide for pagination.
*/
pages: boolean;
/**
* Endpoint mask to assign.
*/
ep_mask: number;
[k: string]: unknown;
}
/**
* The WordPress Query class.
*/
export interface WP_Query {
/**
* Query vars set by the user.
*/
query: {
[k: string]: unknown;
} | null;
/**
* Query vars, after parsing.
*/
query_vars:
| {
[k: string]: unknown;
}
| [];
/**
* Taxonomy query, as passed to get_tax_sql().
*/
tax_query: {
[k: string]: unknown;
} | null;
/**
* Metadata query container.
*/
meta_query:
| {
[k: string]: unknown;
}
| false;
/**
* Date query container.
*/
date_query:
| {
[k: string]: unknown;
}
| false;
/**
* Holds the data for a single object that is queried. Holds the contents of a post, page, category, attachment.
*/
queried_object?: WP_Post | WP_Post_Type | WP_Term | WP_User | null;
/**
* The ID of the queried object.
*/
queried_object_id?: number | null;
/**
* SQL for the database query.
*/
request: string | null;
/**
* Array of post objects or post IDs.
*/
posts: WP_Post[] | number[] | [] | null;
/**
* The number of posts for the current query.
*/
post_count: number;
/**
* Index of the current item in the loop.
*/
current_post: number;
/**
* Whether the loop has started and the caller is in the loop.
*/
in_the_loop: boolean;
/**
* The current post.
*/
post?: WP_Post | null;
/**
* The list of comments for current post.
*/
comments?: WP_Comment[] | [] | null;
/**
* The number of comments for the posts.
*/
comment_count?: number;
/**
* The index of the comment in the comment loop.
*/
current_comment: number;
/**
* Current comment object.
*/
comment?: WP_Comment | null;
/**
* The number of found posts for the current query. If limit clause was not used, equals $post_count.
*/
found_posts: number;
/**
* The number of pages.
*/
max_num_pages: number;
/**
* The number of comment pages.
*/
max_num_comment_pages: number;
/**
* Signifies whether the current query is for a single post.
*/
is_single: boolean;
/**
* Signifies whether the current query is for a preview.
*/
is_preview: boolean;
/**
* Signifies whether the current query is for a page.
*/
is_page: boolean;
/**
* Signifies whether the current query is for an archive.
*/
is_archive: boolean;
/**
* Signifies whether the current query is for a date archive.
*/
is_date: boolean;
/**
* Signifies whether the current query is for a year archive.
*/
is_year: boolean;
/**
* Signifies whether the current query is for a month archive.
*/
is_month: boolean;
/**
* Signifies whether the current query is for a day archive.
*/
is_day: boolean;
/**
* Signifies whether the current query is for a specific time.
*/
is_time: boolean;
/**
* Signifies whether the current query is for an author archive.
*/
is_author: boolean;
/**
* Signifies whether the current query is for a category archive.
*/
is_category: boolean;
/**
* Signifies whether the current query is for a tag archive.
*/
is_tag: boolean;
/**
* Signifies whether the current query is for a taxonomy archive.
*/
is_tax: boolean;
/**
* Signifies whether the current query is for a search.
*/
is_search: boolean;
/**
* Signifies whether the current query is for a feed.
*/
is_feed: boolean;
/**
* Signifies whether the current query is for a comment feed.
*/
is_comment_feed: boolean;
/**
* Signifies whether the current query is for trackback endpoint call.
*/
is_trackback: boolean;
/**
* Signifies whether the current query is for the site homepage.
*/
is_home: boolean;
/**
* Signifies whether the current query is for the Privacy Policy page.
*/
is_privacy_policy: boolean;
/**
* Signifies whether the current query couldn't find anything.
*/
is_404: boolean;
/**
* Signifies whether the current query is for an embed.
*/
is_embed: boolean;
/**
* Signifies whether the current query is for a paged result and not for the first page.
*/
is_paged: boolean;
/**
* Signifies whether the current query is for an administrative interface page.
*/
is_admin: boolean;
/**
* Signifies whether the current query is for an attachment page.
*/
is_attachment: boolean;
/**
* Signifies whether the current query is for an existing single post of any post type (post, attachment, page, custom post types).
*/
is_singular: boolean;
/**
* Signifies whether the current query is for the robots.txt file.
*/
is_robots: boolean;
/**
* Signifies whether the current query is for the favicon.ico file.
*/
is_favicon: boolean;
/**
* Signifies whether the current query is for the page_for_posts page. Basically, the homepage if the option isn't set for the static homepage.
*/
is_posts_page: boolean;
/**
* Signifies whether the current query is for a post type archive.
*/
is_post_type_archive: boolean;
/**
* Set if post thumbnails are cached
*/
thumbnails_cached: boolean;
}
/**
* Core class used to implement the WP_Term object.
*/
export interface WP_Term {
/**
* Term ID.
*/
term_id: number;
/**
* The term's name.
*/
name: string;
/**
* The term's slug.
*/
slug: string;
/**
* The term's term_group.
*/
term_group: number;
/**
* Term Taxonomy ID.
*/
term_taxonomy_id: number;
/**
* The term's taxonomy name.
*/
taxonomy: WP_Taxonomy_Name | string;
/**
* The term's description.
*/
description: string;
/**
* ID of a term's parent term.
*/
parent: number;
/**
* Cached object count for this term.
*/
count: number;
/**
* Term ID. Only present if the term object has passed through `_make_cat_compat()`.
*/
cat_ID?: number;
/**
* Cached object count for this term. Only present if the term object has passed through `_make_cat_compat()`.
*/
category_count?: number;
/**
* The term's description. Only present if the term object has passed through `_make_cat_compat()`.
*/
category_description?: string;
/**
* The term's name. Only present if the term object has passed through `_make_cat_compat()`.
*/
cat_name?: string;
/**
* The term's slug. Only present if the term object has passed through `_make_cat_compat()`.
*/
category_nicename?: string;
/**
* ID of a term's parent term. Only present if the term object has passed through `_make_cat_compat()`.
*/
category_parent?: number;
/**
* Stores the term object's sanitization level.
*/
filter: WP_Object_Filter_Context | null;
}
/**
* Core class used to implement the WP_User object.
*/
export interface WP_User {
/**
* The user's ID.
*/
ID: number;
/**
* All capabilities the user has, including individual and role based.
*/
allcaps: WP_User_Caps;
/**
* User metadata option name.
*/
cap_key: string;
/**
* The individual capabilities the user has been given.
*
* See the allcaps property for a complete list of caps that the user has.
*/
caps: WP_User_Caps;
/**
* User data container.
*/
data: WP_User_Data;
/**
* The filter context applied to user data fields.
*/
filter: WP_Object_Filter_Context | null;
/**
* The roles the user is part of.
*/
roles: (WP_User_Role_Name | string)[];
}
/**
* A dictionary of user capabilities.
*
* Property names represent a capability name and boolean values represent whether the user has that capability.
*/
export interface WP_User_Caps {
[k: string]: boolean;
}
/**
* User data container.
*/
export interface WP_User_Data {
/**
* The user's ID.
*
* A numeric string, for compatibility reasons.
*/
ID?: string;
/**
* The user's deletion status. Only used on Multisite.
*/
deleted?: "0" | "1";
/**
* The user's full display name.
*/
display_name?: string;
/**
* The user's spam status. Only used on Multisite.
*/
spam?: "0" | "1";
/**
* The user's activation key. Be careful not to expose this in your application.
*/
user_activation_key?: string;
/**
* The user's email address.
*/
user_email?: string | "";
/**
* The user's login name.
*/
user_login?: string;
/**
* The user's name as used in their author archive URL slug.
*/
user_nicename?: string;
/**
* The one-way hash of the user's password.
*/
user_pass?: string;
/**
* The user's registration date.
*/
user_registered?: WP_Date_Time;
/**
* The user's status. This field does not appear to be used by WordPress core.
*/
user_status?: "0";
/**
* The user's URL.
*/
user_url?: string | "";
}
/**
* Core class used to extend the user roles API.
*/
export interface WP_Role {
/**
* Role name.
*/
name: WP_User_Role_Name | string;
/**
* List of capabilities the role contains.
*/
capabilities: WP_User_Caps;
}
/**
* Core class used for interacting with a multisite site.
*/
export interface WP_Site {
/**
* Site ID.
*
* A numeric string, for compatibility reasons.
*/
blog_id: string;
/**
* Domain of the site.
*/
domain: string;
/**
* Path of the site.
*/
path: string;
/**
* The ID of the site's parent network.
*
* Named "site" vs. "network" for legacy reasons. An individual site's "site" is its network.
*
* A numeric string, for compatibility reasons.
*/
site_id: string;
/**
* The date on which the site was created or registered.
*/
registered: WP_Date_Time;
/**
* The date and time on which site settings were last updated.
*/
last_updated: WP_Date_Time;
/**
* Whether the site should be treated as public.
*
* A numeric string, for compatibility reasons.
*/
public: "0" | "1";
/**
* Whether the site should be treated as archived.
*
* A numeric string, for compatibility reasons.
*/
archived: "0" | "1";
/**
* Whether the site should be treated as mature.
*
* A numeric string, for compatibility reasons.
*/
mature: "0" | "1";
/**
* Whether the site should be treated as spam.
*
* A numeric string, for compatibility reasons.
*/
spam: "0" | "1";
/**
* Whether the site should be treated as deleted.
*
* A numeric string, for compatibility reasons.
*/
deleted: "0" | "1";
/**
* The language pack associated with this site.
*
* A numeric string, for compatibility reasons.
*/
lang_id: string;
}
/**
* Core class used for interacting with taxonomies.
*/
export interface WP_Taxonomy {
/**
* Taxonomy key.
*/
name: WP_Taxonomy_Name | string;
/**
* Name of the taxonomy shown in the menu. Usually plural.
*/
label: string;
/**
* Labels object for this taxonomy.
*/
labels: WP_Taxonomy_Labels;
/**
* A short descriptive summary of what the taxonomy is for.
*/
description: string;
/**
* Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users.
*/
public: boolean;
/**
* Whether the taxonomy is publicly queryable.
*/
publicly_queryable: boolean;
/**
* Whether the taxonomy is hierarchical.
*/
hierarchical: boolean;
/**
* Whether to generate and allow a UI for managing terms in this taxonomy in the admin.
*/
show_ui: boolean;
/**
* Whether to show the taxonomy in the admin menu.
*/
show_in_menu: boolean;
/**
* Whether the taxonomy is available for selection in navigation menus.
*/
show_in_nav_menus: boolean;
/**
* Whether to list the taxonomy in the tag cloud widget controls.
*/
show_tagcloud: boolean;
/**
* Whether to show the taxonomy in the quick/bulk edit panel.
*/
show_in_quick_edit: boolean;
/**
* Whether to display a column for the taxonomy on its post type listing screens.
*/
show_admin_column: boolean;
/**
* The callback function for the meta box display.
*/
meta_box_cb: Callable | false;
/**
* The callback function for sanitizing taxonomy data saved from a meta box.
*/
meta_box_sanitize_cb: Callable | false;
/**
* An array of object types this taxonomy is registered for.
*/
object_type: (WP_Post_Type_Name | string)[];
/**
* Capabilities for this taxonomy.
*/
cap: WP_Taxonomy_Caps;
/**
* Rewrites information for this taxonomy.
*/
rewrite: WP_Taxonomy_Rewrite | boolean;
/**
* Query var string for this taxonomy.
*/
query_var: string | boolean;
/**
* Function that will be called when the count is updated.
*/
update_count_callback: Callable | "";
/**
* Whether this taxonomy should appear in the REST API.
*
* Default false. If true, standard endpoints will be registered with respect to $rest_base and $rest_controller_class.
*/
show_in_rest: boolean;
/**
* The base path for this taxonomy's REST API endpoints.
*/
rest_base: string | boolean;
/**
* The controller for this taxonomy's REST API endpoints.
*
* Custom controllers must extend WP_REST_Controller.
*/
rest_controller_class: string | false;
/**
* The controller instance for this taxonomy's REST API endpoints.
*/
rest_controller: null;
/**
* The default term name for this taxonomy. If you pass an array you have to set 'name' and optionally 'slug' and 'description'.
*/
default_term:
| {
name: string;
slug?: string;
description?: string;
}
| string
| null;
/**
* Whether terms in this taxonomy should be sorted in the order they are provided to `wp_set_object_terms()`.
*
* Use this in combination with `'orderby' => 'term_order'` when fetching terms.
*/
sort: boolean | null;
/**
* Array of arguments to automatically use inside `wp_get_object_terms()` for this taxonomy.
*/
args: {
[k: string]: unknown;
} | null;
/**
* Whether it is a built-in taxonomy.
*/
_builtin: boolean;
}
/**
* Taxonomy labels.
*/
export interface WP_Taxonomy_Labels {
name: string;
singular_name: string;
search_items: string;
popular_items: string | null;
all_items: string;
archives?: string;
parent_item: string | null;
parent_item_colon: string | null;
edit_item: string;
view_item: string;
update_item: string;
add_new_item: string;
new_item_name: string;
separate_items_with_commas: string | null;
add_or_remove_items: string | null;
choose_from_most_used: string | null;
not_found: string;
no_terms: string;
filter_by_item: string | null;
items_list_navigation: string;
items_list: string;
most_used: string;
back_to_items: string;
item_link: string;
item_link_description: string;
menu_name: string;
name_admin_bar: string;
}
/**
* Taxonomy capabilities.
*/
export interface WP_Taxonomy_Caps {
manage_terms: WP_User_Cap_Name;
edit_terms: WP_User_Cap_Name;
delete_terms: WP_User_Cap_Name;
assign_terms: WP_User_Cap_Name;
}
/**
* Taxonomy rewrite rule definition.
*/
export interface WP_Taxonomy_Rewrite {
/**
* Should the permastruct be prepended with WP_Rewrite::$front.
*/
with_front: boolean;
/**
* Either hierarchical rewrite tag or not.
*/
hierarchical: boolean;
/**
* Assign an endpoint mask.
*/
ep_mask: number;
/**
* Customize the permastruct slug.
*/
slug: string;
[k: string]: unknown;
}
/**
* A comment object in a REST API context.
*/
export interface WP_REST_API_Comment {
/**
* Unique identifier for the object.
*/
id: number;
/**
* The ID of the user object, if author was a user.
*/
author: number;
/**
* Email address for the comment author. Only present when using the 'edit' context.
*/
author_email?: string | "";
/**
* IP address for the comment author. Only present when using the 'edit' context.
*/
author_ip?: string | "";
/**
* Display name for the comment author.
*/
author_name: string;
/**
* URL for the comment author.
*/
author_url: string | "";
/**
* User agent for the comment author. Only present when using the 'edit' context.
*/
author_user_agent?: string;
/**
* The content for the comment.
*/
content: {
/**
* Content for the comment, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML content for the comment, transformed for display.
*/
rendered?: string;
};
/**
* The date the comment was published, in the site's timezone.
*/
date: WP_REST_API_Date_Time;
/**
* The date the comment was published, as GMT.
*/
date_gmt: WP_REST_API_Date_Time;
/**
* URL to the comment.
*/
link: string;
/**
* The ID for the parent of the comment.
*/
parent: number;
/**
* The ID of the associated post object.
*/
post: number;
/**
* State of the comment.
*/
status: WP_Comment_Status_Name | string;
/**
* Type of comment.
*/
type: WP_Comment_Type_Name | string;
/**
* Avatar URLs for the comment author.
*/
author_avatar_urls?: {
/**
* Avatar URL with image size of 24 pixels.
*/
"24": string;
/**
* Avatar URL with image size of 48 pixels.
*/
"48": string;
/**
* Avatar URL with image size of 96 pixels.
*/
"96": string;
/**
* Avatar URL with image of another size.
*/
[k: string]: string;
};
/**
* Meta fields.
*/
meta:
| []
| {
[k: string]: unknown;
};
_links: WP_REST_API_Object_Links;
/**
* The embedded representation of relations. Only present when the '_embed' query parameter is set.
*/
_embedded?: {
/**
* The author of the comment.
*/
author?: unknown[];
/**
* The associated post.
*/
up?: unknown[];
[k: string]: unknown;
};
[k: string]: unknown;
}
/**
* The relations for the object and its properties.
*/
export interface WP_REST_API_Object_Links {
[k: string]: {
href: string;
embeddable?: boolean;
[k: string]: unknown;
}[];
}
/**
* A post object in a REST API context.
*/
export interface WP_REST_API_Post {
/**
* The date the post was published, in the site's timezone.
*/
date: WP_REST_API_Date_Time;
/**
* The date the post was published, as GMT.
*/
date_gmt: WP_REST_API_Date_Time;
/**
* The globally unique identifier for the post.
*/
guid: {
/**
* GUID for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* GUID for the post, transformed for display.
*/
rendered: string;
};
/**
* Unique identifier for the post.
*/
id: number;
/**
* URL to the post.
*/
link: string;
/**
* The date the post was last modified, in the site's timezone.
*/
modified: WP_REST_API_Date_Time;
/**
* The date the post was last modified, as GMT.
*/
modified_gmt: WP_REST_API_Date_Time;
/**
* An alphanumeric identifier for the post unique to its type.
*/
slug: string;
/**
* A named status for the post.
*/
status: WP_Post_Status_Name | string;
/**
* Type of Post for the post.
*/
type: WP_Post_Type_Name | string;
/**
* A password to protect access to the content and excerpt. Only present when using the 'edit' context.
*/
password?: string;
/**
* Permalink template for the post. Only present when using the 'edit' context and the post type is public.
*/
permalink_template?: string;
/**
* Slug automatically generated from the post title. Only present when using the 'edit' context and the post type is public.
*/
generated_slug?: string;
/**
* The ID for the parent of the post. Only present for hierarchical post types.
*/
parent?: number;
/**
* The title for the post.
*/
title: {
/**
* Title for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML title for the post, transformed for display.
*/
rendered: string;
};
/**
* The content for the post.
*/
content: {
/**
* Content for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML content for the post, transformed for display.
*/
rendered: string;
/**
* Version of the content block format used by the post. Only present when using the 'edit' context.
*/
block_version?: number;
/**
* Whether the content is protected with a password.
*/
protected: boolean;
};
/**
* The ID for the author of the post.
*/
author: number;
/**
* The excerpt for the post.
*/
excerpt: {
/**
* Excerpt for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML excerpt for the post, transformed for display.
*/
rendered: string;
/**
* Whether the excerpt is protected with a password.
*/
protected: boolean;
};
/**
* The ID of the featured media for the post.
*/
featured_media?: number;
/**
* Whether or not comments are open on the post.
*/
comment_status: WP_Post_Comment_Status_Name;
/**
* Whether or not the post can be pinged.
*/
ping_status: WP_Post_Comment_Status_Name;
/**
* The format for the post.
*/
format?: WP_Post_Format_Name;
/**
* Meta fields.
*/
meta:
| []
| {
[k: string]: unknown;
};
/**
* Whether or not the post should be treated as sticky. Only present for the 'post' post type.
*/
sticky?: boolean;
/**
* The theme file to use to display the post.
*/
template?: string;
/**
* The terms assigned to the post in the category taxonomy. Only present for post types that support categories.
*/
categories?: number[];
/**
* The terms assigned to the post in the post_tag taxonomy. Only present for post types that support tags.
*/
tags?: number[];
_links: WP_REST_API_Object_Links;
/**
* The embedded representation of relations. Only present when the '_embed' query parameter is set.
*/
_embedded?: {
/**
* The author of the post.
*/
author: unknown[];
/**
* The replies to the post (comments, pingbacks, trackbacks).
*/
replies?: unknown[];
/**
* The taxonomy terms for the post.
*/
"wp:term"?: unknown[];
/**
* The featured image post.
*/
"wp:featuredmedia"?: unknown[];
/**
* The parent post.
*/
up?: unknown[];
[k: string]: unknown;
};
[k: string]: unknown;
}
/**
* A media attachment object in a REST API context.
*/
export interface WP_REST_API_Attachment {
/**
* The date the attachment was published, in the site's timezone.
*/
date: WP_REST_API_Date_Time;
/**
* The date the attachment was published, as GMT.
*/
date_gmt: WP_REST_API_Date_Time;
/**
* The globally unique identifier for the attachment.
*/
guid: {
/**
* GUID for the attachment, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* GUID for the attachment, transformed for display.
*/
rendered: string;
};
/**
* Unique identifier for the attachment.
*/
id: number;
/**
* URL to the attachment.
*/
link: string;
/**
* The date the attachment was last modified, in the site's timezone.
*/
modified: WP_REST_API_Date_Time;
/**
* The date the attachment was last modified, as GMT.
*/
modified_gmt: WP_REST_API_Date_Time;
/**
* An alphanumeric identifier for the attachment unique to its type.
*/
slug: string;
/**
* A named status for the attachment.
*/
status: WP_Post_Status_Name | string;
/**
* Type of Post for the attachment.
*/
type: WP_Post_Type_Name.attachment;
/**
* Alternative text to display when attachment is not displayed.
*/
alt_text: string;
/**
* The attachment caption.
*/
caption: {
/**
* Caption for the attachment, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML caption for the attachment, transformed for display.
*/
rendered: string;
};
/**
* The attachment description.
*/
description: {
/**
* Description for the attachment, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML description for the attachment, transformed for display.
*/
rendered: string;
};
/**
* The attachment MIME type.
*/
media_type: string;
/**
* Details about the media file, specific to its type.
*/
media_details: {
[k: string]: unknown;
};
/**
* The ID for the associated post of the attachment.
*/
post: number;
/**
* URL to the original attachment file.
*/
source_url: string;
/**
* List of the missing image sizes of the attachment. Only present when using the 'edit' context.
*/
missing_image_sizes: string[];
/**
* Permalink template for the attachment. Only present when using the 'edit' context and the post type is public.
*/
permalink_template?: string;
/**
* Slug automatically generated from the attachment title. Only present when using the 'edit' context and the post type is public.
*/
generated_slug?: string;
/**
* The title for the attachment.
*/
title: {
/**
* Title for the attachment, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML title for the attachment, transformed for display.
*/
rendered: string;
};
/**
* The ID for the author of the attachment.
*/
author: number;
/**
* Whether or not comments are open on the attachment.
*/
comment_status: WP_Post_Comment_Status_Name;
/**
* Whether or not the attachment can be pinged.
*/
ping_status: WP_Post_Comment_Status_Name;
/**
* Meta fields.
*/
meta:
| []
| {
[k: string]: unknown;
};
/**
* The theme file to use to display the attachment.
*/
template: string;
_links: WP_REST_API_Object_Links;
/**
* The embedded representation of relations. Only present when the '_embed' query parameter is set.
*/
_embedded?: {
/**
* The author of the post.
*/
author: unknown[];
/**
* The featured image post.
*/
"wp:featuredmedia"?: unknown[];
[k: string]: unknown;
};
[k: string]: unknown;
}
/**
* A reusable block object in a REST API context.
*/
export interface WP_REST_API_Block {
/**
* The date the block was published, in the site's timezone.
*/
date: WP_REST_API_Date_Time;
/**
* The date the block was published, as GMT.
*/
date_gmt: WP_REST_API_Date_Time;
/**
* The globally unique identifier for the block.
*/
guid: {
/**
* GUID for the block, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* GUID for the block, transformed for display.
*/
rendered: string;
};
/**
* Unique identifier for the block.
*/
id: number;
/**
* URL to the block.
*/
link: string;
/**
* The date the block was last modified, in the site's timezone.
*/
modified: WP_REST_API_Date_Time;
/**
* The date the block was last modified, as GMT.
*/
modified_gmt: WP_REST_API_Date_Time;
/**
* An alphanumeric identifier for the block unique to its type.
*/
slug: string;
/**
* A named status for the block.
*/
status: WP_Post_Status_Name | string;
/**
* Type of Post for the block.
*/
type: WP_Post_Type_Name.wp_block;
/**
* A password to protect access to the content and excerpt. Only present when using the 'edit' context.
*/
password?: string;
/**
* The title for the block.
*/
title: {
/**
* Title for the block, as it exists in the database.
*/
raw: string;
};
/**
* The content for the block.
*/
content: {
/**
* Content for the block, as it exists in the database.
*/
raw: string;
/**
* Version of the content block format used by the block. Only present when using the 'edit' context.
*/
block_version?: number;
/**
* Whether the content is protected with a password.
*/
protected: boolean;
};
/**
* The theme file to use to display the block.
*/
template?: string;
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A block directory search result in a REST API context.
*/
export interface WP_REST_API_Block_Directory_Item {
/**
* The block name, in namespace/block-name format.
*/
name: string;
/**
* The block title, in human readable format.
*/
title: string;
/**
* A short description of the block, in human readable format.
*/
description: string;
/**
* The block slug.
*/
id: string;
/**
* The star rating of the block.
*/
rating: number;
/**
* The number of ratings.
*/
rating_count: number;
/**
* The number sites that have activated this block.
*/
active_installs: number;
/**
* The average rating of blocks published by the same author.
*/
author_block_rating: number;
/**
* The number of blocks published by the same author.
*/
author_block_count: number;
/**
* The WordPress.org username of the block author.
*/
author: string;
/**
* The block icon.
*/
icon: string;
/**
* The date when the block was last updated.
*/
last_updated: string;
/**
* The date when the block was last updated, in fuzzy human readable format.
*/
humanized_updated: string;
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A block type object in a REST API context.
*/
export interface WP_REST_API_Block_Type {
/**
* Version of block API.
*/
api_version: number;
/**
* Title of block type.
*/
title: string;
/**
* Unique name identifying the block type.
*/
name: string;
/**
* Description of block type.
*/
description: string;
/**
* Icon of block type.
*/
icon: string | null;
/**
* Block attributes.
*/
attributes:
| []
| {
[k: string]: unknown;
}
| null;
/**
* Context provided by blocks of this type.
*/
provides_context:
| []
| {
[k: string]: string;
};
/**
* Context values inherited by blocks of this type.
*/
uses_context: string[];
/**
* Block supports.
*/
supports: {
[k: string]: unknown;
};
/**
* Block category.
*/
category: string | null;
/**
* Is the block dynamically rendered.
*/
is_dynamic: boolean;
/**
* Editor script handle.
*/
editor_script: string | null;
/**
* Public facing script handle.
*/
script: string | null;
/**
* Editor style handle.
*/
editor_style: string | null;
/**
* Public facing style handle.
*/
style: string | null;
/**
* Block style variations.
*/
styles: {
/**
* Unique name identifying the style.
*/
name: string;
/**
* The human-readable label for the style.
*/
label?: string;
/**
* Inline CSS code that registers the CSS class required for the style.
*/
inline_style?: string;
/**
* Contains the handle that defines the block style.
*/
style_handle?: string;
[k: string]: unknown;
}[];
/**
* Public text domain.
*/
textdomain: string | null;
/**
* Parent blocks.
*/
parent: string[] | null;
/**
* Block keywords.
*/
keywords: string[];
/**
* Block example.
*/
example: {
/**
* The attributes used in the example.
*/
attributes?: {
[k: string]: unknown;
};
/**
* The list of inner blocks used in the example.
*/
innerBlocks?: {
/**
* The name of the inner block.
*/
name?: string;
/**
* The attributes of the inner block.
*/
attributes?: {
[k: string]: unknown;
};
/**
* A list of the inner block's own inner blocks. This is a recursive definition following the parent innerBlocks schema.
*/
innerBlocks?: unknown[];
[k: string]: unknown;
}[];
[k: string]: unknown;
} | null;
[k: string]: unknown;
}
/**
* A revision object in a REST API context.
*/
export interface WP_REST_API_Revision {
/**
* The ID for the author of the revision.
*/
author: number;
/**
* The date the revision was published, in the site's timezone.
*/
date: WP_REST_API_Date_Time;
/**
* The date the revision was published, as GMT.
*/
date_gmt: WP_REST_API_Date_Time;
/**
* The globally unique identifier for the post.
*/
guid: {
/**
* GUID for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* GUID for the post, transformed for display.
*/
rendered: string;
[k: string]: unknown;
};
/**
* Unique identifier for the revision.
*/
id: number;
/**
* The date the revision was last modified, in the site's timezone.
*/
modified: WP_REST_API_Date_Time;
/**
* The date the revision was last modified, as GMT.
*/
modified_gmt: WP_REST_API_Date_Time;
/**
* The ID for the parent of the revision.
*/
parent: number;
/**
* An alphanumeric identifier for the revision unique to its type.
*/
slug: string;
/**
* The title for the post.
*/
title: {
/**
* Title for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML title for the post, transformed for display.
*/
rendered: string;
[k: string]: unknown;
};
/**
* The content for the post.
*/
content: {
/**
* Content for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML content for the post, transformed for display.
*/
rendered: string;
/**
* Version of the content block format used by the post. Only present when using the 'edit' context.
*/
block_version?: number;
[k: string]: unknown;
};
/**
* The excerpt for the post.
*/
excerpt: {
/**
* Excerpt for the post, as it exists in the database. Only present when using the 'edit' context.
*/
raw?: string;
/**
* HTML excerpt for the post, transformed for display.
*/
rendered: string;
[k: string]: unknown;
};
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A rendered dynamic block in a REST API context. Only accessible with the 'edit' context.
*/
export interface WP_REST_API_Rendered_Block {
/**
* The rendered block.
*/
rendered: string;
[k: string]: unknown;
}
/**
* A post status object in a REST API context.
*/
export interface WP_REST_API_Status {
/**
* The title for the status.
*/
name: string;
/**
* Whether posts with this status should be private. Only present when using the 'edit' context.
*/
private?: boolean;
/**
* Whether posts with this status should be protected. Only present when using the 'edit' context.
*/
protected?: boolean;
/**
* Whether posts of this status should be shown in the front end of the site.
*/
public: boolean;
/**
* Whether posts with this status should be publicly-queryable.
*/
queryable: boolean;
/**
* Whether to include posts in the edit listing for their post type. Only present when using the 'edit' context.
*/
show_in_list?: boolean;
/**
* An alphanumeric identifier for the status.
*/
slug: string;
/**
* Whether posts of this status may have floating published dates.
*/
date_floating: boolean;
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A collection of post status objects in a REST API context.
*/
export interface WP_REST_API_Statuses {
[k: string]: WP_REST_API_Status;
}
/**
* A taxonomy term object in a REST API context.
*/
export interface WP_REST_API_Term {
/**
* Unique identifier for the term.
*/
id: number;
/**
* Number of published posts for the term.
*/
count: number;
/**
* HTML description of the term.
*/
description: string;
/**
* URL of the term.
*/
link: string;
/**
* HTML title for the term.
*/
name: string;
/**
* An alphanumeric identifier for the term unique to its type.
*/
slug: string;
/**
* Type attribution for the term.
*/
taxonomy: WP_Taxonomy_Name | string;
/**
* The parent term ID. Only present for hierarchical taxonomies.
*/
parent?: number;
/**
* Meta fields.
*/
meta:
| []
| {
[k: string]: unknown;
};
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A user object in a REST API context.
*/
export interface WP_REST_API_User {
/**
* Unique identifier for the user.
*/
id: number;
/**
* Login name for the user. Only present when using the 'edit' context.
*/
username?: string;
/**
* Display name for the user.
*/
name: string;
/**
* First name for the user. Only present when using the 'edit' context.
*/
first_name?: string;
/**
* Last name for the user. Only present when using the 'edit' context.
*/
last_name?: string;
/**
* The email address for the user. Only present when using the 'edit' context.
*/
email?: string | "";
/**
* URL of the user.
*/
url: string | "";
/**
* Description of the user.
*/
description: string;
/**
* Author URL of the user.
*/
link: string;
/**
* Locale for the user. Only present when using the 'edit' context.
*/
locale?: string;
/**
* The nickname for the user. Only present when using the 'edit' context.
*/
nickname?: string;
/**
* An alphanumeric identifier for the user.
*/
slug: string;
/**
* Registration date for the user in UTC. Only present when using the 'edit' context.
*/
registered_date?: WP_REST_API_Date_Time_UTC;
/**
* Roles assigned to the user. Only present when using the 'edit' context.
*/
roles?: (WP_User_Role_Name | string)[];
/**
* All capabilities assigned to the user. Only present when using the 'edit' context.
*/
capabilities?: WP_User_Caps;
/**
* Any extra capabilities assigned to the user. Only present when using the 'edit' context.
*/
extra_capabilities?: WP_User_Caps;
/**
* Avatar URLs for the user.
*/
avatar_urls?: {
/**
* Avatar URL with image size of 24 pixels.
*/
"24": string;
/**
* Avatar URL with image size of 48 pixels.
*/
"48": string;
/**
* Avatar URL with image size of 96 pixels.
*/
"96": string;
/**
* Avatar URL with image of another size.
*/
[k: string]: string;
};
/**
* Meta fields.
*/
meta:
| []
| {
[k: string]: unknown;
};
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A search result in a REST API context.
*/
export interface WP_REST_API_Search_Result {
/**
* Unique identifier for the object.
*/
id: number | string;
/**
* The title for the object.
*/
title: string;
/**
* URL to the object.
*/
url: string;
/**
* Object type.
*/
type: "post" | "term" | "post-format";
/**
* Object subtype.
*/
subtype: WP_Post_Type_Name | WP_Taxonomy_Name | string;
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* Site settings in a REST API context.
*/
export interface WP_REST_API_Settings {
/**
* Site title.
*/
title: string;
/**
* Site tagline.
*/
description: string;
/**
* Site URL. Not available on Multisite.
*/
url?: string;
/**
* This address is used for admin purposes, like new user notification. Not available on Multisite.
*/
email?: string;
/**
* A city in the same timezone as you.
*/
timezone: string;
/**
* A date format for all date strings.
*/
date_format: string;
/**
* A time format for all time strings.
*/
time_format: string;
/**
* A day number of the week that the week should start on.
*/
start_of_week: number;
/**
* WordPress locale code.
*/
language: string;
/**
* Convert emoticons like :-) and :-P to graphics on display.
*/
use_smilies: boolean;
/**
* Default post category.
*/
default_category: number;
/**
* Default post format.
*/
default_post_format: string;
/**
* Blog pages show at most.
*/
posts_per_page: number;
/**
* Allow link notifications from other blogs (pingbacks and trackbacks) on new articles.
*/
default_ping_status: WP_Post_Comment_Status_Name;
/**
* Allow people to submit comments on new posts.
*/
default_comment_status: WP_Post_Comment_Status_Name;
/**
* Site logo.
*/
site_logo?: number | null;
}
/**
* A taxonomy in a REST API context.
*/
export interface WP_REST_API_Taxonomy {
/**
* All capabilities used by the taxonomy. Only present when using the 'edit' context.
*/
capabilities?: WP_Taxonomy_Caps;
/**
* A human-readable description of the taxonomy.
*/
description: string;
/**
* Whether or not the taxonomy should have children.
*/
hierarchical: boolean;
/**
* Human-readable labels for the taxonomy for various contexts. Only present when using the 'edit' context.
*/
labels?: WP_Taxonomy_Labels;
/**
* The title for the taxonomy.
*/
name: string;
/**
* An alphanumeric identifier for the taxonomy.
*/
slug: WP_Taxonomy_Name | string;
/**
* Whether or not the term cloud should be displayed. Only present when using the 'edit' context.
*/
show_cloud?: boolean;
/**
* Types associated with the taxonomy.
*/
types: (WP_Post_Type_Name | string)[];
/**
* REST base route for the taxonomy. Only present when using the 'edit' context.
*/
rest_base: string;
/**
* The visibility settings for the taxonomy. Only present when using the 'edit' context.
*/
visibility?: {
/**
* Whether a taxonomy is intended for use publicly either via the admin interface or by front-end users.
*/
public: boolean;
/**
* Whether the taxonomy is publicly queryable.
*/
publicly_queryable: boolean;
/**
* Whether to generate a default UI for managing this taxonomy.
*/
show_ui: boolean;
/**
* Whether to allow automatic creation of taxonomy columns on associated post-types table.
*/
show_admin_column: boolean;
/**
* Whether to make the taxonomy available for selection in navigation menus.
*/
show_in_nav_menus: boolean;
/**
* Whether to show the taxonomy in the quick/bulk edit panel.
*/
show_in_quick_edit: boolean;
};
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A collection of taxonomy objects in a REST API context.
*/
export interface WP_REST_API_Taxonomies {
[k: string]: WP_REST_API_Taxonomy;
}
/**
* A post type object in a REST API context.
*/
export interface WP_REST_API_Type {
/**
* All capabilities used by the post type. Only present when using the 'edit' context.
*/
capabilities?: WP_Post_Type_Caps;
/**
* A human-readable description of the post type.
*/
description: string;
/**
* Whether or not the post type should have children.
*/
hierarchical: boolean;
/**
* Whether or not the post type can be viewed. Only present when using the 'edit' context.
*/
viewable?: boolean;
/**
* Human-readable labels for the post type for various contexts. Only present when using the 'edit' context.
*/
labels?: WP_Post_Type_Labels;
/**
* The title for the post type.
*/
name: string;
/**
* An alphanumeric identifier for the post type.
*/
slug: WP_Post_Type_Name | string;
/**
* All features, supported by the post type. Only present when using the 'edit' context.
*/
supports?: {
[k: string]: unknown;
};
/**
* Taxonomies associated with post type.
*/
taxonomies: (WP_Taxonomy_Name | string)[];
/**
* REST base route for the post type. Only present when using the 'edit' context.
*/
rest_base: string;
_links: WP_REST_API_Object_Links;
[k: string]: unknown;
}
/**
* A collection of post type object in a REST API context.
*/
export interface WP_REST_API_Types {
[k: string]: WP_REST_API_Type;
}
/**
* A user application password in a REST API context.
*/
export interface WP_REST_API_Application_Password {
/**
* The unique identifier for the application password.
*/
uuid: string;
/**
* A UUID provided by the application to uniquely identify it. It is recommended to use an UUID v5 with the URL or DNS namespace.
*/
app_id: string;
/**
* The name of the application password.
*/
name: string;
/**
* The generated password. Only available after adding an application.
*/
password?: string;
/**
* The GMT date the application password was created.
*/
created: WP_REST_API_Date_Time;
/**
* The GMT date the application password was last used.
*/
last_used: WP_REST_API_Date_Time | null;
/**
* The IP address the application password was last used by.
*/
last_ip: string | null;
_links?: WP_REST_API_Object_Links;
}
/**
* A REST API error response.
*/
export interface WP_REST_API_Error {
/**
* The error message code.
*/
code: string;
/**
* The error message text.
*/
message: string;
/**
* Extra data about the error
*/
data: {
/**
* The HTTP status code
*/
status?: WP_Http_Status_Code;
[k: string]: unknown;
};
/**
* Additional error objects, if there are any.
*/
additional_errors?: WP_REST_API_Error[];
}
export const enum WP_Comment_Type_Name {
comment = "comment",
pingback = "pingback",
trackback = "trackback",
}
export const enum WP_Post_Status_Name {
publish = "publish",
draft = "draft",
auto_draft = "auto-draft",
inherit = "inherit",
pending = "pending",
future = "future",
trash = "trash",
private = "private",
}
export const enum WP_Post_Comment_Status_Name {
open = "open",
closed = "closed",
}
export const enum WP_Post_Type_Name {
post = "post",
page = "page",
attachment = "attachment",
revision = "revision",
nav_menu_item = "nav_menu_item",
custom_css = "custom_css",
customize_changeset = "customize_changeset",
oembed_cache = "oembed_cache",
user_request = "user_request",
wp_block = "wp_block",
}
export const enum WP_Object_Filter_Context {
attribute = "attribute",
db = "db",
display = "display",
edit = "edit",
js = "js",
raw = "raw",
rss = "rss",
}
export const enum WP_Taxonomy_Name {
category = "category",
post_tag = "post_tag",
nav_menu = "nav_menu",
post_format = "post_format",
}
export const enum WP_User_Role_Name {
administrator = "administrator",
editor = "editor",
author = "author",
contributor = "contributor",
subscriber = "subscriber",
}
export const enum WP_Comment_Status_Name {
approved = "approved",
unapproved = "unapproved",
spam = "spam",
trash = "trash",
}
export const enum WP_Post_Format_Name {
aside = "aside",
audio = "audio",
chat = "chat",
gallery = "gallery",
image = "image",
link = "link",
quote = "quote",
standard = "standard",
status = "status",
video = "video",
}
export const enum WP_Http_Status_Code {
HTTP_CONTINUE = 100,
SWITCHING_PROTOCOLS = 101,
PROCESSING = 102,
EARLY_HINTS = 103,
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
MULTI_STATUS = 207,
IM_USED = 226,
MULTIPLE_CHOICES = 300,
MOVED_PERMANENTLY = 301,
FOUND = 302,
SEE_OTHER = 303,
NOT_MODIFIED = 304,
USE_PROXY = 305,
RESERVED = 306,
TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
PAYMENT_REQUIRED = 402,
FORBIDDEN = 403,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED = 405,
NOT_ACCEPTABLE = 406,
PROXY_AUTHENTICATION_REQUIRED = 407,
REQUEST_TIMEOUT = 408,
CONFLICT = 409,
GONE = 410,
LENGTH_REQUIRED = 411,
PRECONDITION_FAILED = 412,
REQUEST_ENTITY_TOO_LARGE = 413,
REQUEST_URI_TOO_LONG = 414,
UNSUPPORTED_MEDIA_TYPE = 415,
REQUESTED_RANGE_NOT_SATISFIABLE = 416,
EXPECTATION_FAILED = 417,
IM_A_TEAPOT = 418,
MISDIRECTED_REQUEST = 421,
UNPROCESSABLE_ENTITY = 422,
LOCKED = 423,
FAILED_DEPENDENCY = 424,
UPGRADE_REQUIRED = 426,
PRECONDITION_REQUIRED = 428,
TOO_MANY_REQUESTS = 429,
REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
UNAVAILABLE_FOR_LEGAL_REASONS = 451,
INTERNAL_SERVER_ERROR = 500,
NOT_IMPLEMENTED = 501,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
GATEWAY_TIMEOUT = 504,
HTTP_VERSION_NOT_SUPPORTED = 505,
VARIANT_ALSO_NEGOTIATES = 506,
INSUFFICIENT_STORAGE = 507,
NOT_EXTENDED = 510,
NETWORK_AUTHENTICATION_REQUIRED = 511,
}
type ValueOf<T> = T[keyof T]
/**
* An enveloped REST API response.
*
* @template T A REST API response type.
*/
export interface WP_REST_API_Envelope<T extends ValueOf<WP["REST_API"]>> {
/**
* The response body
*/
body: T;
/**
* The HTTP status code
*/
status: WP_Http_Status_Code;
/**
* The HTTP headers
*/
headers: object;
} | the_stack |
import { CompilationData, Compiler } from '../template/compiler-types';
import {
CompilationError,
CompilationResultParseError,
CompilationResultReduceError,
CompilationResultResolveError,
} from '../template/language/language-types';
import {
allErrorsAreRecoverable,
extractResolvedVariableBytecodeMap,
} from '../template/language/language-utils';
import {
encodeOutpoints,
encodeOutput,
encodeOutputsForSigning,
encodeSequenceNumbersForSigning,
} from './transaction-serialization';
import {
BytecodeGenerationCompletionInput,
BytecodeGenerationCompletionOutput,
BytecodeGenerationErrorBase,
BytecodeGenerationErrorLocking,
BytecodeGenerationErrorUnlocking,
Input,
InputTemplate,
Output,
OutputTemplate,
TransactionContextCommon,
TransactionGenerationAttempt,
TransactionGenerationError,
TransactionTemplateFixed,
} from './transaction-types';
const returnFailedCompilationDirective = <
Type extends 'locking' | 'unlocking'
>({
index,
result,
type,
}: {
index: number;
result:
| CompilationResultParseError
| CompilationResultResolveError
| CompilationResultReduceError<unknown>;
type: Type;
}) => {
return {
errors: result.errors.map((error) => ({
...error,
error: `Failed compilation of ${type} directive at index "${index}": ${error.error}`,
})),
index,
...(result.errorType === 'parse' ? {} : { resolved: result.resolve }),
type,
};
};
export const compileOutputTemplate = <
CompilerType extends Compiler<TransactionContextCommon, unknown, unknown>
>({
outputTemplate,
index,
}: {
outputTemplate: OutputTemplate<CompilerType>;
index: number;
}): Output | BytecodeGenerationErrorLocking => {
if ('script' in outputTemplate.lockingBytecode) {
const directive = outputTemplate.lockingBytecode;
const data = directive.data === undefined ? {} : directive.data;
const result = directive.compiler.generateBytecode(
directive.script,
data,
true
);
return result.success
? {
lockingBytecode: result.bytecode,
satoshis: outputTemplate.satoshis,
}
: returnFailedCompilationDirective({ index, result, type: 'locking' });
}
return {
lockingBytecode: outputTemplate.lockingBytecode.slice(),
satoshis: outputTemplate.satoshis,
};
};
export const compileInputTemplate = <
CompilerType extends Compiler<TransactionContextCommon, unknown, unknown>
>({
inputTemplate,
index,
outputs,
template,
transactionOutpoints,
transactionSequenceNumbers,
}: {
inputTemplate: InputTemplate<CompilerType>;
index: number;
outputs: Output[];
template: Readonly<TransactionTemplateFixed<CompilerType>>;
transactionOutpoints: Uint8Array;
transactionSequenceNumbers: Uint8Array;
}): Input | BytecodeGenerationErrorUnlocking => {
if ('script' in inputTemplate.unlockingBytecode) {
const directive = inputTemplate.unlockingBytecode;
const correspondingOutput = outputs[index] as Output | undefined;
const result = directive.compiler.generateBytecode(
directive.script,
{
...directive.data,
transactionContext: {
correspondingOutput:
correspondingOutput === undefined
? undefined
: encodeOutput(correspondingOutput),
locktime: template.locktime,
outpointIndex: inputTemplate.outpointIndex,
outpointTransactionHash: inputTemplate.outpointTransactionHash.slice(),
outputValue: directive.satoshis,
sequenceNumber: inputTemplate.sequenceNumber,
transactionOutpoints: transactionOutpoints.slice(),
transactionOutputs: encodeOutputsForSigning(outputs),
transactionSequenceNumbers: transactionSequenceNumbers.slice(),
version: template.version,
},
},
true
);
return result.success
? {
outpointIndex: inputTemplate.outpointIndex,
outpointTransactionHash: inputTemplate.outpointTransactionHash.slice(),
sequenceNumber: inputTemplate.sequenceNumber,
unlockingBytecode: result.bytecode,
}
: returnFailedCompilationDirective({ index, result, type: 'unlocking' });
}
return {
outpointIndex: inputTemplate.outpointIndex,
outpointTransactionHash: inputTemplate.outpointTransactionHash.slice(),
sequenceNumber: inputTemplate.sequenceNumber,
unlockingBytecode: inputTemplate.unlockingBytecode.slice(),
};
};
/**
* Generate a `Transaction` given a `TransactionTemplate` and any applicable
* compilers and compilation data.
*
* Returns either a `Transaction` or an array of compilation errors.
*
* For each `CompilationDirective`, the `transactionContext` property will be
* automatically provided to the compiler. All other necessary `CompilationData`
* properties must be specified in the `TransactionTemplate`.
*
* @param template - the `TransactionTemplate` from which to create the
* `Transaction`
*/
export const generateTransaction = <
CompilerType extends Compiler<TransactionContextCommon, unknown, unknown>
>(
template: Readonly<TransactionTemplateFixed<CompilerType>>
): TransactionGenerationAttempt => {
const outputResults = template.outputs.map((outputTemplate, index) =>
compileOutputTemplate({
index,
outputTemplate,
})
);
const outputCompilationErrors = outputResults.filter(
(result): result is BytecodeGenerationErrorLocking => 'errors' in result
);
if (outputCompilationErrors.length > 0) {
const outputCompletions = outputResults
.map<BytecodeGenerationCompletionOutput | BytecodeGenerationErrorLocking>(
(result, index) =>
'lockingBytecode' in result
? { index, output: result, type: 'output' }
: result
)
.filter(
(result): result is BytecodeGenerationCompletionOutput =>
'output' in result
);
return {
completions: outputCompletions,
errors: outputCompilationErrors,
stage: 'outputs',
success: false,
};
}
const outputs = outputResults as Output[];
const inputSerializationElements = template.inputs.map((inputTemplate) => ({
outpointIndex: inputTemplate.outpointIndex,
outpointTransactionHash: inputTemplate.outpointTransactionHash.slice(),
sequenceNumber: inputTemplate.sequenceNumber,
}));
const transactionOutpoints = encodeOutpoints(inputSerializationElements);
const transactionSequenceNumbers = encodeSequenceNumbersForSigning(
inputSerializationElements
);
const inputResults = template.inputs.map((inputTemplate, index) =>
compileInputTemplate({
index,
inputTemplate,
outputs,
template,
transactionOutpoints,
transactionSequenceNumbers,
})
);
const inputCompilationErrors = inputResults.filter(
(result): result is BytecodeGenerationErrorUnlocking => 'errors' in result
);
if (inputCompilationErrors.length > 0) {
const inputCompletions = inputResults
.map<
BytecodeGenerationCompletionInput | BytecodeGenerationErrorUnlocking
>((result, index) =>
'unlockingBytecode' in result
? { index, input: result, type: 'input' }
: result
)
.filter(
(result): result is BytecodeGenerationCompletionInput =>
'input' in result
);
return {
completions: inputCompletions,
errors: inputCompilationErrors,
stage: 'inputs',
success: false,
};
}
const inputs = inputResults as Input[];
return {
success: true,
transaction: {
inputs,
locktime: template.locktime,
outputs,
version: template.version,
},
};
};
/**
* TODO: fundamentally unsound, migrate to PST format
*
* Extract a map of successfully resolved variables to their resolved bytecode.
*
* @param transactionGenerationError - a transaction generation attempt where
* `success` is `false`
*/
export const extractResolvedVariables = (
transactionGenerationError: TransactionGenerationError
) =>
(transactionGenerationError.errors as BytecodeGenerationErrorBase[]).reduce<{
[fullIdentifier: string]: Uint8Array;
}>(
(all, error) =>
error.resolved === undefined
? all
: { ...all, ...extractResolvedVariableBytecodeMap(error.resolved) },
{}
);
/**
* TODO: fundamentally unsound, migrate to PST format
*
* Given an unsuccessful transaction generation result, extract a map of the
* identifiers missing from the compilation mapped to the entity which owns each
* variable.
*
* Returns `false` if any errors are fatal (the error either cannot be resolved
* by providing a variable, or the entity ownership of the required variable was
* not provided in the compilation data).
*
* @param transactionGenerationError - a transaction generation result where
* `success` is `false`
*/
export const extractMissingVariables = (
transactionGenerationError: TransactionGenerationError
) => {
const allErrors = (transactionGenerationError.errors as BytecodeGenerationErrorBase[]).reduce<
CompilationError[]
>((all, error) => [...all, ...error.errors], []);
if (!allErrorsAreRecoverable(allErrors)) {
return false;
}
return allErrors.reduce<{ [fullIdentifier: string]: string }>(
(all, error) => ({
...all,
[error.missingIdentifier]: error.owningEntity,
}),
{}
);
};
/**
* TODO: fundamentally unsound, migrate to PST format
*
* Safely extend a compilation data with resolutions provided by other entities
* (via `extractResolvedVariables`).
*
* It is security-critical that compilation data only be extended with expected
* identifiers from the proper owning entity of each variable. See
* `CompilationData.bytecode` for details.
*
* Returns `false` if any errors are fatal (the error either cannot be resolved
* by providing a variable, or the entity ownership of the required variable was
* not provided in the compilation data).
*
* @remarks
* To determine which identifiers are required by a given compilation, the
* compilation is first attempted with only trusted variables: variables owned
* or previously verified (like `WalletData`) by the compiling entity. If this
* compilation produces a `TransactionGenerationError`, the error can be
* provided to `safelyExtendCompilationData`, along with the trusted compilation
* data and a mapping of untrusted resolutions (where the result of
* `extractResolvedVariables` is assigned to the entity ID of the entity from
* which they were received).
*
* The first compilation must use only trusted compilation data
*/
export const safelyExtendCompilationData = <
TransactionContext = TransactionContextCommon
>(
transactionGenerationError: TransactionGenerationError,
trustedCompilationData: CompilationData<TransactionContext>,
untrustedResolutions: {
[providedByEntityId: string]: ReturnType<typeof extractResolvedVariables>;
}
): false | CompilationData<TransactionContext> => {
const missing = extractMissingVariables(transactionGenerationError);
if (missing === false) return false;
const selectedResolutions = Object.entries(missing).reduce<{
[fullIdentifier: string]: Uint8Array;
}>((all, [identifier, entityId]) => {
const entityResolution = untrustedResolutions[entityId] as
| {
[fullIdentifier: string]: Uint8Array;
}
| undefined;
if (entityResolution === undefined) {
return all;
}
const resolution = entityResolution[identifier] as Uint8Array | undefined;
if (resolution === undefined) {
return all;
}
return { ...all, [identifier]: resolution };
}, {});
return {
...trustedCompilationData,
bytecode: {
...selectedResolutions,
...trustedCompilationData.bytecode,
},
};
}; | the_stack |
import * as fs from 'fs'
import parseArgs from 'minimist'
import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor'
import { constants } from '@opengsn/common/dist/Constants'
import { Address, NpmLogLevel } from '@opengsn/common/dist/types/Aliases'
import { KeyManager } from './KeyManager'
import { TxStoreManager } from './TxStoreManager'
import { createServerLogger } from './ServerWinstonLogger'
import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface'
import { GasPriceFetcher } from './GasPriceFetcher'
import { ReputationManager, ReputationManagerConfiguration } from './ReputationManager'
import { defaultEnvironment } from '@opengsn/common/dist/Environments'
import { Environment, environments, EnvironmentsKeys } from '@opengsn/common'
import { toBN } from 'web3-utils'
export enum LoggingProviderMode {
NONE,
DURATION,
ALL,
CHATTY
}
// TODO: is there a way to merge the typescript definition ServerConfigParams with the runtime checking ConfigParamTypes ?
export interface ServerConfigParams {
ownerAddress: string
baseRelayFee: string
pctRelayFee: number
url: string
port: number
relayHubAddress: string
ethereumNodeUrl: string
workdir: string
checkInterval: number
devMode: boolean
loggingProvider: LoggingProviderMode
// if set, must match clients' "relayRegistrationMaximumAge" parameter for relay to remain discoverable
registrationRateSeconds: number
maxAcceptanceBudget: number
alertedDelaySeconds: number
minAlertedDelayMS: number
maxAlertedDelayMS: number
trustedPaymasters: Address[]
blacklistedPaymasters: Address[]
gasPriceFactor: number
gasPriceOracleUrl: string
gasPriceOraclePath: string
logLevel: NpmLogLevel
loggerUrl: string
loggerUserId: string
etherscanApiUrl: string
etherscanApiKey: string
workerMinBalance: number
workerTargetBalance: number
managerMinBalance: number
managerMinStake: string
managerStakeTokenAddress: string
managerTargetBalance: number
minHubWithdrawalBalance: number
withdrawToOwnerOnBalance?: number
refreshStateTimeoutBlocks: number
pendingTransactionTimeoutSeconds: number
confirmationsNeeded: number
dbAutoCompactionInterval: number
retryGasPriceFactor: number
maxGasPrice: string
defaultPriorityFee: string
defaultGasLimit: number
requestMinValidSeconds: number
runPenalizer: boolean
runPaymasterReputations: boolean
requiredVersionRange?: string
// when server starts, it will look for relevant Relay Hub, Stake Manager events starting at this block
coldRestartLogsFromBlock?: number
// if the number of blocks per 'getLogs' query is limited, use pagination with this page size
pastEventsQueryMaxPageSize: number
environmentName?: string
// number of blocks the server will not repeat a ServerAction for regardless of blockchain state to avoid duplicates
recentActionAvoidRepeatDistanceBlocks: number
}
export interface ServerDependencies {
// TODO: rename as this name is terrible
managerKeyManager: KeyManager
workersKeyManager: KeyManager
contractInteractor: ContractInteractor
gasPriceFetcher: GasPriceFetcher
txStoreManager: TxStoreManager
reputationManager?: ReputationManager
logger: LoggerInterface
}
export const serverDefaultConfiguration: ServerConfigParams = {
ownerAddress: constants.ZERO_ADDRESS,
alertedDelaySeconds: 0,
minAlertedDelayMS: 0,
maxAlertedDelayMS: 0,
// set to paymasters' default acceptanceBudget + RelayHub.calldataGasCost(<paymasters' default calldataSizeLimit>)
maxAcceptanceBudget:
defaultEnvironment.paymasterConfiguration.acceptanceBudget +
defaultEnvironment.dataOnChainHandlingGasCostPerByte *
defaultEnvironment.paymasterConfiguration.calldataSizeLimit,
relayHubAddress: constants.ZERO_ADDRESS,
trustedPaymasters: [],
blacklistedPaymasters: [],
gasPriceFactor: 1,
gasPriceOracleUrl: '',
gasPriceOraclePath: '',
registrationRateSeconds: 0,
workerMinBalance: 0.1e18,
workerTargetBalance: 0.3e18,
managerMinBalance: 0.1e18, // 0.1 eth
managerMinStake: '1', // 1 wei
managerStakeTokenAddress: constants.ZERO_ADDRESS,
managerTargetBalance: 0.3e18,
minHubWithdrawalBalance: 0.1e18,
checkInterval: 10000,
devMode: false,
loggingProvider: LoggingProviderMode.NONE,
runPenalizer: true,
logLevel: 'debug',
loggerUrl: '',
etherscanApiUrl: '',
etherscanApiKey: '',
loggerUserId: '',
baseRelayFee: '0',
pctRelayFee: 0,
url: 'http://localhost:8090',
ethereumNodeUrl: '',
port: 8090,
workdir: '',
refreshStateTimeoutBlocks: 5,
pendingTransactionTimeoutSeconds: 300,
confirmationsNeeded: 12,
dbAutoCompactionInterval: 604800000, // Week in ms: 1000*60*60*24*7
retryGasPriceFactor: 1.2,
defaultGasLimit: 500000,
maxGasPrice: 500e9.toString(),
defaultPriorityFee: 1e9.toString(),
requestMinValidSeconds: 43200, // roughly 12 hours, quarter of client's default of 172800 seconds (2 days)
runPaymasterReputations: true,
pastEventsQueryMaxPageSize: Number.MAX_SAFE_INTEGER,
recentActionAvoidRepeatDistanceBlocks: 10
}
const ConfigParamsTypes = {
ownerAddress: 'string',
config: 'string',
baseRelayFee: 'number',
pctRelayFee: 'number',
url: 'string',
port: 'number',
relayHubAddress: 'string',
gasPriceFactor: 'number',
gasPriceOracleUrl: 'string',
gasPriceOraclePath: 'string',
ethereumNodeUrl: 'string',
workdir: 'string',
checkInterval: 'number',
devMode: 'boolean',
loggingProvider: 'number',
logLevel: 'string',
loggerUrl: 'string',
loggerUserId: 'string',
customerToken: 'string',
hostOverride: 'string',
userId: 'string',
registrationRateSeconds: 'number',
maxAcceptanceBudget: 'number',
alertedDelaySeconds: 'number',
workerMinBalance: 'number',
workerTargetBalance: 'number',
managerMinBalance: 'number',
managerMinStake: 'string',
managerStakeTokenAddress: 'string',
managerTargetBalance: 'number',
minHubWithdrawalBalance: 'number',
withdrawToOwnerOnBalance: 'number',
defaultGasLimit: 'number',
requestMinValidSeconds: 'number',
trustedPaymasters: 'list',
blacklistedPaymasters: 'list',
runPenalizer: 'boolean',
etherscanApiUrl: 'string',
etherscanApiKey: 'string',
// TODO: does not belong here
initialReputation: 'number',
requiredVersionRange: 'string',
dbAutoCompactionInterval: 'number',
retryGasPriceFactor: 'number',
runPaymasterReputations: 'boolean',
refreshStateTimeoutBlocks: 'number',
pendingTransactionTimeoutSeconds: 'number',
minAlertedDelayMS: 'number',
maxAlertedDelayMS: 'number',
maxGasPrice: 'string',
defaultPriorityFee: 'string',
coldRestartLogsFromBlock: 'number',
pastEventsQueryMaxPageSize: 'number',
confirmationsNeeded: 'number',
environmentName: 'string',
recentActionAvoidRepeatDistanceBlocks: 'number'
} as any
// helper function: throw and never return..
function error (err: string): never {
throw new Error(err)
}
// get the keys matching specific type from ConfigParamsType
export function filterType (config: any, type: string): any {
return Object.entries(config).flatMap(e => e[1] === type ? [e[0]] : [])
}
// convert [key,val] array (created by Object.entries) back to an object.
export function entriesToObj (entries: any[]): any {
return entries
.reduce((set: any, [k, v]) => ({ ...set, [k]: v }), {})
}
// filter and return from env only members that appear in "config"
export function filterMembers (env: any, config: any): any {
return entriesToObj(Object.entries(env)
.filter(e => config[e[0]] != null))
}
// map value from string into its explicit type (number, boolean)
// TODO; maybe we can use it for more specific types, such as "address"..
function explicitType ([key, val]: [string, any]): any {
const type = ConfigParamsTypes[key] as string
if (type === undefined) {
error(`unexpected param ${key}=${val as string}`)
}
switch (type) {
case 'boolean' :
if (val === 'true' || val === true) return [key, true]
if (val === 'false' || val === false) return [key, false]
break
case 'number': {
const v = parseFloat(val)
if (!isNaN(v)) {
return [key, v]
}
break
}
default:
return [key, val]
}
error(`Invalid ${type}: ${key} = ${val as string}`)
}
/**
* initialize each parameter from commandline, env or config file (in that order)
* config file must be provided either as command-line or env (obviously, not in
* the config file..)
*/
export function parseServerConfig (args: string[], env: any): any {
const envDefaults = filterMembers(env, ConfigParamsTypes)
const argv = parseArgs(args, {
string: filterType(ConfigParamsTypes, 'string'),
// boolean: filterType(ConfigParamsTypes, 'boolean'),
default: envDefaults
})
if (argv._.length > 0) {
error(`unexpected param(s) ${argv._.join(',')}`)
}
// @ts-ignore
delete argv._
let configFile = {}
const configFileName = argv.config as string
console.log('Using config file', configFileName)
if (configFileName != null) {
if (!fs.existsSync(configFileName)) {
error(`unable to read config file "${configFileName}"`)
}
configFile = JSON.parse(fs.readFileSync(configFileName, 'utf8'))
console.log('Initial configuration:', configFile)
}
const config = { ...configFile, ...argv }
return entriesToObj(Object.entries(config).map(explicitType))
}
// resolve params, and validate the resulting struct
export async function resolveServerConfig (config: Partial<ServerConfigParams>, web3provider: any): Promise<{
config: ServerConfigParams
environment: Environment
}> {
let environment: Environment
if (config.environmentName != null) {
environment = environments[config.environmentName as EnvironmentsKeys]
if (environment == null) {
throw new Error(`Unknown named environment: ${config.environmentName}`)
}
} else {
environment = defaultEnvironment
console.error(`Must provide one of the supported values for environmentName: ${Object.keys(EnvironmentsKeys).toString()}`)
}
// TODO: avoid functions that are not parts of objects! Refactor this so there is a configured logger before we start blockchain interactions.
const logger = createServerLogger(config.logLevel ?? 'debug', config.loggerUrl ?? '', config.loggerUserId ?? '')
const contractInteractor: ContractInteractor = new ContractInteractor({
maxPageSize: config.pastEventsQueryMaxPageSize ?? Number.MAX_SAFE_INTEGER,
provider: web3provider,
logger,
deployment: {
relayHubAddress: config.relayHubAddress
},
environment
})
await contractInteractor._resolveDeployment()
await contractInteractor._initializeContracts()
await contractInteractor._initializeNetworkParams()
if (config.relayHubAddress == null) {
error('missing param: must have relayHubAddress')
}
if (config.coldRestartLogsFromBlock == null) {
const block = await contractInteractor.getCreationBlockFromRelayHub()
config.coldRestartLogsFromBlock = block.toNumber()
}
if (config.url == null) error('missing param: url')
if (config.workdir == null) error('missing param: workdir')
if (config.ownerAddress == null || config.ownerAddress === constants.ZERO_ADDRESS) error('missing param: ownerAddress')
if (config.managerStakeTokenAddress == null || config.managerStakeTokenAddress === constants.ZERO_ADDRESS) error('missing param: managerStakeTokenAddress')
const finalConfig = { ...serverDefaultConfiguration, ...config }
validateBalanceParams(finalConfig)
return {
config: finalConfig,
environment
}
}
export function validateBalanceParams (config: ServerConfigParams): void {
const workerTargetBalance = toBN(config.workerTargetBalance)
const managerTargetBalance = toBN(config.managerTargetBalance)
const managerMinBalance = toBN(config.managerMinBalance)
const workerMinBalance = toBN(config.workerMinBalance)
const minHubWithdrawalBalance = toBN(config.minHubWithdrawalBalance)
if (managerTargetBalance.lt(managerMinBalance)) {
throw new Error('managerTargetBalance must be at least managerMinBalance')
}
if (workerTargetBalance.lt(workerMinBalance)) {
throw new Error('workerTargetBalance must be at least workerMinBalance')
}
if (config.withdrawToOwnerOnBalance == null) {
return
}
const withdrawToOwnerOnBalance = toBN(config.withdrawToOwnerOnBalance)
if (minHubWithdrawalBalance.gt(withdrawToOwnerOnBalance)) {
throw new Error('withdrawToOwnerOnBalance must be at least minHubWithdrawalBalance')
}
if (managerTargetBalance.add(workerTargetBalance).gte(withdrawToOwnerOnBalance)) {
throw new Error('withdrawToOwnerOnBalance must be larger than managerTargetBalance + workerTargetBalance')
}
}
export function resolveReputationManagerConfig (config: any): Partial<ReputationManagerConfiguration> {
if (config.configFileName != null) {
if (!fs.existsSync(config.configFileName)) {
error(`unable to read config file "${config.configFileName as string}"`)
}
return JSON.parse(fs.readFileSync(config.configFileName, 'utf8'))
}
// TODO: something not insane!
return config as Partial<ReputationManagerConfiguration>
}
export function configureServer (partialConfig: Partial<ServerConfigParams>): ServerConfigParams {
return Object.assign({}, serverDefaultConfiguration, partialConfig)
} | 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 mybusinessbusinesscalls_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;
}
/**
* My Business Business Calls API
*
* The My Business Business Calls API manages business calls information of a location on Google.
*
* @example
* ```js
* const {google} = require('googleapis');
* const mybusinessbusinesscalls = google.mybusinessbusinesscalls('v1');
* ```
*/
export class Mybusinessbusinesscalls {
context: APIRequestContext;
locations: Resource$Locations;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.locations = new Resource$Locations(this.context);
}
}
/**
* Metrics aggregated over the input time range.
*/
export interface Schema$AggregateMetrics {
/**
* Total count of answered calls.
*/
answeredCallsCount?: number | null;
/**
* End date for this metric.
*/
endDate?: Schema$Date;
/**
* A list of metrics by hour of day.
*/
hourlyMetrics?: Schema$HourlyMetrics[];
/**
* Total count of missed calls.
*/
missedCallsCount?: number | null;
/**
* Date for this metric. If metric is monthly, only year and month are used.
*/
startDate?: Schema$Date;
/**
* A list of metrics by day of week.
*/
weekdayMetrics?: Schema$WeekDayMetrics[];
}
/**
* Insights for calls made to a location.
*/
export interface Schema$BusinessCallsInsights {
/**
* Metric for the time range based on start_date and end_date.
*/
aggregateMetrics?: Schema$AggregateMetrics;
/**
* The metric for which the value applies.
*/
metricType?: string | null;
/**
* Required. The resource name of the calls insights. Format: locations/{location\}/businesscallsinsights
*/
name?: string | null;
}
/**
* Business calls settings for a location.
*/
export interface Schema$BusinessCallsSettings {
/**
* Required. The state of this location's enrollment in Business calls.
*/
callsState?: string | null;
/**
* Input only. Time when the end user provided consent to the API user to enable business calls.
*/
consentTime?: string | null;
/**
* Required. The resource name of the calls settings. Format: locations/{location\}/businesscallssettings
*/
name?: string | null;
}
/**
* Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp
*/
export interface Schema$Date {
/**
* Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
*/
day?: number | null;
/**
* Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
*/
month?: number | null;
/**
* Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
*/
year?: number | null;
}
/**
* Metrics for an hour.
*/
export interface Schema$HourlyMetrics {
/**
* Hour of the day. Allowed values are 0-23.
*/
hour?: number | null;
/**
* Total count of missed calls for this hour.
*/
missedCallsCount?: number | null;
}
/**
* Response message for ListBusinessCallsInsights.
*/
export interface Schema$ListBusinessCallsInsightsResponse {
/**
* A collection of business calls insights for the location.
*/
businessCallsInsights?: Schema$BusinessCallsInsights[];
/**
* A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. Some of the metric_types (e.g, AGGREGATE_COUNT) returns a single page. For these metrics, the next_page_token will be empty.
*/
nextPageToken?: string | null;
}
/**
* Metrics for a week day.
*/
export interface Schema$WeekDayMetrics {
/**
* Day of the week. Allowed values are Sunday - Saturday.
*/
day?: string | null;
/**
* Total count of missed calls for this hour.
*/
missedCallsCount?: number | null;
}
export class Resource$Locations {
context: APIRequestContext;
businesscallsinsights: Resource$Locations$Businesscallsinsights;
constructor(context: APIRequestContext) {
this.context = context;
this.businesscallsinsights = new Resource$Locations$Businesscallsinsights(
this.context
);
}
/**
* Returns the Business calls settings resource for the given location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessbusinesscalls.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 mybusinessbusinesscalls = google.mybusinessbusinesscalls('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: [],
* });
*
* // 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 mybusinessbusinesscalls.locations.getBusinesscallssettings({
* // Required. The BusinessCallsSettings to get. The `name` field is used to identify the business call settings to get. Format: locations/{location_id\}/businesscallssettings.
* name: 'locations/my-location/businesscallssettings',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "callsState": "my_callsState",
* // "consentTime": "my_consentTime",
* // "name": "my_name"
* // }
* }
*
* 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.
*/
getBusinesscallssettings(
params: Params$Resource$Locations$Getbusinesscallssettings,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
getBusinesscallssettings(
params?: Params$Resource$Locations$Getbusinesscallssettings,
options?: MethodOptions
): GaxiosPromise<Schema$BusinessCallsSettings>;
getBusinesscallssettings(
params: Params$Resource$Locations$Getbusinesscallssettings,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
getBusinesscallssettings(
params: Params$Resource$Locations$Getbusinesscallssettings,
options:
| MethodOptions
| BodyResponseCallback<Schema$BusinessCallsSettings>,
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
getBusinesscallssettings(
params: Params$Resource$Locations$Getbusinesscallssettings,
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
getBusinesscallssettings(
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
getBusinesscallssettings(
paramsOrCallback?:
| Params$Resource$Locations$Getbusinesscallssettings
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$BusinessCallsSettings>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Getbusinesscallssettings;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Getbusinesscallssettings;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessbusinesscalls.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$BusinessCallsSettings>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$BusinessCallsSettings>(parameters);
}
}
/**
* Updates the Business call settings for the specified location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessbusinesscalls.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 mybusinessbusinesscalls = google.mybusinessbusinesscalls('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: [],
* });
*
* // 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 mybusinessbusinesscalls.locations.updateBusinesscallssettings({
* // Required. The resource name of the calls settings. Format: locations/{location\}/businesscallssettings
* name: 'locations/my-location/businesscallssettings',
* // Required. The list of fields to update.
* updateMask: 'placeholder-value',
*
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "callsState": "my_callsState",
* // "consentTime": "my_consentTime",
* // "name": "my_name"
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "callsState": "my_callsState",
* // "consentTime": "my_consentTime",
* // "name": "my_name"
* // }
* }
*
* 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.
*/
updateBusinesscallssettings(
params: Params$Resource$Locations$Updatebusinesscallssettings,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
updateBusinesscallssettings(
params?: Params$Resource$Locations$Updatebusinesscallssettings,
options?: MethodOptions
): GaxiosPromise<Schema$BusinessCallsSettings>;
updateBusinesscallssettings(
params: Params$Resource$Locations$Updatebusinesscallssettings,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
updateBusinesscallssettings(
params: Params$Resource$Locations$Updatebusinesscallssettings,
options:
| MethodOptions
| BodyResponseCallback<Schema$BusinessCallsSettings>,
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
updateBusinesscallssettings(
params: Params$Resource$Locations$Updatebusinesscallssettings,
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
updateBusinesscallssettings(
callback: BodyResponseCallback<Schema$BusinessCallsSettings>
): void;
updateBusinesscallssettings(
paramsOrCallback?:
| Params$Resource$Locations$Updatebusinesscallssettings
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$BusinessCallsSettings>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$BusinessCallsSettings>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Updatebusinesscallssettings;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Updatebusinesscallssettings;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessbusinesscalls.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'PATCH',
},
options
),
params,
requiredParams: ['name'],
pathParams: ['name'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$BusinessCallsSettings>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$BusinessCallsSettings>(parameters);
}
}
}
export interface Params$Resource$Locations$Getbusinesscallssettings
extends StandardParameters {
/**
* Required. The BusinessCallsSettings to get. The `name` field is used to identify the business call settings to get. Format: locations/{location_id\}/businesscallssettings.
*/
name?: string;
}
export interface Params$Resource$Locations$Updatebusinesscallssettings
extends StandardParameters {
/**
* Required. The resource name of the calls settings. Format: locations/{location\}/businesscallssettings
*/
name?: string;
/**
* Required. The list of fields to update.
*/
updateMask?: string;
/**
* Request body metadata
*/
requestBody?: Schema$BusinessCallsSettings;
}
export class Resource$Locations$Businesscallsinsights {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* Returns insights for Business calls for a location.
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/mybusinessbusinesscalls.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 mybusinessbusinesscalls = google.mybusinessbusinesscalls('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: [],
* });
*
* // 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 mybusinessbusinesscalls.locations.businesscallsinsights.list({
* // Optional. A filter constraining the calls insights to return. The response includes only entries that match the filter. If the MetricType is not provided, AGGREGATE_COUNT is returned. If no end_date is provided, the last date for which data is available is used. If no start_date is provided, we will default to the first date for which data is available, which is currently 6 months. If start_date is before the date when data is available, data is returned starting from the date when it is available. At this time we support following filters. 1. start_date="DATE" where date is in YYYY-MM-DD format. 2. end_date="DATE" where date is in YYYY-MM-DD format. 3. metric_type=XYZ where XYZ is a valid MetricType. 4. Conjunctions(AND) of all of the above. e.g., "start_date=2021-08-01 AND end_date=2021-08-10 AND metric_type=AGGREGATE_COUNT" The AGGREGATE_COUNT metric_type ignores the DD part of the date.
* filter: 'placeholder-value',
* // Optional. The maximum number of BusinessCallsInsights to return. If unspecified, at most 20 will be returned. Some of the metric_types(e.g, AGGREGATE_COUNT) returns a single page. For these metrics, the page_size is ignored.
* pageSize: 'placeholder-value',
* // Optional. A page token, received from a previous `ListBusinessCallsInsights` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListBusinessCallsInsights` must match the call that provided the page token. Some of the metric_types (e.g, AGGREGATE_COUNT) returns a single page. For these metrics, the pake_token is ignored.
* pageToken: 'placeholder-value',
* // Required. The parent location to fetch calls insights for. Format: locations/{location_id\}
* parent: 'locations/my-location',
* });
* console.log(res.data);
*
* // Example response
* // {
* // "businessCallsInsights": [],
* // "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.
*/
list(
params: Params$Resource$Locations$Businesscallsinsights$List,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
list(
params?: Params$Resource$Locations$Businesscallsinsights$List,
options?: MethodOptions
): GaxiosPromise<Schema$ListBusinessCallsInsightsResponse>;
list(
params: Params$Resource$Locations$Businesscallsinsights$List,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
list(
params: Params$Resource$Locations$Businesscallsinsights$List,
options:
| MethodOptions
| BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>,
callback: BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
): void;
list(
params: Params$Resource$Locations$Businesscallsinsights$List,
callback: BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
): void;
list(
callback: BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
): void;
list(
paramsOrCallback?:
| Params$Resource$Locations$Businesscallsinsights$List
| BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ListBusinessCallsInsightsResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ListBusinessCallsInsightsResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Locations$Businesscallsinsights$List;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Locations$Businesscallsinsights$List;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://mybusinessbusinesscalls.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v1/{+parent}/businesscallsinsights').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'GET',
},
options
),
params,
requiredParams: ['parent'],
pathParams: ['parent'],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ListBusinessCallsInsightsResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ListBusinessCallsInsightsResponse>(
parameters
);
}
}
}
export interface Params$Resource$Locations$Businesscallsinsights$List
extends StandardParameters {
/**
* Optional. A filter constraining the calls insights to return. The response includes only entries that match the filter. If the MetricType is not provided, AGGREGATE_COUNT is returned. If no end_date is provided, the last date for which data is available is used. If no start_date is provided, we will default to the first date for which data is available, which is currently 6 months. If start_date is before the date when data is available, data is returned starting from the date when it is available. At this time we support following filters. 1. start_date="DATE" where date is in YYYY-MM-DD format. 2. end_date="DATE" where date is in YYYY-MM-DD format. 3. metric_type=XYZ where XYZ is a valid MetricType. 4. Conjunctions(AND) of all of the above. e.g., "start_date=2021-08-01 AND end_date=2021-08-10 AND metric_type=AGGREGATE_COUNT" The AGGREGATE_COUNT metric_type ignores the DD part of the date.
*/
filter?: string;
/**
* Optional. The maximum number of BusinessCallsInsights to return. If unspecified, at most 20 will be returned. Some of the metric_types(e.g, AGGREGATE_COUNT) returns a single page. For these metrics, the page_size is ignored.
*/
pageSize?: number;
/**
* Optional. A page token, received from a previous `ListBusinessCallsInsights` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListBusinessCallsInsights` must match the call that provided the page token. Some of the metric_types (e.g, AGGREGATE_COUNT) returns a single page. For these metrics, the pake_token is ignored.
*/
pageToken?: string;
/**
* Required. The parent location to fetch calls insights for. Format: locations/{location_id\}
*/
parent?: string;
}
} | the_stack |
import * as THREE from 'three';
import { Orbit } from './Orbit';
import type { Coordinate3d } from './Coordinates';
import type { Ephem } from './Ephem';
import type { EphemerisTable } from './EphemerisTable';
import type { Simulation, SimulationContext, SimulationObject } from './Simulation';
export interface SpaceObjectOptions {
position?: Coordinate3d;
scale?: [number, number, number];
particleSize?: number;
labelText?: string;
labelUrl?: string;
hideOrbit?: boolean;
axialTilt?: number;
color?: number;
radius?: number;
levelsOfDetail?: {
radii: number;
segments: number;
}[];
atmosphere?: {
color?: number;
innerSizeRatio?: number;
outerSizeRatio?: number;
enable?: boolean;
};
orbitPathSettings?: {
leadDurationYears?: number;
trailDurationYears?: number;
numberSamplePoints?: number;
};
ephem?: Ephem;
ephemTable?: EphemerisTable;
textureUrl?: string;
basePath?: string;
rotation?: {
enable: boolean;
period: number;
speed?: number;
lambdaDeg?: number;
betaDeg?: number;
yorp?: number;
phi0?: number;
jd0?: number;
};
shape?: {
shapeUrl?: string;
color?: number;
};
ecliptic?: {
lineColor?: number;
displayLines?: boolean;
};
theme?: {
color?: number;
orbitColor?: number;
};
debug?: {
showAxes: boolean;
showGrid: boolean;
};
}
/**
* An object that can be added to a visualization.
* @example
* ```
* const myObject = viz.addObject('planet1', {
* position: [0, 0, 0],
* scale: [1, 1, 1],
* particleSize: 5,
* labelText: 'My object',
* labelUrl: 'http://...',
* hideOrbit: false,
* ephem: new Spacekit.Ephem({...}),
* textureUrl: '/path/to/spriteTexture.png',
* basePath: '/base',
* ecliptic: {
* lineColor: 0xCCCCCC,
* displayLines: false,
* },
* theme: {
* color: 0xFFFFFF,
* orbitColor: 0x888888,
* },
* });
* ```
*/
export declare class SpaceObject implements SimulationObject {
protected _id: string;
protected _options: SpaceObjectOptions;
protected _simulation: Simulation;
protected _context: SimulationContext;
protected _renderMethod?: 'SPRITE' | 'PARTICLESYSTEM' | 'ROTATING_OBJECT' | 'SPHERE';
protected _initialized: boolean;
private _object3js?;
private _useEphemTable;
private _isStaticObject;
private _label?;
private _showLabel;
private _lastLabelUpdate;
private _position;
private _orbitAround?;
private _scale;
private _particleIndex?;
private _orbitPath?;
private _eclipticLines?;
private _orbit?;
/**
* @param {String} id Unique id of this object
* @param {Object} options Options container
* @param {Array.<Number>} options.position [X, Y, Z] heliocentric coordinates of object. Defaults to [0, 0, 0]
* @param {Array.<Number>} options.scale Scale of object on each [X, Y, Z] axis. Defaults to [1, 1, 1]
* @param {Number} options.particleSize Size of particle if this object is a Kepler object being represented as a particle.
* @param {String} options.labelText Text label to display above object (set undefined for no label)
* @param {String} options.labelUrl Label becomes a link that goes to this url.
* @param {boolean} options.hideOrbit If true, don't show an orbital ellipse. Defaults false.
* @param {Object} options.orbitPathSettings Contains settings for defining the orbit path
* @param {Object} options.orbitPathSettings.leadDurationYears orbit path lead time in years
* @param {Object} options.orbitPathSettings.trailDurationYears orbit path trail time in years
* @param {Object} options.orbitPathSettings.numberSamplePoints number of
* points to use when drawing the orbit line. Only applicable for
* non-elliptical and ephemeris table orbits.
* @param {Ephem} options.ephem Ephemerides for this orbit
* @param {EphemerisTable} options.ephemTable ephemeris table object which represents look up ephemeris
* @param {String} options.textureUrl Texture for sprite
* @param {String} options.basePath Base path for simulation assets and data
* @param {Object} options.ecliptic Contains settings related to ecliptic
* @param {Number} options.ecliptic.lineColor Hex color of lines that run perpendicular to ecliptic. @see Orbit
* @param {boolean} options.ecliptic.displayLines Whether to show ecliptic lines. Defaults false.
* @param {Object} options.theme Contains settings related to appearance of orbit
* @param {Number} options.theme.color Hex color of the object, if applicable
* @param {Number} options.theme.orbitColor Hex color of the orbit
* @param {Simulation} contextOrSimulation Simulation context or simulation object
* @param {boolean} autoInit Automatically initialize this object. If false
* you must call init() manually.
*/
constructor(id: string, options: SpaceObjectOptions, simulation: Simulation, autoInit?: boolean);
/**
* Initializes label and three.js objects. Called automatically unless you've
* set autoInit to false in constructor (this init is suppressed by some
* child classes).
*/
init(): boolean;
/**
* @protected
* Used by child classes to set the object that gets its position updated.
* @param {THREE.Object3D} obj Any THREE.js object
*/
protected setPositionedObject(obj: THREE.Object3D): void;
/**
* @private
* Build the THREE.js object for this SpaceObject.
*/
private renderObject;
/**
* @private
* Builds the label div and adds it to the visualization
* @return {HTMLElement} A div that contains the label for this object
*/
private createLabel;
/**
* @private
* Updates the label's position
* @param {Array.Number} newpos Position of the label in the visualization's
* coordinate system
*/
private updateLabelPosition;
/**
* @private
* Builds the sprite for this object
* @return {THREE.Sprite} A sprite object
*/
private createSprite;
/**
* @private
* Builds the {Orbit} for this object
* @return {Orbit} An orbit object
*/
private createOrbit;
/**
* @private
* Determines whether to update the position of an update. Don't update if JD
* threshold is less than a certain amount.
* @param {Number} afterJd Next JD
* @return {boolean} Whether to update
*/
private shouldUpdateObjectPosition;
/**
* Make this object orbit another orbit.
* @param {Object} spaceObj The SpaceObject that will serve as the origin of this object's orbit.
*/
orbitAround(spaceObj: SpaceObject): void;
/**
* Updates the position of this object. Applicable only if this object is a
* sprite and not a particle type.
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} z Z position
*/
setPosition(x: number, y: number, z: number): void;
/**
* Gets the visualization coordinates of this object at a given time.
* @param {Number} jd JD date
* @return {Array.<Number>} [X, Y,Z] coordinates
*/
getPosition(jd: number): Coordinate3d;
/**
* Updates the object and its label positions for a given time.
* @param {Number} jd JD date
* @param {boolean} force Whether to force an update regardless of checks for
* movement.
*/
update(jd: number, force?: boolean): void;
/**
* Gets the THREE.js objects that represent this SpaceObject. The first
* object returned is the primary object. Other objects may be returned,
* such as rings, ellipses, etc.
* @return {Array.<THREE.Object3D>} A list of THREE.js objects
*/
get3jsObjects(): THREE.Object3D[];
/**
* Specifies the object that is used to compute the bounding box. By default,
* this will be the first THREE.js object in this class's list of objects.
* @return {THREE.Object3D} THREE.js object
*/
getBoundingObject(): Promise<THREE.Object3D>;
/**
* Gets the color of this object. Usually this corresponds to the color of
* the dot representing the object as well as its orbit.
* @return {Number} A hexidecimal color value, e.g. 0xFFFFFF
*/
getColor(): number;
/**
* Gets the {Orbit} object for this SpaceObject.
* @return {Orbit} Orbit object
*/
getOrbit(): Orbit | undefined;
/**
* Gets label visilibity status.
* @return {boolean} Whether label is visible.
*/
getLabelVisibility(): boolean;
/**
* Toggle the visilibity of the label.
* @param {boolean} val Whether to show or hide.
*/
setLabelVisibility(val: boolean): void;
/**
* Gets the unique ID of this object.
* @return {String} Unique ID
*/
getId(): string;
/**
* Determines whether object is static (can't change its position) or whether
* its position can be updated (ie, it has ephemeris)
* @return {boolean} Whether this object can change its position.
*/
isStaticObject(): boolean;
/**
* Determines whether object is ready to be measured or added to scene.
* @return {boolean} True if ready
*/
isReady(): boolean;
removalCleanup(): void;
}
/**
* Useful presets for creating SpaceObjects.
* @example
* ```
* const myobject = viz.addObject('planet1', Spacekit.SpaceObjectPresets.MERCURY);
* ```
*/
export declare const SpaceObjectPresets: {
SUN: {
textureUrl: string;
position: number[];
};
MERCURY: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
VENUS: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
EARTH: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
MOON: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
particleSize: number;
};
MARS: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
JUPITER: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
SATURN: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
URANUS: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
NEPTUNE: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
PLUTO: {
textureUrl: string;
theme: {
color: number;
};
ephem: Ephem;
};
}; | the_stack |
import {BeforeVisitorOptions} from "../before-visitor-options";
import {getExportsData} from "../../util/get-exports-data";
import {walkThroughFillerNodes} from "../../util/walk-through-filler-nodes";
import {isNamedDeclaration} from "../../util/is-named-declaration";
import {ensureNodeHasExportModifier} from "../../util/ensure-node-has-export-modifier";
import {nodeContainsSuper} from "../../util/node-contains-super";
import {addExportModifier} from "../../util/add-export-modifier";
import {isRequireCall} from "../../util/is-require-call";
import {getModuleExportsFromRequireDataInContext} from "../../util/get-module-exports-from-require-data-in-context";
import {isExpression} from "../../util/is-expression";
import {findNodeUp} from "../../util/find-node-up";
import {getLocalsForBindingName} from "../../util/get-locals-for-binding-name";
import {TS} from "../../../type/ts";
import {shouldDebug} from "../../util/should-debug";
/**
* Visits the given BinaryExpression
*/
export function visitBinaryExpression({node, sourceFile, context, continuation}: BeforeVisitorOptions<TS.BinaryExpression>): TS.VisitResult<TS.Node> {
// Check if the left-hand side contains exports. For example: 'exports = ...' or 'exports.foo = 1' or event 'module.exports = 1'
const {typescript, factory} = context;
const exportsData = getExportsData(node.left, context.exportsName, typescript);
const right = walkThroughFillerNodes(node.right, typescript);
if (exportsData == null) return node;
// If it is an assignment
if (node.operatorToken.kind === typescript.SyntaxKind.EqualsToken) {
// Check if this expression is part of a VariableDeclaration.
// For example: 'const foo = module.exports = ...'
const variableDeclarationParent = findNodeUp(node, typescript.isVariableDeclaration);
const variableDeclarationLocal =
variableDeclarationParent != null ? factory.createIdentifier(getLocalsForBindingName(variableDeclarationParent.name, typescript)[0]) : undefined;
// This is something like for example 'exports = ...', 'module.exports = ...', 'exports.default', or 'module.exports.default'
if (exportsData.property == null || exportsData.property === "default") {
// Take all individual key-value pairs of that ObjectLiteral
// and turn them into named exports if possible.
// Also generate a default export of the entire exports object
if (typescript.isObjectLiteralExpression(right)) {
// If it has no properties, or if the literal is exported as part of the right-hand side of the assignment for a VariableDeclaration, create a simple default export declaration
if (right.properties.length === 0 || variableDeclarationLocal != null) {
const continuationResult = continuation(node.right);
if (continuationResult == null || Array.isArray(continuationResult) || !isExpression(continuationResult, typescript)) {
return undefined;
}
const exportedSymbol = variableDeclarationLocal != null ? variableDeclarationLocal : continuationResult;
// Only generate the default export if the module don't already include a default export
if (!context.isDefaultExported) {
context.markDefaultAsExported();
context.addTrailingStatements(factory.createExportAssignment(undefined, undefined, false, exportedSymbol));
}
return variableDeclarationParent != null ? node.right : undefined;
}
const statements: TS.Statement[] = [];
let moduleExportsIdentifierName: string | undefined;
const elements: TS.ObjectLiteralElementLike[] = [];
for (const property of right.properties) {
const propertyName =
property.name == null
? undefined
: typescript.isLiteralExpression(property.name) || typescript.isIdentifier(property.name) || typescript.isPrivateIdentifier(property.name)
? property.name.text
: typescript.isLiteralExpression(property.name.expression)
? property.name.expression.text
: undefined;
// If no property name could be decided, or if the local is already exported, or if it is a setter, skip this property
if (propertyName == null || typescript.isSetAccessorDeclaration(property) || typescript.isGetAccessorDeclaration(property) || context.isLocalExported(propertyName)) {
elements.push(property);
continue;
}
// If it is a Shorthand Property assignment, we know that it holds a reference to some root-level identifier.
// Based on this knowledge, we can safely generate a proper ExportDeclaration for it
if (typescript.isShorthandPropertyAssignment(property)) {
context.markLocalAsExported(propertyName);
elements.push(factory.createShorthandPropertyAssignment(propertyName, property.objectAssignmentInitializer));
const namedExports = factory.createNamedExports([factory.createExportSpecifier(undefined, propertyName)]);
statements.push(factory.createExportDeclaration(undefined, undefined, false, namedExports, undefined));
}
// If it is a PropertyAssignment that points to an Identifier, we know that it holds a reference to some root-level identifier.
// Based on this knowledge, we can safely generate a proper ExportDeclaration for it
else if (typescript.isPropertyAssignment(property) && typescript.isIdentifier(property.initializer)) {
context.markLocalAsExported(propertyName);
elements.push(factory.createPropertyAssignment(propertyName, factory.createIdentifier(property.initializer.text)));
const namedExports = factory.createNamedExports([
propertyName === property.initializer.text
? factory.createExportSpecifier(undefined, propertyName)
: factory.createExportSpecifier(property.initializer.text, propertyName)
]);
statements.push(factory.createExportDeclaration(undefined, undefined, false, namedExports, undefined));
} else if (context.isIdentifierFree(propertyName) && typescript.isPropertyAssignment(property) && !nodeContainsSuper(property.initializer, typescript)) {
context.addLocal(propertyName);
elements.push(factory.createShorthandPropertyAssignment(propertyName));
statements.push(
factory.createVariableStatement(
[factory.createModifier(typescript.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList([factory.createVariableDeclaration(propertyName, undefined, undefined, property.initializer)], typescript.NodeFlags.Const)
)
);
}
// If it is a MethodDeclaration that can be safely rewritten to a function, do so
else if (
context.isIdentifierFree(propertyName) &&
typescript.isMethodDeclaration(property) &&
typescript.isIdentifier(property.name) &&
!nodeContainsSuper(property, typescript)
) {
context.addLocal(propertyName);
elements.push(factory.createShorthandPropertyAssignment(propertyName));
statements.push(
factory.createFunctionDeclaration(
property.decorators,
addExportModifier(property.modifiers, context),
property.asteriskToken,
property.name,
property.typeParameters,
property.parameters,
property.type,
property.body
)
);
}
// Otherwise, so long as the identifier of the property is free, generate a VariableStatement that exports
// the binding as a named export
else if (context.isIdentifierFree(propertyName)) {
context.addLocal(propertyName);
elements.push(property);
if (moduleExportsIdentifierName == null) {
moduleExportsIdentifierName = context.getFreeIdentifier("moduleExports");
}
context.markLocalAsExported(propertyName);
statements.push(
factory.createVariableStatement(
[factory.createModifier(typescript.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[
factory.createVariableDeclaration(
propertyName,
undefined,
undefined,
factory.createPropertyAccessExpression(factory.createIdentifier(moduleExportsIdentifierName), propertyName)
)
],
typescript.NodeFlags.Const
)
)
);
} else {
elements.push(property);
}
}
// If we need the default export the have a name such that it can be referenced in a later named export,
// create a VariableStatement as well as an ExportAssignment that references it
if (moduleExportsIdentifierName != null) {
// Create a VariableStatement that exports the ObjectLiteral
statements.push(
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(moduleExportsIdentifierName, undefined, undefined, factory.createObjectLiteralExpression(elements, true))],
typescript.NodeFlags.Const
)
)
);
if (!context.isDefaultExported) {
statements.push(factory.createExportAssignment(undefined, undefined, false, factory.createIdentifier(moduleExportsIdentifierName)));
context.markDefaultAsExported();
}
}
// Otherwise, we don't need to assign it to a VariableStatement. Instead, we can just provide the ObjectLiteralExpression to the ExportAssignment directly.
else if (!context.isDefaultExported) {
const defaultExportInitializer = factory.createObjectLiteralExpression(elements, true);
statements.push(factory.createExportAssignment(undefined, undefined, false, defaultExportInitializer));
}
// Return all of the statements
context.addTrailingStatements(...statements);
return undefined;
}
// Convert it into an ExportAssignment instead if possible
else {
// Check if the rightvalue represents a require(...) call.
const requireData = isRequireCall(node.right, sourceFile, context);
// If it doesn't, export the right side
if (!requireData.match) {
if (!context.isDefaultExported) {
context.markDefaultAsExported();
const continuationResult = continuation(node.right);
if (continuationResult == null || Array.isArray(continuationResult) || !isExpression(continuationResult, typescript)) {
return undefined;
} else {
const replacementNode = variableDeclarationParent != null ? continuationResult : undefined;
const exportedSymbol = variableDeclarationLocal != null ? variableDeclarationLocal : continuationResult;
context.addTrailingStatements(factory.createExportAssignment(undefined, undefined, false, exportedSymbol));
return replacementNode;
}
}
return undefined;
}
// Otherwise, spread out the things we know about the require call
const {moduleSpecifier} = requireData;
// If no module specifier could be determined, there's nothing we can do
if (moduleSpecifier == null) {
if (shouldDebug(context.debug)) {
throw new TypeError(`Could not handle re-export from require() call. The module specifier wasn't statically analyzable`);
} else {
return undefined;
}
}
// Otherwise, take the exports from that module
else {
const moduleExports = getModuleExportsFromRequireDataInContext(requireData, context);
const moduleSpecifierExpression = factory.createStringLiteral(moduleSpecifier);
// If the module has a default export, or if we know nothing about it,
// export the default export from that module
if (!context.isDefaultExported && (moduleExports == null || moduleExports.hasDefaultExport)) {
context.markDefaultAsExported();
const namedExports = factory.createNamedExports([factory.createExportSpecifier(undefined, "default")]);
context.addTrailingStatements(factory.createExportDeclaration(undefined, undefined, false, namedExports, moduleSpecifierExpression));
return undefined;
}
// Otherwise, export the entire module (e.g. all named exports)
else {
context.addTrailingStatements(factory.createExportDeclaration(undefined, undefined, false, undefined, moduleSpecifierExpression));
return undefined;
}
}
}
}
// If this is part of a VariableDeclaration, such as for 'const foo = exports.bar = ...', it should be translated into:
// const foo = ...;
// export {foo as bar}
else if (variableDeclarationLocal != null) {
const local = exportsData.property;
const continuationResult = continuation(node.right);
if (continuationResult == null || Array.isArray(continuationResult) || (!isExpression(continuationResult, typescript) && !typescript.isIdentifier(continuationResult))) {
return undefined;
}
const namedExports = factory.createNamedExports([
local === variableDeclarationLocal.text
? factory.createExportSpecifier(undefined, factory.createIdentifier(local))
: factory.createExportSpecifier(variableDeclarationLocal.text, factory.createIdentifier(local))
]);
context.addTrailingStatements(factory.createExportDeclaration(undefined, undefined, false, namedExports));
return continuationResult;
}
// If the right-hand side is an identifier, this can safely be converted into an ExportDeclaration
// such as 'export {foo}'
else if (typescript.isIdentifier(right)) {
const local = exportsData.property;
if (!context.isLocalExported(local)) {
const namedExports = factory.createNamedExports([
local === right.text
? factory.createExportSpecifier(undefined, factory.createIdentifier(local))
: factory.createExportSpecifier(right.text, factory.createIdentifier(local))
]);
context.markLocalAsExported(local);
context.addTrailingStatements(factory.createExportDeclaration(undefined, undefined, false, namedExports));
}
return undefined;
}
// Otherwise, this is something like 'exports.foo = function foo () {}'
else if (isNamedDeclaration(right, typescript) && right.name != null && typescript.isIdentifier(right.name) && exportsData.property === right.name.text) {
context.addTrailingStatements(ensureNodeHasExportModifier(right, context) as unknown as TS.Statement);
return undefined;
}
// Otherwise, this can be converted into a VariableStatement
else {
const continuationResult = continuation(node.right);
if (continuationResult == null || Array.isArray(continuationResult)) {
return undefined;
}
if (!context.isLocalExported(exportsData.property)) {
context.markLocalAsExported(exportsData.property);
if (typescript.isIdentifier(continuationResult)) {
const namedExports = factory.createNamedExports([
continuationResult.text === exportsData.property
? factory.createExportSpecifier(undefined, factory.createIdentifier(exportsData.property))
: factory.createExportSpecifier(factory.createIdentifier(continuationResult.text), factory.createIdentifier(exportsData.property))
]);
context.addTrailingStatements(factory.createExportDeclaration(undefined, undefined, false, namedExports, undefined));
} else {
const freeIdentifier = context.getFreeIdentifier(exportsData.property);
// If it is free, we can simply add an export modifier in front of the expression
if (freeIdentifier === exportsData.property) {
context.addTrailingStatements(
factory.createVariableStatement(
[factory.createModifier(typescript.SyntaxKind.ExportKeyword)],
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(exportsData.property, undefined, undefined, continuationResult as TS.Expression)],
typescript.NodeFlags.Const
)
)
);
} else {
const namedExports = factory.createNamedExports([factory.createExportSpecifier(freeIdentifier, exportsData.property)]);
// If it isn't, we'll need to bind it to a variable with the free name, but then export it under the original one
context.addTrailingStatements(
factory.createVariableStatement(
undefined,
factory.createVariableDeclarationList(
[factory.createVariableDeclaration(freeIdentifier, undefined, undefined, continuationResult as TS.Expression)],
typescript.NodeFlags.Const
)
),
factory.createExportDeclaration(undefined, undefined, false, namedExports, undefined)
);
}
}
}
return undefined;
}
}
return node;
} | the_stack |
import assert from "assert";
import { Decimal, Decimalish } from "./Decimal";
import {
MINIMUM_COLLATERAL_RATIO,
CRITICAL_COLLATERAL_RATIO,
LUSD_LIQUIDATION_RESERVE,
MINIMUM_BORROWING_RATE
} from "./constants";
/** @internal */ export type _CollateralDeposit<T> = { depositCollateral: T };
/** @internal */ export type _CollateralWithdrawal<T> = { withdrawCollateral: T };
/** @internal */ export type _LUSDBorrowing<T> = { borrowLUSD: T };
/** @internal */ export type _LUSDRepayment<T> = { repayLUSD: T };
/** @internal */ export type _NoCollateralDeposit = Partial<_CollateralDeposit<undefined>>;
/** @internal */ export type _NoCollateralWithdrawal = Partial<_CollateralWithdrawal<undefined>>;
/** @internal */ export type _NoLUSDBorrowing = Partial<_LUSDBorrowing<undefined>>;
/** @internal */ export type _NoLUSDRepayment = Partial<_LUSDRepayment<undefined>>;
/** @internal */
export type _CollateralChange<T> =
| (_CollateralDeposit<T> & _NoCollateralWithdrawal)
| (_CollateralWithdrawal<T> & _NoCollateralDeposit);
/** @internal */
export type _NoCollateralChange = _NoCollateralDeposit & _NoCollateralWithdrawal;
/** @internal */
export type _DebtChange<T> =
| (_LUSDBorrowing<T> & _NoLUSDRepayment)
| (_LUSDRepayment<T> & _NoLUSDBorrowing);
/** @internal */
export type _NoDebtChange = _NoLUSDBorrowing & _NoLUSDRepayment;
/**
* Parameters of an {@link TransactableLiquity.openTrove | openTrove()} transaction.
*
* @remarks
* The type parameter `T` specifies the allowed value type(s) of the particular `TroveCreationParams`
* object's properties.
*
* <h2>Properties</h2>
*
* <table>
*
* <tr>
* <th> Property </th>
* <th> Type </th>
* <th> Description </th>
* </tr>
*
* <tr>
* <td> depositCollateral </td>
* <td> T </td>
* <td> The amount of collateral that's deposited. </td>
* </tr>
*
* <tr>
* <td> borrowLUSD </td>
* <td> T </td>
* <td> The amount of LUSD that's borrowed. </td>
* </tr>
*
* </table>
*
* @public
*/
export type TroveCreationParams<T = unknown> = _CollateralDeposit<T> &
_NoCollateralWithdrawal &
_LUSDBorrowing<T> &
_NoLUSDRepayment;
/**
* Parameters of a {@link TransactableLiquity.closeTrove | closeTrove()} transaction.
*
* @remarks
* The type parameter `T` specifies the allowed value type(s) of the particular `TroveClosureParams`
* object's properties.
*
* <h2>Properties</h2>
*
* <table>
*
* <tr>
* <th> Property </th>
* <th> Type </th>
* <th> Description </th>
* </tr>
*
* <tr>
* <td> withdrawCollateral </td>
* <td> T </td>
* <td> The amount of collateral that's withdrawn. </td>
* </tr>
*
* <tr>
* <td> repayLUSD? </td>
* <td> T </td>
* <td> <i>(Optional)</i> The amount of LUSD that's repaid. </td>
* </tr>
*
* </table>
*
* @public
*/
export type TroveClosureParams<T> = _CollateralWithdrawal<T> &
_NoCollateralDeposit &
Partial<_LUSDRepayment<T>> &
_NoLUSDBorrowing;
/**
* Parameters of an {@link TransactableLiquity.adjustTrove | adjustTrove()} transaction.
*
* @remarks
* The type parameter `T` specifies the allowed value type(s) of the particular
* `TroveAdjustmentParams` object's properties.
*
* Even though all properties are optional, a valid `TroveAdjustmentParams` object must define at
* least one.
*
* Defining both `depositCollateral` and `withdrawCollateral`, or both `borrowLUSD` and `repayLUSD`
* at the same time is disallowed, and will result in a type-checking error.
*
* <h2>Properties</h2>
*
* <table>
*
* <tr>
* <th> Property </th>
* <th> Type </th>
* <th> Description </th>
* </tr>
*
* <tr>
* <td> depositCollateral? </td>
* <td> T </td>
* <td> <i>(Optional)</i> The amount of collateral that's deposited. </td>
* </tr>
*
* <tr>
* <td> withdrawCollateral? </td>
* <td> T </td>
* <td> <i>(Optional)</i> The amount of collateral that's withdrawn. </td>
* </tr>
*
* <tr>
* <td> borrowLUSD? </td>
* <td> T </td>
* <td> <i>(Optional)</i> The amount of LUSD that's borrowed. </td>
* </tr>
*
* <tr>
* <td> repayLUSD? </td>
* <td> T </td>
* <td> <i>(Optional)</i> The amount of LUSD that's repaid. </td>
* </tr>
*
* </table>
*
* @public
*/
export type TroveAdjustmentParams<T = unknown> =
| (_CollateralChange<T> & _NoDebtChange)
| (_DebtChange<T> & _NoCollateralChange)
| (_CollateralChange<T> & _DebtChange<T>);
/**
* Describes why a Trove could not be created.
*
* @remarks
* See {@link TroveChange}.
*
* <h2>Possible values</h2>
*
* <table>
*
* <tr>
* <th> Value </th>
* <th> Reason </th>
* </tr>
*
* <tr>
* <td> "missingLiquidationReserve" </td>
* <td> A Trove's debt cannot be less than the liquidation reserve. </td>
* </tr>
*
* </table>
*
* More errors may be added in the future.
*
* @public
*/
export type TroveCreationError = "missingLiquidationReserve";
/**
* Represents the change between two Trove states.
*
* @remarks
* Returned by {@link Trove.whatChanged}.
*
* Passed as a parameter to {@link Trove.apply}.
*
* @public
*/
export type TroveChange<T> =
| { type: "invalidCreation"; invalidTrove: Trove; error: TroveCreationError }
| { type: "creation"; params: TroveCreationParams<T> }
| { type: "closure"; params: TroveClosureParams<T> }
| { type: "adjustment"; params: TroveAdjustmentParams<T>; setToZero?: "collateral" | "debt" };
// This might seem backwards, but this way we avoid spamming the .d.ts and generated docs
type InvalidTroveCreation = Extract<TroveChange<never>, { type: "invalidCreation" }>;
type TroveCreation<T> = Extract<TroveChange<T>, { type: "creation" }>;
type TroveClosure<T> = Extract<TroveChange<T>, { type: "closure" }>;
type TroveAdjustment<T> = Extract<TroveChange<T>, { type: "adjustment" }>;
const invalidTroveCreation = (
invalidTrove: Trove,
error: TroveCreationError
): InvalidTroveCreation => ({
type: "invalidCreation",
invalidTrove,
error
});
const troveCreation = <T>(params: TroveCreationParams<T>): TroveCreation<T> => ({
type: "creation",
params
});
const troveClosure = <T>(params: TroveClosureParams<T>): TroveClosure<T> => ({
type: "closure",
params
});
const troveAdjustment = <T>(
params: TroveAdjustmentParams<T>,
setToZero?: "collateral" | "debt"
): TroveAdjustment<T> => ({
type: "adjustment",
params,
setToZero
});
const valueIsDefined = <T>(entry: [string, T | undefined]): entry is [string, T] =>
entry[1] !== undefined;
type AllowedKey<T> = Exclude<
{
[P in keyof T]: T[P] extends undefined ? never : P;
}[keyof T],
undefined
>;
const allowedTroveCreationKeys: AllowedKey<TroveCreationParams>[] = [
"depositCollateral",
"borrowLUSD"
];
function checkAllowedTroveCreationKeys<T>(
entries: [string, T][]
): asserts entries is [AllowedKey<TroveCreationParams>, T][] {
const badKeys = entries
.filter(([k]) => !(allowedTroveCreationKeys as string[]).includes(k))
.map(([k]) => `'${k}'`);
if (badKeys.length > 0) {
throw new Error(`TroveCreationParams: property ${badKeys.join(", ")} not allowed`);
}
}
const troveCreationParamsFromEntries = <T>(
entries: [AllowedKey<TroveCreationParams>, T][]
): TroveCreationParams<T> => {
const params = Object.fromEntries(entries) as Record<AllowedKey<TroveCreationParams>, T>;
const missingKeys = allowedTroveCreationKeys.filter(k => !(k in params)).map(k => `'${k}'`);
if (missingKeys.length > 0) {
throw new Error(`TroveCreationParams: property ${missingKeys.join(", ")} missing`);
}
return params;
};
const decimalize = <T>([k, v]: [T, Decimalish]): [T, Decimal] => [k, Decimal.from(v)];
const nonZero = <T>([, v]: [T, Decimal]): boolean => !v.isZero;
/** @internal */
export const _normalizeTroveCreation = (
params: Record<string, Decimalish | undefined>
): TroveCreationParams<Decimal> => {
const definedEntries = Object.entries(params).filter(valueIsDefined);
checkAllowedTroveCreationKeys(definedEntries);
const nonZeroEntries = definedEntries.map(decimalize);
return troveCreationParamsFromEntries(nonZeroEntries);
};
const allowedTroveAdjustmentKeys: AllowedKey<TroveAdjustmentParams>[] = [
"depositCollateral",
"withdrawCollateral",
"borrowLUSD",
"repayLUSD"
];
function checkAllowedTroveAdjustmentKeys<T>(
entries: [string, T][]
): asserts entries is [AllowedKey<TroveAdjustmentParams>, T][] {
const badKeys = entries
.filter(([k]) => !(allowedTroveAdjustmentKeys as string[]).includes(k))
.map(([k]) => `'${k}'`);
if (badKeys.length > 0) {
throw new Error(`TroveAdjustmentParams: property ${badKeys.join(", ")} not allowed`);
}
}
const collateralChangeFrom = <T>({
depositCollateral,
withdrawCollateral
}: Partial<Record<AllowedKey<TroveAdjustmentParams>, T>>): _CollateralChange<T> | undefined => {
if (depositCollateral !== undefined && withdrawCollateral !== undefined) {
throw new Error(
"TroveAdjustmentParams: 'depositCollateral' and 'withdrawCollateral' " +
"can't be present at the same time"
);
}
if (depositCollateral !== undefined) {
return { depositCollateral };
}
if (withdrawCollateral !== undefined) {
return { withdrawCollateral };
}
};
const debtChangeFrom = <T>({
borrowLUSD,
repayLUSD
}: Partial<Record<AllowedKey<TroveAdjustmentParams>, T>>): _DebtChange<T> | undefined => {
if (borrowLUSD !== undefined && repayLUSD !== undefined) {
throw new Error(
"TroveAdjustmentParams: 'borrowLUSD' and 'repayLUSD' can't be present at the same time"
);
}
if (borrowLUSD !== undefined) {
return { borrowLUSD };
}
if (repayLUSD !== undefined) {
return { repayLUSD };
}
};
const troveAdjustmentParamsFromEntries = <T>(
entries: [AllowedKey<TroveAdjustmentParams>, T][]
): TroveAdjustmentParams<T> => {
const params = Object.fromEntries(entries) as Partial<
Record<AllowedKey<TroveAdjustmentParams>, T>
>;
const collateralChange = collateralChangeFrom(params);
const debtChange = debtChangeFrom(params);
if (collateralChange !== undefined && debtChange !== undefined) {
return { ...collateralChange, ...debtChange };
}
if (collateralChange !== undefined) {
return collateralChange;
}
if (debtChange !== undefined) {
return debtChange;
}
throw new Error("TroveAdjustmentParams: must include at least one non-zero parameter");
};
/** @internal */
export const _normalizeTroveAdjustment = (
params: Record<string, Decimalish | undefined>
): TroveAdjustmentParams<Decimal> => {
const definedEntries = Object.entries(params).filter(valueIsDefined);
checkAllowedTroveAdjustmentKeys(definedEntries);
const nonZeroEntries = definedEntries.map(decimalize).filter(nonZero);
return troveAdjustmentParamsFromEntries(nonZeroEntries);
};
const applyFee = (borrowingRate: Decimalish, debtIncrease: Decimal) =>
debtIncrease.mul(Decimal.ONE.add(borrowingRate));
const unapplyFee = (borrowingRate: Decimalish, debtIncrease: Decimal) =>
debtIncrease._divCeil(Decimal.ONE.add(borrowingRate));
const NOMINAL_COLLATERAL_RATIO_PRECISION = Decimal.from(100);
/**
* A combination of collateral and debt.
*
* @public
*/
export class Trove {
/** Amount of native currency (e.g. Ether) collateralized. */
readonly collateral: Decimal;
/** Amount of LUSD owed. */
readonly debt: Decimal;
/** @internal */
constructor(collateral = Decimal.ZERO, debt = Decimal.ZERO) {
this.collateral = collateral;
this.debt = debt;
}
get isEmpty(): boolean {
return this.collateral.isZero && this.debt.isZero;
}
/**
* Amount of LUSD that must be repaid to close this Trove.
*
* @remarks
* This doesn't include the liquidation reserve, which is refunded in case of normal closure.
*/
get netDebt(): Decimal {
if (this.debt.lt(LUSD_LIQUIDATION_RESERVE)) {
throw new Error(`netDebt should not be used when debt < ${LUSD_LIQUIDATION_RESERVE}`);
}
return this.debt.sub(LUSD_LIQUIDATION_RESERVE);
}
/** @internal */
get _nominalCollateralRatio(): Decimal {
return this.collateral.mulDiv(NOMINAL_COLLATERAL_RATIO_PRECISION, this.debt);
}
/** Calculate the Trove's collateralization ratio at a given price. */
collateralRatio(price: Decimalish): Decimal {
return this.collateral.mulDiv(price, this.debt);
}
/**
* Whether the Trove is undercollateralized at a given price.
*
* @returns
* `true` if the Trove's collateralization ratio is less than the
* {@link MINIMUM_COLLATERAL_RATIO}.
*/
collateralRatioIsBelowMinimum(price: Decimalish): boolean {
return this.collateralRatio(price).lt(MINIMUM_COLLATERAL_RATIO);
}
/**
* Whether the collateralization ratio is less than the {@link CRITICAL_COLLATERAL_RATIO} at a
* given price.
*
* @example
* Can be used to check whether the Liquity protocol is in recovery mode by using it on the return
* value of {@link ReadableLiquity.getTotal | getTotal()}. For example:
*
* ```typescript
* const total = await liquity.getTotal();
* const price = await liquity.getPrice();
*
* if (total.collateralRatioIsBelowCritical(price)) {
* // Recovery mode is active
* }
* ```
*/
collateralRatioIsBelowCritical(price: Decimalish): boolean {
return this.collateralRatio(price).lt(CRITICAL_COLLATERAL_RATIO);
}
/** Whether the Trove is sufficiently collateralized to be opened during recovery mode. */
isOpenableInRecoveryMode(price: Decimalish): boolean {
return this.collateralRatio(price).gte(CRITICAL_COLLATERAL_RATIO);
}
/** @internal */
toString(): string {
return `{ collateral: ${this.collateral}, debt: ${this.debt} }`;
}
equals(that: Trove): boolean {
return this.collateral.eq(that.collateral) && this.debt.eq(that.debt);
}
add(that: Trove): Trove {
return new Trove(this.collateral.add(that.collateral), this.debt.add(that.debt));
}
addCollateral(collateral: Decimalish): Trove {
return new Trove(this.collateral.add(collateral), this.debt);
}
addDebt(debt: Decimalish): Trove {
return new Trove(this.collateral, this.debt.add(debt));
}
subtract(that: Trove): Trove {
const { collateral, debt } = that;
return new Trove(
this.collateral.gt(collateral) ? this.collateral.sub(collateral) : Decimal.ZERO,
this.debt.gt(debt) ? this.debt.sub(debt) : Decimal.ZERO
);
}
subtractCollateral(collateral: Decimalish): Trove {
return new Trove(
this.collateral.gt(collateral) ? this.collateral.sub(collateral) : Decimal.ZERO,
this.debt
);
}
subtractDebt(debt: Decimalish): Trove {
return new Trove(this.collateral, this.debt.gt(debt) ? this.debt.sub(debt) : Decimal.ZERO);
}
multiply(multiplier: Decimalish): Trove {
return new Trove(this.collateral.mul(multiplier), this.debt.mul(multiplier));
}
setCollateral(collateral: Decimalish): Trove {
return new Trove(Decimal.from(collateral), this.debt);
}
setDebt(debt: Decimalish): Trove {
return new Trove(this.collateral, Decimal.from(debt));
}
private _debtChange({ debt }: Trove, borrowingRate: Decimalish): _DebtChange<Decimal> {
return debt.gt(this.debt)
? { borrowLUSD: unapplyFee(borrowingRate, debt.sub(this.debt)) }
: { repayLUSD: this.debt.sub(debt) };
}
private _collateralChange({ collateral }: Trove): _CollateralChange<Decimal> {
return collateral.gt(this.collateral)
? { depositCollateral: collateral.sub(this.collateral) }
: { withdrawCollateral: this.collateral.sub(collateral) };
}
/**
* Calculate the difference between this Trove and another.
*
* @param that - The other Trove.
* @param borrowingRate - Borrowing rate to use when calculating a borrowed amount.
*
* @returns
* An object representing the change, or `undefined` if the Troves are equal.
*/
whatChanged(
that: Trove,
borrowingRate: Decimalish = MINIMUM_BORROWING_RATE
): TroveChange<Decimal> | undefined {
if (this.collateral.eq(that.collateral) && this.debt.eq(that.debt)) {
return undefined;
}
if (this.isEmpty) {
if (that.debt.lt(LUSD_LIQUIDATION_RESERVE)) {
return invalidTroveCreation(that, "missingLiquidationReserve");
}
return troveCreation({
depositCollateral: that.collateral,
borrowLUSD: unapplyFee(borrowingRate, that.netDebt)
});
}
if (that.isEmpty) {
return troveClosure(
this.netDebt.nonZero
? { withdrawCollateral: this.collateral, repayLUSD: this.netDebt }
: { withdrawCollateral: this.collateral }
);
}
return this.collateral.eq(that.collateral)
? troveAdjustment<Decimal>(this._debtChange(that, borrowingRate), that.debt.zero && "debt")
: this.debt.eq(that.debt)
? troveAdjustment<Decimal>(this._collateralChange(that), that.collateral.zero && "collateral")
: troveAdjustment<Decimal>(
{
...this._debtChange(that, borrowingRate),
...this._collateralChange(that)
},
(that.debt.zero && "debt") ?? (that.collateral.zero && "collateral")
);
}
/**
* Make a new Trove by applying a {@link TroveChange} to this Trove.
*
* @param change - The change to apply.
* @param borrowingRate - Borrowing rate to use when adding a borrowed amount to the Trove's debt.
*/
apply(
change: TroveChange<Decimal> | undefined,
borrowingRate: Decimalish = MINIMUM_BORROWING_RATE
): Trove {
if (!change) {
return this;
}
switch (change.type) {
case "invalidCreation":
if (!this.isEmpty) {
throw new Error("Can't create onto existing Trove");
}
return change.invalidTrove;
case "creation": {
if (!this.isEmpty) {
throw new Error("Can't create onto existing Trove");
}
const { depositCollateral, borrowLUSD } = change.params;
return new Trove(
depositCollateral,
LUSD_LIQUIDATION_RESERVE.add(applyFee(borrowingRate, borrowLUSD))
);
}
case "closure":
if (this.isEmpty) {
throw new Error("Can't close empty Trove");
}
return _emptyTrove;
case "adjustment": {
const {
setToZero,
params: { depositCollateral, withdrawCollateral, borrowLUSD, repayLUSD }
} = change;
const collateralDecrease = withdrawCollateral ?? Decimal.ZERO;
const collateralIncrease = depositCollateral ?? Decimal.ZERO;
const debtDecrease = repayLUSD ?? Decimal.ZERO;
const debtIncrease = borrowLUSD ? applyFee(borrowingRate, borrowLUSD) : Decimal.ZERO;
return setToZero === "collateral"
? this.setCollateral(Decimal.ZERO).addDebt(debtIncrease).subtractDebt(debtDecrease)
: setToZero === "debt"
? this.setDebt(Decimal.ZERO)
.addCollateral(collateralIncrease)
.subtractCollateral(collateralDecrease)
: this.add(new Trove(collateralIncrease, debtIncrease)).subtract(
new Trove(collateralDecrease, debtDecrease)
);
}
}
}
/**
* Calculate the result of an {@link TransactableLiquity.openTrove | openTrove()} transaction.
*
* @param params - Parameters of the transaction.
* @param borrowingRate - Borrowing rate to use when calculating the Trove's debt.
*/
static create(params: TroveCreationParams<Decimalish>, borrowingRate?: Decimalish): Trove {
return _emptyTrove.apply(troveCreation(_normalizeTroveCreation(params)), borrowingRate);
}
/**
* Calculate the parameters of an {@link TransactableLiquity.openTrove | openTrove()} transaction
* that will result in the given Trove.
*
* @param that - The Trove to recreate.
* @param borrowingRate - Current borrowing rate.
*/
static recreate(that: Trove, borrowingRate?: Decimalish): TroveCreationParams<Decimal> {
const change = _emptyTrove.whatChanged(that, borrowingRate);
assert(change?.type === "creation");
return change.params;
}
/**
* Calculate the result of an {@link TransactableLiquity.adjustTrove | adjustTrove()} transaction
* on this Trove.
*
* @param params - Parameters of the transaction.
* @param borrowingRate - Borrowing rate to use when adding to the Trove's debt.
*/
adjust(params: TroveAdjustmentParams<Decimalish>, borrowingRate?: Decimalish): Trove {
return this.apply(troveAdjustment(_normalizeTroveAdjustment(params)), borrowingRate);
}
/**
* Calculate the parameters of an {@link TransactableLiquity.adjustTrove | adjustTrove()}
* transaction that will change this Trove into the given Trove.
*
* @param that - The desired result of the transaction.
* @param borrowingRate - Current borrowing rate.
*/
adjustTo(that: Trove, borrowingRate?: Decimalish): TroveAdjustmentParams<Decimal> {
const change = this.whatChanged(that, borrowingRate);
assert(change?.type === "adjustment");
return change.params;
}
}
/** @internal */
export const _emptyTrove = new Trove();
/**
* Represents whether a UserTrove is open or not, or why it was closed.
*
* @public
*/
export type UserTroveStatus =
| "nonExistent"
| "open"
| "closedByOwner"
| "closedByLiquidation"
| "closedByRedemption";
/**
* A Trove that is associated with a single owner.
*
* @remarks
* The SDK uses the base {@link Trove} class as a generic container of collateral and debt, for
* example to represent the {@link ReadableLiquity.getTotal | total collateral and debt} locked up
* in the protocol.
*
* The `UserTrove` class extends `Trove` with extra information that's only available for Troves
* that are associated with a single owner (such as the owner's address, or the Trove's status).
*
* @public
*/
export class UserTrove extends Trove {
/** Address that owns this Trove. */
readonly ownerAddress: string;
/** Provides more information when the UserTrove is empty. */
readonly status: UserTroveStatus;
/** @internal */
constructor(ownerAddress: string, status: UserTroveStatus, collateral?: Decimal, debt?: Decimal) {
super(collateral, debt);
this.ownerAddress = ownerAddress;
this.status = status;
}
equals(that: UserTrove): boolean {
return (
super.equals(that) && this.ownerAddress === that.ownerAddress && this.status === that.status
);
}
/** @internal */
toString(): string {
return (
`{ ownerAddress: "${this.ownerAddress}"` +
`, collateral: ${this.collateral}` +
`, debt: ${this.debt}` +
`, status: "${this.status}" }`
);
}
}
/**
* A Trove in its state after the last direct modification.
*
* @remarks
* The Trove may have received collateral and debt shares from liquidations since then.
* Use {@link TroveWithPendingRedistribution.applyRedistribution | applyRedistribution()} to
* calculate the Trove's most up-to-date state.
*
* @public
*/
export class TroveWithPendingRedistribution extends UserTrove {
private readonly stake: Decimal;
private readonly snapshotOfTotalRedistributed: Trove;
/** @internal */
constructor(
ownerAddress: string,
status: UserTroveStatus,
collateral?: Decimal,
debt?: Decimal,
stake = Decimal.ZERO,
snapshotOfTotalRedistributed = _emptyTrove
) {
super(ownerAddress, status, collateral, debt);
this.stake = stake;
this.snapshotOfTotalRedistributed = snapshotOfTotalRedistributed;
}
applyRedistribution(totalRedistributed: Trove): UserTrove {
const afterRedistribution = this.add(
totalRedistributed.subtract(this.snapshotOfTotalRedistributed).multiply(this.stake)
);
return new UserTrove(
this.ownerAddress,
this.status,
afterRedistribution.collateral,
afterRedistribution.debt
);
}
equals(that: TroveWithPendingRedistribution): boolean {
return (
super.equals(that) &&
this.stake.eq(that.stake) &&
this.snapshotOfTotalRedistributed.equals(that.snapshotOfTotalRedistributed)
);
}
} | the_stack |
import { SignedTransaction } from './SignedTransaction'
import { SignedTransactionWithProof } from './SignedTransactionWithProof'
import { SumMerkleTreeNode, SumMerkleProof, SumMerkleTree } from './merkle'
import { Segment } from './segment'
import { constants, utils } from 'ethers'
import HashZero = constants.HashZero
import BigNumber = utils.BigNumber
import { TOTAL_AMOUNT } from './helpers/constants'
import { Hash, Address } from './helpers/types'
import { MapUtil } from './utils/MapUtil'
import { SegmentedBlock } from './models/SegmentedBlock'
import { ExclusionProof } from './models/ExclusionProof'
import { StateUpdate } from './StateUpdate'
import { PredicatesManager } from './predicates'
import { SegmentNode } from './models'
/**
* @title Block
* @description Plasma Block
* If we have 40bit for amount, we need 40 depth tree and 2^40 prime numbers.
* 2^40 is 1.0995116e+12
* ETH: 1 in plasma is 1 microether
* Plasma's capacity is 1098756 ether
* ETH: 1 in plasma is 1 gwei
* Plasma's capacity is 1098 ether
*
* If we have 48bit for amount, we need 48 depth tree and 2^49 prime numbers.
* 2^48 is 2.8147498e+14(260000000000000)
* ETH: 1 in plasma is 1 gwei
* Plasma's capacity is 260000 ether
* ETH: 1 in plasma is 10 gwei
* Plasma's capacity is 2600000 ether
*
* When there are not enough prime numbers, operator don't receive split tx and do merge.
*/
export class Block {
public static deserialize(data: any): Block {
const block = new Block(data.numTokens)
block.setBlockNumber(data.number)
block.setBlockTimestamp(utils.bigNumberify(data.timestamp))
block.setSuperRoot(data.superRoot)
if (data.depositTx !== null) {
block.setDepositTx(StateUpdate.deserialize(data.depositTx))
}
data.txs.forEach((tx: any) => {
block.appendTx(SignedTransaction.deserialize(tx))
})
block.confSigMap = MapUtil.deserialize<string[]>(data.confSigs)
return block
}
public number: number
public superRoot: string | null
public timestamp: BigNumber
public isDepositBlock: boolean
public txs: SignedTransaction[]
public depositTx?: StateUpdate
public tree: SumMerkleTree | null
public numTokens: number
public confSigMap: Map<string, string[]>
constructor(numTokens?: number) {
this.number = 0
this.superRoot = null
this.timestamp = constants.Zero
this.isDepositBlock = false
this.txs = []
this.tree = null
this.numTokens = numTokens || 1
this.confSigMap = new Map<string, string[]>()
}
public checkSuperRoot() {
return utils.keccak256(
utils.concat([
utils.arrayify(this.getRoot()),
utils.padZeros(utils.arrayify(this.timestamp), 8)
])
)
}
public verifySuperRoot() {
if (this.superRoot != null) {
return this.checkSuperRoot() === this.superRoot
} else {
throw new Error("superRoot doesn't setted")
}
}
public setSuperRoot(superRoot: string) {
this.superRoot = superRoot
}
public setBlockNumber(blockNumber: number) {
this.number = blockNumber
}
public setBlockTimestamp(bn: BigNumber) {
this.timestamp = bn
}
public setDepositTx(depositTx: StateUpdate) {
this.depositTx = depositTx
this.isDepositBlock = true
}
public appendTx(tx: SignedTransaction) {
this.txs.push(tx)
}
public appendConfSig(tx: SignedTransaction, confSig: string) {
const hash = tx.hash()
const confSigs = this.confSigMap.get(hash)
if (confSigs && confSigs.indexOf(confSig) < 0) {
confSigs.push(confSig)
this.confSigMap.set(hash, confSigs)
}
}
public serialize() {
return {
number: this.number,
isDepositBlock: this.isDepositBlock,
depositTx: this.depositTx ? this.depositTx.serialize() : null,
txs: this.txs.map(tx => tx.serialize()),
root: this.txs.length > 0 ? this.getRoot() : null,
numTokens: this.numTokens,
superRoot: this.superRoot,
timestamp: this.timestamp.toString(),
confSigs: MapUtil.serialize<string[]>(this.confSigMap)
}
}
public getBlockNumber() {
return this.number
}
public getRoot(): Hash {
if (this.tree === null) {
this.tree = this.createTree()
}
return utils.hexlify(this.tree.root())
}
public getProof(hash: string): SumMerkleProof[] {
if (this.tree === null) {
this.tree = this.createTree()
}
return this.tree.proofs(this.numTokens, Buffer.from(hash.substr(2), 'hex'))
}
public getSignedTransaction(hash: string): SignedTransaction {
return this.txs.filter(tx => tx.hash() === hash)[0]
}
public getSignedTransactionWithProof(hash: string) {
if (this.superRoot != null) {
const superRoot: string = this.superRoot
const signedTx = this.getSignedTransaction(hash)
const proofs = this.getProof(hash)
return proofs
.map((p, i) => {
const index = signedTx.getIndex(p.segment)
return new SignedTransactionWithProof(
signedTx,
index.txIndex,
superRoot,
this.getRoot(),
this.timestamp,
proofs,
utils.bigNumberify(this.number)
)
})
.map(tx => {
return tx
})
} else {
throw new Error("superRoot doesn't setted")
}
}
public getSegmentedBlock(segment: Segment): SegmentedBlock {
if (this.tree === null) {
this.tree = this.createTree()
}
if (this.superRoot != null) {
const superRoot = this.superRoot
const proofs = this.tree.getProofByRange(
this.numTokens,
segment.getGlobalStart(),
segment.getGlobalEnd()
)
const items = proofs.map(proof => {
if (proof.leaf === utils.keccak256(HashZero)) {
return new ExclusionProof(this.getRoot(), proof)
} else {
const signedTx = this.getSignedTransaction(proof.leaf)
const index = signedTx.getIndex(proof.segment)
const proofsForInclusion = this.getProof(signedTx.hash())
return new SignedTransactionWithProof(
signedTx,
index.txIndex,
superRoot,
this.getRoot(),
this.timestamp,
proofsForInclusion,
utils.bigNumberify(this.number)
)
}
})
return new SegmentedBlock(segment, items, this.number)
} else {
throw new Error('')
}
}
public checkInclusion(tx: SignedTransactionWithProof, segment: Segment) {
if (this.tree === null) {
this.tree = this.createTree()
}
const proof = tx.getProof()
return SumMerkleTree.verify(
segment.getGlobalStart(),
segment.getGlobalEnd(),
Buffer.from(tx.signedTx.hash().substr(2), 'hex'),
TOTAL_AMOUNT.mul(proof.numTokens),
Buffer.from(this.getRoot().substr(2), 'hex'),
proof
)
}
/**
* @description construct merkle tree
* by segments of the transaction output
*/
public createTree() {
const numTokens = this.numTokens
const leaves = Array(numTokens)
.fill(0)
.map((_, i) => {
return this.createTokenTree(utils.bigNumberify(i))
})
.reduce((acc: SumMerkleTreeNode[], item: SumMerkleTreeNode[]) => {
return acc.concat(item)
}, [])
return new SumMerkleTree(leaves)
}
public createTokenTree(tokenId: BigNumber): SumMerkleTreeNode[] {
const segments: SegmentNode[] = []
this.txs.forEach(tx => {
tx.getSegments().forEach(s => {
if (tokenId.eq(s.getTokenId()) && s.getAmount().gt(0)) {
segments.push(new SegmentNode(s, tx.hash()))
}
})
})
segments.sort((a, b) => {
if (a.segment.start.gt(b.segment.start)) {
return 1
} else if (a.segment.start.lt(b.segment.start)) {
return -1
} else {
return 0
}
})
const nodes = segments.reduce(
(acc: SegmentNode[], segmentNode: SegmentNode) => {
let prevEnd = new BigNumber(0)
if (acc.length > 0) {
prevEnd = acc[acc.length - 1].segment.end
}
if (segmentNode.segment.start.gt(prevEnd)) {
return acc.concat([
new SegmentNode(
new Segment(tokenId, prevEnd, segmentNode.segment.start),
utils.keccak256(HashZero)
),
segmentNode
])
} else if (segmentNode.segment.start.eq(prevEnd)) {
return acc.concat([segmentNode])
} else {
throw new Error('segment duplecated')
}
},
[]
)
// add last exclusion segment
if (nodes.length === 0) {
// if there are no transaction
nodes.push(
new SegmentNode(
new Segment(tokenId, constants.Zero, TOTAL_AMOUNT),
utils.keccak256(HashZero)
)
)
} else {
const lastSegment = nodes[nodes.length - 1].segment
if (lastSegment.end.lt(TOTAL_AMOUNT)) {
const lastExclusion = new SegmentNode(
new Segment(tokenId, lastSegment.end, TOTAL_AMOUNT),
utils.keccak256(HashZero)
)
nodes.push(lastExclusion)
}
}
return nodes.map(n => new SumMerkleTreeNode(n.tx, n.segment.getAmount()))
}
public getTransactions() {
return this.txs
}
public getUserTransactions(
owner: Address,
predicatesManager: PredicatesManager
): SignedTransaction[] {
return this.txs.filter(tx => {
const hasOutput =
tx.getStateUpdates().filter(output => {
return output.isOwnedBy(owner, predicatesManager)
}).length > 0
const isSigner = tx.getSigners().indexOf(owner) >= 0
return hasOutput || isSigner
})
}
public getUserTransactionAndProofs(
owner: Address,
predicatesManager: PredicatesManager
): SignedTransactionWithProof[] {
return this.getUserTransactions(owner, predicatesManager).reduce(
(acc: SignedTransactionWithProof[], tx) => {
return acc.concat(this.getSignedTransactionWithProof(tx.hash()))
},
[]
)
}
} | the_stack |
import AsyncStorage from '@react-native-community/async-storage'
import { persistReducer } from 'redux-persist'
import {
Action,
walletInitRequestAction,
walletPhraseRequestAction,
walletDestroyRequestAction,
walletDestroySuccessAction,
walletMigrateToMainnetRequestAction,
walletScanOutputsRequestAction,
Store,
walletScanPmmrRangeFalureAction,
walletScanPmmrRangeRequestAction,
walletScanOutputsFalureAction,
walletScanPmmrRangeSuccessAction,
walletScanOutputsSuccessAction,
walletScanFailureAction,
} from 'src/common/types'
import { log } from 'src/common/logger'
import { combineReducers } from 'redux'
import {
mapPmmrRange,
checkWalletDataDirectory,
getConfigForRust,
} from 'src/common'
import RNFS from 'react-native-fs'
import { WALLET_DATA_DIRECTORY, TOR_DIRECTORY } from 'src/common'
import WalletBridge from 'src/bridges/wallet'
const MAX_RETRIES = 10
export const RECOVERY_LIMIT = 1000
const PMMR_RANGE_UPDATE_INTERVAL = 60 * 1000 // roughly one block
export type WalletInitState = {
isNew: boolean
error: {
message: string
code?: number
}
}
export type WalletScanState = {
inProgress: boolean
progress: number
isDone: boolean
lastRetrievedIndex?: number
lowestIndex?: number
highestIndex?: number
pmmrRangeLastUpdated?: number
currentPmmrIndex?: number
retryCount: number
error: {
message: string
code?: number
}
}
export type State = {
walletInit: WalletInitState
walletScan: WalletScanState
isCreated: boolean | null
isOpened: boolean
}
const initialState: State = {
walletInit: {
isNew: true,
error: {
message: '',
code: 0,
},
},
walletScan: {
inProgress: false,
progress: 0,
isDone: false,
currentPmmrIndex: 0,
retryCount: 0,
pmmrRangeLastUpdated: 0,
error: {
message: '',
code: 0,
},
},
isCreated: null,
isOpened: false,
}
const walletInit = function (
state: WalletInitState = initialState.walletInit,
action: Action,
): WalletInitState {
switch (action.type) {
case 'WALLET_CLEAR': {
return { ...initialState.walletInit }
}
case 'WALLET_INIT_REQUEST':
return {
...state,
error: {
message: '',
code: 0,
},
}
case 'WALLET_INIT_SET_IS_NEW':
return { ...initialState.walletInit, isNew: action.value }
case 'WALLET_INIT_FAILURE':
return {
...state,
error: {
message: action.message,
code: 0,
},
}
default:
return state
}
}
const walletScan = function (
state: WalletScanState = initialState.walletScan,
action: Action,
): WalletScanState {
switch (action.type) {
case 'WALLET_SCAN_START':
return { ...initialState.walletScan, inProgress: true }
case 'WALLET_SCAN_DONE':
return { ...initialState.walletScan, isDone: true }
case 'WALLET_SCAN_RESET':
return { ...initialState.walletScan }
case 'WALLET_SCAN_PMMR_RANGE_SUCCESS':
return {
...state,
lowestIndex: state.lowestIndex
? state.lowestIndex
: action.range.lastRetrievedIndex,
lastRetrievedIndex: state.lastRetrievedIndex
? state.lastRetrievedIndex
: action.range.lastRetrievedIndex,
highestIndex: action.range.highestIndex,
pmmrRangeLastUpdated: Date.now(),
retryCount: 0,
}
case 'WALLET_SCAN_PMMR_RANGE_FAILURE':
return { ...state, retryCount: state.retryCount + 1 }
case 'WALLET_SCAN_OUTPUTS_REQUEST':
return { ...state, error: initialState.walletScan.error }
case 'WALLET_SCAN_OUTPUTS_SUCCESS': {
if (!state.highestIndex || !state.lowestIndex) {
return state
}
const range = state.highestIndex - state.lowestIndex
const progress = action.lastRetrievedIndex - state.lowestIndex
const percentageComplete = Math.min(
Math.round((progress / range) * 100),
99,
)
return {
...state,
retryCount: 0,
progress: percentageComplete,
lastRetrievedIndex: action.lastRetrievedIndex,
}
}
case 'WALLET_SCAN_OUTPUTS_FAILURE':
return { ...state, retryCount: state.retryCount + 1 }
case 'WALLET_SCAN_FAILURE':
return {
...state,
inProgress: false,
isDone: true,
error: {
message: action.message,
},
}
default:
return state
}
}
export const reducer = combineReducers({
isCreated: function (
state: State['isCreated'] = initialState.isCreated,
action: Action,
): boolean | null {
switch (action.type) {
case 'WALLET_DESTROY_SUCCESS':
return false
case 'WALLET_INIT_SUCCESS':
return true
case 'WALLET_EXISTS_SUCCESS':
return action.exists
default:
return state
}
},
isOpened: function (
state: State['isOpened'] = initialState.isOpened,
action: Action,
): boolean | null {
switch (action.type) {
case 'SET_WALLET_OPEN':
return true
case 'CLOSE_WALLET':
return false
default:
return state
}
},
walletInit: persistReducer(
{
key: 'walletInit',
storage: AsyncStorage,
whitelist: ['isNew'],
},
walletInit,
) as typeof walletInit,
walletScan: persistReducer(
{
key: 'walletScan',
storage: AsyncStorage,
whitelist: [
'inProgress',
'isDone',
'progress',
'lastRetrievedIndex',
'highestIndex',
'downloadedInBytes',
],
},
walletScan,
) as typeof walletScan,
})
export const sideEffects = {
['WALLET_INIT_REQUEST']: async (
action: walletInitRequestAction,
store: Store,
) => {
const { password, phrase, isNew } = action
const configForWalletRust = getConfigForRust(store.getState())
await checkWalletDataDirectory()
try {
await WalletBridge.walletInit(
JSON.stringify(configForWalletRust),
phrase,
password,
)
await WalletBridge.openWallet(
JSON.stringify(configForWalletRust),
password,
)
store.dispatch({
type: 'SET_WALLET_OPEN',
})
if (isNew) {
store.dispatch({
type: 'WALLET_SCAN_DONE',
})
} else {
store.dispatch({
type: 'WALLET_SCAN_START',
})
}
setTimeout(() => {
store.dispatch({
type: 'WALLET_INIT_SUCCESS',
})
}, 250)
} catch (error) {
store.dispatch({
type: 'WALLET_INIT_FAILURE',
message: error.message,
})
log(error, true)
return
}
},
['WALLET_SCAN_FAILURE']: async (action: walletScanFailureAction) => {
log(action, true)
},
['CLOSE_WALLET']: async () => {
try {
await WalletBridge.closeWallet()
} catch (error) {
log(error, true)
}
},
['WALLET_SCAN_PMMR_RANGE_REQUEST']: async (
_action: walletScanPmmrRangeRequestAction,
store: Store,
) => {
await checkWalletDataDirectory()
try {
const range = mapPmmrRange(
JSON.parse(await WalletBridge.walletPmmrRange()),
)
store.dispatch({
type: 'WALLET_SCAN_PMMR_RANGE_SUCCESS',
range,
})
} catch (error) {
store.dispatch({
type: 'WALLET_SCAN_PMMR_RANGE_FAILURE',
message: error.message,
})
}
},
['WALLET_SCAN_PMMR_RANGE_SUCCESS']: async (
_action: walletScanPmmrRangeSuccessAction,
store: Store,
) => {
const { lastRetrievedIndex } = store.getState().wallet.walletScan
store.dispatch({
type: 'WALLET_SCAN_OUTPUTS_REQUEST',
lastRetrievedIndex: lastRetrievedIndex ?? 0,
})
},
['WALLET_SCAN_PMMR_RANGE_FAILURE']: async (
action: walletScanPmmrRangeFalureAction,
store: Store,
) => {
const { message } = action
const { retryCount } = store.getState().wallet.walletScan
if (retryCount < MAX_RETRIES) {
store.dispatch({
type: 'WALLET_SCAN_PMMR_RANGE_REQUEST',
})
} else {
store.dispatch({
type: 'WALLET_SCAN_FAILURE',
message,
})
}
},
['WALLET_SCAN_OUTPUTS_REQUEST']: async (
action: walletScanOutputsRequestAction,
store: Store,
) => {
const { lastRetrievedIndex } = action
const { highestIndex, lowestIndex } = store.getState().wallet.walletScan
if (!lowestIndex || !highestIndex) {
store.dispatch({
type: 'WALLET_SCAN_PMMR_RANGE_REQUEST',
})
return
}
await checkWalletDataDirectory()
try {
const newlastRetrievedIndex = JSON.parse(
await WalletBridge.walletScanOutputs(
lastRetrievedIndex ?? 0,
highestIndex,
),
)
store.dispatch({
type: 'WALLET_SCAN_OUTPUTS_SUCCESS',
lastRetrievedIndex: newlastRetrievedIndex,
})
} catch (error) {
store.dispatch({
type: 'WALLET_SCAN_OUTPUTS_FAILURE',
message: error.message,
})
}
},
['WALLET_SCAN_OUTPUTS_SUCCESS']: async (
action: walletScanOutputsSuccessAction,
store: Store,
) => {
const {
lastRetrievedIndex,
highestIndex,
pmmrRangeLastUpdated,
} = store.getState().wallet.walletScan
if (
!pmmrRangeLastUpdated ||
Date.now() - pmmrRangeLastUpdated > PMMR_RANGE_UPDATE_INTERVAL
) {
store.dispatch({
type: 'WALLET_SCAN_PMMR_RANGE_REQUEST',
})
} else {
if (lastRetrievedIndex == highestIndex) {
store.dispatch({
type: 'WALLET_SCAN_DONE',
})
} else {
if (store.getState().wallet.isOpened) {
store.dispatch({
type: 'WALLET_SCAN_OUTPUTS_REQUEST',
lastRetrievedIndex: action.lastRetrievedIndex,
})
}
}
}
},
['WALLET_SCAN_OUTPUTS_FAILURE']: async (
action: walletScanOutputsFalureAction,
store: Store,
) => {
const { message } = action
const {
retryCount,
lastRetrievedIndex,
} = store.getState().wallet.walletScan
if (store.getState().wallet.isOpened) {
// we ignore these errors, if wallet is closed
return
}
if (retryCount < MAX_RETRIES && lastRetrievedIndex) {
store.dispatch({
type: 'WALLET_SCAN_OUTPUTS_REQUEST',
lastRetrievedIndex,
})
} else {
store.dispatch({
type: 'WALLET_SCAN_FAILURE',
message,
})
}
},
['WALLET_PHRASE_REQUEST']: (
action: walletPhraseRequestAction,
store: Store,
) => {
return WalletBridge.walletPhrase(
getConfigForRust(store.getState()).wallet_dir,
// TODO: Add password here
action.password,
)
.then((phrase: string) => {
store.dispatch({
type: 'WALLET_PHRASE_SUCCESS',
phrase,
})
})
.catch((error: Error) => {
store.dispatch({
type: 'WALLET_PHRASE_FAILURE',
message: error.message,
})
log(error, true)
})
},
['WALLET_DESTROY_REQUEST']: async (
_action: walletDestroyRequestAction,
store: Store,
) => {
try {
if (await RNFS.exists(TOR_DIRECTORY)) {
await RNFS.unlink(TOR_DIRECTORY)
}
await RNFS.unlink(WALLET_DATA_DIRECTORY)
store.dispatch({
type: 'TX_LIST_CLEAR',
})
store.dispatch({
type: 'RESET_BIOMETRY_REQUEST',
})
store.dispatch({
type: 'WALLET_DESTROY_SUCCESS',
})
} catch (error) {
store.dispatch({
type: 'WALLET_PHRASE_FAILURE',
message: error.message,
})
log(error, true)
}
},
['WALLET_DESTROY_SUCCESS']: (
_action: walletDestroySuccessAction,
store: Store,
) => {
store.dispatch({
type: 'WALLET_CLEAR',
})
store.dispatch({
type: 'ACCEPT_LEGAL',
value: false,
})
},
['WALLET_MIGRATE_TO_MAINNET_REQUEST']: (
_action: walletMigrateToMainnetRequestAction,
store: Store,
) => {
store.dispatch({
type: 'SWITCH_TO_MAINNET',
})
store.dispatch({
type: 'WALLET_DESTROY_REQUEST',
})
},
['WALLET_EXISTS_REQUEST']: async (
_action: walletDestroySuccessAction,
store: Store,
) => {
try {
const exists = await WalletBridge.isWalletCreated()
store.dispatch({
type: 'WALLET_EXISTS_SUCCESS',
exists,
})
} catch (error) {
store.dispatch({
type: 'WALLET_EXISTS_FAILURE',
message: error.message,
})
log(error, true)
}
},
} | the_stack |
import * as AWS from 'aws-sdk';
import * as _ from 'lodash';
const elbv2 = new AWS.ELBv2();
const docClient = new AWS.DynamoDB.DocumentClient();
const ddbTable = process.env.LOOKUP_TABLE || '';
const sleep = (ms: number) => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
const createTargetGroup = async (name: string, port: number, vpcId: string, protocol: string) => {
const targetGroupParams = {
Name: name,
Port: port,
Protocol: protocol,
VpcId: vpcId,
TargetType: 'ip',
};
return elbv2.createTargetGroup(targetGroupParams).promise();
};
const enableTargetStickyness = async (targetGroupArn: string) => {
const targetGroupAtrributesParams = {
Attributes: [{ Key: 'stickiness.enabled', Value: 'true' }],
TargetGroupArn: targetGroupArn,
};
return elbv2.modifyTargetGroupAttributes(targetGroupAtrributesParams).promise();
};
const isValidPriority = async (priority: number, listenerArn: string) => {
const ruleParams = {
ListenerArn: listenerArn,
};
const ruleList = await elbv2.describeRules(ruleParams).promise();
const priorityExists =
ruleList.Rules?.filter(rule => {
return rule.Priority === priority.toString();
}) || [];
return priorityExists.length === 0;
};
const listenerExists = async (listenerArn: string): Promise<Boolean> => {
try {
const listenerParams: AWS.ELBv2.DescribeListenersInput = {
ListenerArns: [listenerArn],
};
await elbv2.describeListeners(listenerParams).promise();
return Promise.resolve(true);
} catch (err) {
console.log(err);
return Promise.resolve(false);
}
};
const createListenerRule = async (
listenerArn: string,
paths: string[],
hosts: string[],
targetGroupArn: string,
priority: number,
) => {
console.log('trying to create listener rule');
console.log(hosts, paths, listenerArn, targetGroupArn, priority);
const ruleParams: AWS.ELBv2.CreateRuleInput = {
Actions: [
{
TargetGroupArn: targetGroupArn,
Type: 'forward',
},
],
ListenerArn: listenerArn,
Priority: priority,
Conditions: [],
};
if (paths?.length > 0) {
const pathConfig = {
Field: 'path-pattern',
Values: paths,
};
ruleParams.Conditions.push(pathConfig);
}
if (hosts.length > 0) {
const hostConfig = {
Field: 'host-header',
Values: hosts,
};
ruleParams.Conditions.push(hostConfig);
}
return elbv2.createRule(ruleParams).promise();
};
const updateListenerRule = async (ruleArn: string, paths: string[], hosts: string[], targetGroupArn: string) => {
const ruleParams: AWS.ELBv2.ModifyRuleInput = {
Actions: [
{
TargetGroupArn: targetGroupArn,
Type: 'forward',
},
],
RuleArn: ruleArn,
Conditions: [],
};
if (paths?.length > 0) {
const pathConfig = {
Field: 'path-pattern',
Values: paths,
};
ruleParams?.Conditions?.push(pathConfig);
}
if (hosts.length > 0) {
const hostConfig = {
Field: 'host-header',
Values: hosts,
};
ruleParams?.Conditions?.push(hostConfig);
}
return elbv2.modifyRule(ruleParams).promise();
};
const deleteListenerRule = async (ruleArn: string) => {
const ruleParams = {
RuleArn: ruleArn,
};
return elbv2.deleteRule(ruleParams).promise();
};
const deleteTargetGroup = async (targetGroupArn: string) => {
const targetGroupParams = {
TargetGroupArn: targetGroupArn,
};
return elbv2.deleteTargetGroup(targetGroupParams).promise();
};
const updateRulePriority = async (ruleArn: string, priority: number) => {
const rulePriorityParams = {
RulePriorities: [
{
Priority: priority,
RuleArn: ruleArn,
},
],
};
return elbv2.setRulePriorities(rulePriorityParams).promise();
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const putRecord = async (table: string, record: any) => {
const putParams = {
TableName: table,
Item: record,
};
return docClient.put(putParams).promise();
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const targetGroupChange = (oldRecord: any, newRecord: any) => {
const oldTargetGroupAttributes = {
vpcId: oldRecord.vpcId,
destinationPort: oldRecord.targetGroupDestinationPort,
protocol: oldRecord.targetGroupProtocol,
};
const newTargetGroupAttributes = {
vpcId: newRecord.vpcId,
destinationPort: newRecord.targetGroupDestinationPort,
protocol: newRecord.targetGroupProtocol,
};
return !_.isEqual(oldTargetGroupAttributes, newTargetGroupAttributes);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const listernerRulesChange = (oldRecord: any, newRecord: any) => {
const oldListenerRules = {
sourceListenerArn: oldRecord.rule.sourceListenerArn,
priority: oldRecord.rule.condition.priority,
paths: oldRecord.rule.condition.paths?.sort(),
hosts: oldRecord.rule.condition.hosts?.sort(),
};
const newListenerRules = {
sourceListenerArn: newRecord.rule.sourceListenerArn,
priority: newRecord.rule.condition.priority,
paths: newRecord.rule.condition.paths?.sort(),
hosts: newRecord.rule.condition.hosts?.sort(),
};
return !_.isEqual(oldListenerRules, newListenerRules);
};
const priorityChange = (oldRecord: any, newRecord: any) => {
const oldPriority = oldRecord.rule.condition.priority;
const newPriority = newRecord.rule.condition.priority;
return !(oldPriority === newPriority);
};
const createRecordHandler = async (record: any) => {
console.log('Record creation detected.');
try {
if (!(await listenerExists(record.rule.sourceListenerArn))) {
throw new Error(`The ALB Listener ARN: ${record.rule.sourceListenerArn} does not exist. Exiting`);
}
console.log('Checking if priority is valid');
if (!(await isValidPriority(record.rule.condition.priority, record.rule.sourceListenerArn))) {
throw new Error(
`The priority ${record.rule.condition.priority.toString()} matches an existing rule priority on the listener arn ${
record.rule.sourceListenerArn
}. Priorities must not match. Exiting`,
);
}
const targetGroup = await createTargetGroup(
record.id,
record.targetGroupDestinationPort,
record.vpcId,
record.targetGroupProtocol,
);
const targetGroupArn = targetGroup?.TargetGroups?.[0].TargetGroupArn ?? '';
await enableTargetStickyness(targetGroupArn);
const rule = await createListenerRule(
record.rule.sourceListenerArn,
record.rule.condition.paths,
record.rule.condition.hosts,
targetGroupArn,
record.rule.condition.priority,
);
const ruleArn = rule?.Rules?.[0].RuleArn ?? '';
if (!targetGroupArn || !ruleArn) {
throw new Error(
`There was an error getting the target group arn or listener rule arn. \nTarget Group Arn: ${targetGroupArn}\nRule Arn: ${ruleArn}`,
);
}
record.metadata = {
targetGroupArn,
ruleArn,
targetGroupIpAddresses: [],
};
await putRecord(ddbTable, record);
console.log('Added metadata to table');
return record;
} catch (err) {
console.log('There was a problem creating resources for the following record', JSON.stringify(record, null, 4));
throw err;
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const deleteRecordHandler = async (record: any) => {
try {
console.log(`Deleting listener rule and target group for ${record.id}`);
await deleteListenerRule(record.metadata.ruleArn);
console.log('Deleted listener rule.');
} catch (err) {
console.log(err);
console.log('Could not delete listener rule for record. Continuing...', JSON.stringify(record, null, 4));
}
try {
await deleteTargetGroup(record.metadata.targetGroupArn);
console.log('Deleted target group');
return;
} catch (err) {
console.log('Could not delete target group for record', JSON.stringify(record, null, 4));
console.log(err);
}
};
const updateRecordHandler = async (newRecord: any, oldRecord: any) => {
try {
console.log(`The record with id ${newRecord.id} was updated. Performing comparison.`);
if (!(await listenerExists(newRecord.rule.sourceListenerArn))) {
throw new Error(`The ALB Listener ARN: ${newRecord.rule.sourceListenerArn} does not exist. Exiting`);
}
const newRecordClone = _.cloneDeep(newRecord);
const oldRecordClone = _.cloneDeep(oldRecord);
delete newRecordClone.metadata;
delete oldRecordClone.metadata;
if (_.isEqual(newRecordClone, oldRecordClone)) {
console.log(`Update Record hanlder found no changes made for record with Id ${newRecord.id}`);
return;
}
if (!oldRecord.metadata) {
console.log('No previous metadata detected for record. Creating metadata based off of new entry');
await createRecordHandler(newRecord);
return;
}
if (listernerRulesChange(oldRecord, newRecord)) {
console.log(`Detected a listener rule change. Modifying rule ${newRecord.metadata.ruleArn}`);
await updateListenerRule(
newRecord.metadata.ruleArn,
newRecord.rule.condition.paths,
newRecord.rule.condition.hosts,
newRecord.metadata.targetGroupArn,
);
}
if (priorityChange(oldRecord, newRecord)) {
if (!(await isValidPriority(newRecord.rule.condition.priority, newRecord.rule.sourceListenerArn))) {
throw new Error(
`The priority ${newRecord.rule.condition.priority.toString()} matches an existing rule priority on the listener arn ${
newRecord.rule.sourceListenerArn
}. Priorities must not match.`,
);
}
await updateRulePriority(newRecord.metadata.ruleArn, newRecord.rule.condition.priority);
}
if (targetGroupChange(oldRecord, newRecord)) {
console.log(
`Detected a target group change. deleting target group ${newRecord.metadata.targetGroupArn} and creating a new target group`,
);
await deleteRecordHandler(newRecord);
await sleep(10000);
await createRecordHandler(newRecord);
}
} catch (err) {
console.log('There was a problem updating a target group or listener rule for the records:');
console.log('Old Record: ', JSON.stringify(oldRecord, null, 4));
console.log('New Record: ', JSON.stringify(newRecord, null, 4));
throw err;
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const handler = async (event: any, _context: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const records = event.Records.map((record: any) => {
if (record.dynamodb.OldImage) {
record.dynamodb.OldImage = AWS.DynamoDB.Converter.unmarshall(record.dynamodb.OldImage);
}
if (record.dynamodb.NewImage) {
record.dynamodb.NewImage = AWS.DynamoDB.Converter.unmarshall(record.dynamodb.NewImage);
}
return record;
});
console.log(JSON.stringify(records, null, 4));
for (const record of records) {
if (record.eventName === 'INSERT') {
await createRecordHandler(record.dynamodb.NewImage);
}
if (record.eventName === 'MODIFY') {
await updateRecordHandler(record.dynamodb.NewImage, record.dynamodb.OldImage);
}
if (record.eventName === 'REMOVE') {
await deleteRecordHandler(record.dynamodb.OldImage);
}
}
console.log(JSON.stringify(records, null, 4));
}; | the_stack |
import { TransformContext } from '@revert/transform'
import { create, act } from 'react-test-renderer'
import type { ReactTestRenderer } from 'react-test-renderer'
import { createSpy, getSpyCalls } from 'spyfn'
import test from 'tape'
import { PrimitiveSize } from '../src/PrimitiveSize'
test('revert/PrimitiveSize: standard flow', (t) => {
const sizes = {
top: 0,
left: 0,
right: 42.424,
bottom: 34.243,
}
const onWidthChangeSpy = createSpy(() => {})
const onHeightChangeSpy = createSpy(() => {})
const getRectSpy = createSpy(() => sizes)
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize
width={0}
height={0}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42.5],
],
'Mount: should call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
],
'Mount: should call onHeightChange'
)
/* Update */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
width={42.5}
height={34}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42.5],
],
'Update: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
],
'Update: should not call onHeightChange'
)
/* Unmount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.unmount()
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42.5],
],
'Unmount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
],
'Unmount: should not call onHeightChange'
)
t.end()
})
test('revert/PrimitiveSize: mount with correct initial sizes', (t) => {
const sizes = {
left: 0,
top: 0,
right: 42.879,
bottom: 34.677,
}
const onWidthChangeSpy = createSpy(() => {})
const onHeightChangeSpy = createSpy(() => {})
const getRectSpy = createSpy(() => sizes)
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize
width={43}
height={34.5}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[],
'Mount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[],
'Mount: should not call onHeightChange'
)
/* Update */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
width={43}
height={34.5}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[],
'Update: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[],
'Update: should not call onHeightChange'
)
/* Unmount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.unmount()
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[],
'Unmount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[],
'Unmount: should not call onHeightChange'
)
t.end()
})
test('revert/PrimitiveSize: report if measured sizes has changed', (t) => {
const sizes = [{
left: 0,
top: 0,
right: 42,
bottom: 34,
}, {
left: 0,
top: 0,
right: 43,
bottom: 35,
}]
const onWidthChangeSpy = createSpy(() => {})
const onHeightChangeSpy = createSpy(() => {})
const getRectSpy = createSpy(({ index }) => sizes[index])
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize
width={0}
height={0}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42],
],
'Mount: should call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
],
'Mount: should call onHeightChange'
)
/* Update */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
width={42}
height={34}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42],
[43],
],
'Update: should call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
[35],
],
'Update: should call onHeightChange'
)
/* Unmount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.unmount()
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[42],
[43],
],
'Unmount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[34],
[35],
],
'Unmount: should not call onHeightChange'
)
t.end()
})
test('revert/PrimitiveSize: multiple children', (t) => {
const sizes = [
{
left: -5,
right: 15,
top: 5,
bottom: 15,
},
{
left: 10,
right: 20,
top: 10,
bottom: 20,
},
]
const onWidthChangeSpy = createSpy(() => {})
const onHeightChangeSpy = createSpy(() => {})
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize
width={0}
height={0}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: () => sizes[0],
}, {
getBoundingClientRect: () => sizes[1],
}],
}
},
}
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[25],
],
'Mount: should call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[15],
],
'Mount: should call onHeightChange'
)
/* Update */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
width={25}
height={15}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[25],
],
'Update: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[15],
],
'Update: should not call onHeightChange'
)
/* Unmount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.unmount()
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[25],
],
'Unmount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[15],
],
'Unmount: should not call onHeightChange'
)
t.end()
})
test('revert/PrimitiveSize: transform scale', (t) => {
const sizes = {
top: 0,
left: 0,
right: 40,
bottom: 25,
}
const onWidthChangeSpy = createSpy(() => {})
const onHeightChangeSpy = createSpy(() => {})
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<TransformContext.Provider value={{ _scale: 2 }}>
<PrimitiveSize
width={0}
height={0}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
</TransformContext.Provider>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: () => sizes,
}],
}
},
}
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[20],
],
'Mount: should call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[12.5],
],
'Mount: should call onHeightChange'
)
/* Update */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<TransformContext.Provider value={{ _scale: 2 }}>
<PrimitiveSize
width={20}
height={12.5}
onWidthChange={onWidthChangeSpy}
onHeightChange={onHeightChangeSpy}
>
<span/>
</PrimitiveSize>
</TransformContext.Provider>
)
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[20],
],
'Update: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[12.5],
],
'Update: should not call onHeightChange'
)
/* Unmount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.unmount()
})
t.deepEquals(
getSpyCalls(onWidthChangeSpy),
[
[20],
],
'Unmount: should not call onWidthChange'
)
t.deepEquals(
getSpyCalls(onHeightChangeSpy),
[
[12.5],
],
'Unmount: should not call onHeightChange'
)
t.end()
})
test('revert/PrimitiveSize: maxWidth', (t) => {
const sizes = {
left: 0,
top: 0,
right: 42,
bottom: 34,
}
const getRectSpy = createSpy(() => sizes)
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
renderer!.toJSON(),
{
type: 'div',
props: {
style: {
position: 'absolute',
left: 0,
top: 0,
width: 'max-content',
},
},
children: [{ type: 'span', props: {}, children: null }],
},
'should not have max-width set in styles'
)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
maxWidth={30}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
renderer!.toJSON(),
{
type: 'div',
props: {
style: {
position: 'absolute',
left: 0,
top: 0,
width: 'max-content',
maxWidth: 30,
},
},
children: [{ type: 'span', props: {}, children: null }],
},
'should have max-width set in styles'
)
t.end()
})
test('revert/PrimitiveSize: expand width', (t) => {
const sizes = {
left: 0,
top: 0,
right: 42,
bottom: 34,
}
const getRectSpy = createSpy(() => sizes)
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
renderer!.toJSON(),
{
type: 'div',
props: {
style: {
position: 'absolute',
left: 0,
top: 0,
width: 'max-content',
},
},
children: [{ type: 'span', props: {}, children: null }],
},
'width is set to max-content'
)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer.update(
<PrimitiveSize
width={30}
>
<span/>
</PrimitiveSize>
)
})
t.deepEquals(
renderer!.toJSON(),
{
type: 'div',
props: {
style: {
position: 'absolute',
left: 0,
top: 0,
width: 30,
},
},
children: [{ type: 'span', props: {}, children: null }],
},
'width is set as defined'
)
t.end()
})
test('revert/PrimitiveSize: shouldPreventWrap prop', (t) => {
const sizes = {
left: 0,
top: 0,
right: 42,
bottom: 34,
}
const getRectSpy = createSpy(() => sizes)
let renderer: ReactTestRenderer
/* Mount */
// eslint-disable-next-line @typescript-eslint/no-floating-promises
act(() => {
renderer = create(
<PrimitiveSize shouldPreventWrap>
<span/>
</PrimitiveSize>
, {
createNodeMock: () => {
return {
children: [{
getBoundingClientRect: getRectSpy,
}],
}
},
}
)
})
t.deepEquals(
renderer!.toJSON(),
{
type: 'div',
props: {
style: {
display: 'flex',
position: 'absolute',
left: 0,
top: 0,
width: 'max-content',
},
},
children: [{ type: 'span', props: {}, children: null }],
},
'should set display to flex'
)
t.end()
}) | the_stack |
import * as assert from 'assert';
import {Labels} from '../src/labels/labels';
import {readFileSync} from 'fs';
import {SjasmplusSldLabelParser} from '../src/labels/sjasmplussldlabelparser';
//import { Settings } from '../src/settings';
suite('Labels (sjasmplus)', () => {
setup(() => {
Labels.init(250);
});
suite('Labels', () => {
test('Labels', () => {
// Read result data (labels)
const labelsFile = readFileSync('./tests/data/labels/projects/sjasmplus/general/general.labels').toString().split('\n');
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld', srcDirs: [""], // Sources mode
excludeFiles: [],
disableBanking: true
}]
};
Labels.readListFiles(config);
// Compare all labels
for (const labelLine of labelsFile) {
if (labelLine == '')
continue;
// A line looks like: "modfilea.fa_label3.mid.local: equ 0x00009003"
const match = /@?(.*):\s+equ\s+(.*)/i.exec(labelLine)!;
assert.notEqual(undefined, match); // Check that line is parsed correctly
const label = match[1];
const value = parseInt(match[2], 16);
// Check
const res = Labels.getNumberForLabel(label);
assert.equal(value, res!);
}
});
test('IF 0 Labels', () => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld',
srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
// Test the a label under an IF 0/ENDIF is not defined
const res = Labels.getNumberForLabel('label5');
assert.equal(undefined, res);
});
suite('Sources-Mode', () => {
test('Labels location', () => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld',
srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
// Test
let res = Labels.getLocationOfLabel('label1')!;
assert.notEqual(undefined, res);
assert.equal('main.asm', res.file);
assert.equal(18 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('fa_label1')!;
assert.notEqual(undefined, res);
assert.equal('filea.asm', res.file);
assert.equal(2 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('modfilea.fa_label2')!;
assert.notEqual(undefined, res);
assert.equal('filea.asm', res.file);
assert.equal(6 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('modfilea.fa_label3.mid')!;
assert.notEqual(undefined, res);
assert.equal('filea.asm', res.file);
assert.equal(9 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('modfilea.fab_label1')!;
assert.notEqual(undefined, res);
assert.equal('filea_b.asm', res.file);
assert.equal(3 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('modfilea.modfileb.fab_label2')!;
assert.notEqual(undefined, res);
assert.equal('filea_b.asm', res.file);
assert.equal(8 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('global_label1')!;
assert.notEqual(undefined, res);
assert.equal('filea_b.asm', res.file);
assert.equal(12 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('global_label2')!;
assert.notEqual(undefined, res);
assert.equal('filea_b.asm', res.file);
assert.equal(14 - 1, res.lineNr); // line number starts at 0
res = Labels.getLocationOfLabel('modfilea.fab_label_equ1')!;
assert.notEqual(undefined, res);
assert.equal('filea_b.asm', res.file);
assert.equal(22 - 1, res.lineNr); // line number starts at 0
});
test('address -> file/line', () => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld',
srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
// Tests
let res = Labels.getFileAndLineForAddress(0x10000 + 0x8000);
assert.ok(res.fileName.endsWith('main.asm'));
assert.equal(19 - 1, res.lineNr);
res = Labels.getFileAndLineForAddress(0x10000 + 0x9001);
assert.ok(res.fileName.endsWith('filea.asm'));
assert.equal(7 - 1, res.lineNr);
res = Labels.getFileAndLineForAddress(0x10000 + 0x9005);
assert.ok(res.fileName.endsWith('filea_b.asm'));
assert.equal(4 - 1, res.lineNr);
res = Labels.getFileAndLineForAddress(0x10000 + 0x900B);
assert.ok(res.fileName.endsWith('filea.asm'));
assert.equal(17 - 1, res.lineNr);
});
test('file/line -> address', () => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld', srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
// Tests
let address = Labels.getAddrForFileAndLine('main.asm', 19 - 1);
assert.equal(0x10000 + 0x8000, address);
address = Labels.getAddrForFileAndLine('filea.asm', 7 - 1);
assert.equal(0x10000 + 0x9001, address);
address = Labels.getAddrForFileAndLine('filea_b.asm', 4 - 1);
assert.equal(0x10000 + 0x9005, address);
address = Labels.getAddrForFileAndLine('filea.asm', 17 - 1);
assert.equal(0x10000 + 0x900B, address);
});
});
});
test('Occurence of WPMEM, ASSERTION, LOGPOINT', () => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/general/general.sld', srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
// Test WPMEM
const wpLines = Labels.getWatchPointLines();
assert.equal(wpLines.length, 1);
assert.equal(wpLines[0].address, 0x10000 + 0x8200);
assert.equal(wpLines[0].line, "WPMEM");
// Test ASSERTION
const assertionLines = Labels.getAssertionLines();
assert.equal(assertionLines.length, 1);
assert.equal(assertionLines[0].address, 0x10000 + 0x8005);
assert.equal(assertionLines[0].line, "ASSERTION");
// Test LOGPOINT
const lpLines = Labels.getLogPointLines();
assert.equal(lpLines.length, 1);
assert.equal(lpLines[0].address, 0x10000 + 0x800F);
assert.equal(lpLines[0].line, "LOGPOINT");
});
suite('Self modifying code', () => {
setup(() => {
// Read the list file
const config = {
sjasmplus: [{
path: './tests/data/labels/projects/sjasmplus/sld_self_modifying_code/main.sld', srcDirs: [""], // Sources mode
excludeFiles: []
}]
};
Labels.readListFiles(config);
});
test('Start addresses found', () => {
// Note 0x8000 is at bank 4. So: 0x05....
// 0x8000
let entry = Labels.getFileAndLineForAddress(0x058000);
assert.notEqual(entry.fileName, ''); // Known
// 0x8100
entry = Labels.getFileAndLineForAddress(0x058100);
assert.notEqual(entry.fileName, ''); // Known
// 0x8200, 0x8201, 0x8203, 0x8206, 0x800A
entry = Labels.getFileAndLineForAddress(0x058200);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058201);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058203);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058206);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x05820A);
assert.notEqual(entry.fileName, ''); // Known
// 0x8300
entry = Labels.getFileAndLineForAddress(0x058300);
assert.notEqual(entry.fileName, ''); // Known
});
test('Address ranges (after start address) found', () => {
// Note 0x8000 is at bank 4. So: 0x05....
// 0x8001-0x8002
let entry = Labels.getFileAndLineForAddress(0x058001);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058002);
assert.notEqual(entry.fileName, ''); // Known
// 0x8101-0x8102
entry = Labels.getFileAndLineForAddress(0x058101);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058102);
assert.notEqual(entry.fileName, ''); // Known
// 0x8202, 0x8004, 0x8005, 0x8007, 0x8008, 0x8009
entry = Labels.getFileAndLineForAddress(0x058202);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058204);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058205);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058207);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058208);
assert.notEqual(entry.fileName, ''); // Known
entry = Labels.getFileAndLineForAddress(0x058209);
assert.notEqual(entry.fileName, ''); // Known
// 0x8301
entry = Labels.getFileAndLineForAddress(0x058301);
assert.notEqual(entry.fileName, ''); // Known
});
test('addressAdd4', () => {
const sdlParser = new SjasmplusSldLabelParser(undefined as any, undefined as any, undefined as any, undefined as any, undefined as any, undefined as any, undefined as any, undefined as any, undefined as any) as any;
// 64k address
sdlParser.bankSize = 0x10000;
assert.equal(sdlParser.addressAdd4(0x0000), 0x0004);
assert.equal(sdlParser.addressAdd4(0xFFFF), 0xFFFF);
assert.equal(sdlParser.addressAdd4(0xFFFE), 0xFFFF);
assert.equal(sdlParser.addressAdd4(0xFFFD), 0xFFFF);
assert.equal(sdlParser.addressAdd4(0xFFFC), 0xFFFF);
assert.equal(sdlParser.addressAdd4(0xFFFB), 0xFFFF);
assert.equal(sdlParser.addressAdd4(0xFFFA), 0xFFFE);
// long address
sdlParser.bankSize = 0x2000;
assert.equal(sdlParser.addressAdd4(0x018000), 0x018004);
assert.equal(sdlParser.addressAdd4(0x019FFE), 0x019FFF);
assert.equal(sdlParser.addressAdd4(0x01FFFF), 0x01FFFF);
});
});
}); | the_stack |
/// <reference types="node" />
import * as SerialPort from 'serialport';
import { EventEmitter } from 'events';
export = Board;
/**
* Most of these are generated by observing https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js.
*
* This is a starting point that appeared to work fine for months within a project of my company, but I give no
* guarantee that it cannot be improved.
*/
declare class Board extends EventEmitter {
constructor(serialPort: any, optionsOrCallback?: Board.Options|((error: any) => void), callback?: (error: any) => void)
MODES: Board.PinModes;
STEPPER: Board.StepperConstants;
I2C_MODES: Board.I2cModes;
SERIAL_MODES: Board.SerialModes;
SERIAL_PORT_IDs: Board.SerialPortIds;
SERIAL_PIN_TYPES: Board.SerialPinTypes;
HIGH: Board.PIN_STATE;
LOW: Board.PIN_STATE;
pins: Board.Pins[];
ports: number[];
analogPins: number[];
version: Board.Version;
firmware: Board.Firmware;
settings: Board.Settings;
protected transport: SerialPort;
reportVersion(callback: () => void): void;
queryFirmware(callback: () => void): void;
analogRead(pin: number, callback: (value: number) => void): void;
analogWrite(pin: number, value: number): void;
pwmWrite(pin: number, value: number): void;
servoConfig(pin: number, min: number, max: number): void;
servoWrite(pin: number, value: number): void;
pinMode(pin: number, mode: Board.PIN_MODE): void;
digitalWrite(pin: number, val: Board.PIN_STATE): void;
digitalRead(pin: number, callback: (val: Board.PIN_STATE) => void): void;
queryCapabilities(callback: () => void): void;
queryAnalogMapping(callback: () => void): void;
queryPinState(pin: number, callback: () => void): void;
// TODO untested --- TWW
sendString(str: string): void;
// TODO untested --- TWW
sendI2CConfig(delay: number): void;
// TODO untested --- TWW
i2cConfig(options: number|{ delay: number }): void;
// TODO untested --- TWW
sendI2CWriteRequest(slaveAddress: number, bytes: number[]): void;
// TODO untested --- TWW
i2cWrite(address: number, register: number, inBytes: number[]): void;
i2cWrite(address: number, data: number[]): void;
// TODO untested --- TWW
i2cWriteReg(address: number, register: number, byte: number): void;
// TODO untested --- TWW
sendI2CReadRequest(address: number, numBytes: number, callback: () => void): void;
// TODO untested --- TWW
i2cRead(address: number, register: number, bytesToRead: number, callback: (data: number[]) => void): void;
i2cRead(address: number, bytesToRead: number, callback: (data: number[]) => void): void;
// TODO untested --- TWW
i2cStop(options: number|{ bus: number, address: number }): void;
// TODO untested --- TWW
i2cReadOnce(address: number, register: number, bytesToRead: number, callback: (data: number[]) => void): void;
i2cReadOnce(address: number, bytesToRead: number, callback: (data: number[]) => void): void;
// TODO untested --- TWW
sendOneWireConfig(pin: number, enableParasiticPower: boolean): void;
// TODO untested --- TWW
sendOneWireSearch(pin: number, callback: () => void): void;
// TODO untested --- TWW
sendOneWireAlarmsSearch(pin: number, callback: () => void): void;
// TODO untested --- TWW
sendOneWireRead(pin: number, device: number, numBytesToRead: number, callback: () => void): void;
// TODO untested --- TWW
sendOneWireReset(pin: number): void;
// TODO untested --- TWW
sendOneWireWrite(pin: number, device: number, data: number|number[]): void;
// TODO untested --- TWW
sendOneWireDelay(pin: number, delay: number): void;
// TODO untested --- TWW
sendOneWireWriteAndRead(
pin: number,
device: number,
data: number|number[],
numBytesToRead: number,
callback: (error?: Error, data?: number) => void): void;
setSamplingInterval(interval: number): void;
getSamplingInterval(): number;
reportAnalogPin(pin: number, value: Board.REPORTING): void;
reportDigitalPin(pin: number, value: Board.REPORTING): void;
// TODO untested/incomplete --- TWW
pingRead(opts: any, callback: () => void): void;
stepperConfig(
deviceNum: number,
type: number,
stepsPerRev: number,
dirOrMotor1Pin: number,
stepOrMotor2Pin: number,
motor3Pin?: number,
motor4Pin?: number): void;
stepperStep(
deviceNum: number,
direction: Board.STEPPER_DIRECTION,
steps: number,
speed: number,
accel: number|((bool?: boolean) => void),
decel?: number,
callback?: (bool?: boolean) => void): void;
// TODO untested --- TWW
serialConfig(options: { portId: Board.SERIAL_PORT_ID, baud: number, rxPin?: number | undefined, txPin?: number | undefined }): void;
// TODO untested --- TWW
serialWrite(portId: Board.SERIAL_PORT_ID, inBytes: number[]): void;
// TODO untested --- TWW
serialRead(portId: Board.SERIAL_PORT_ID, maxBytesToRead: number, callback: () => void): void;
// TODO untested --- TWW
serialStop(portId: Board.SERIAL_PORT_ID): void;
// TODO untested --- TWW
serialClose(portId: Board.SERIAL_PORT_ID): void;
// TODO untested --- TWW
serialFlush(portId: Board.SERIAL_PORT_ID): void;
// TODO untested --- TWW
serialListen(portId: Board.SERIAL_PORT_ID): void;
// TODO untested --- TWW
sysexResponse(commandByte: number, handler: (data: number[]) => void): void;
// TODO untested --- TWW
sysexCommand(message: number[]): void;
reset(): void;
static isAcceptablePort(port: Board.Port): boolean;
static requestPort(callback: (error: any, port: Board.Port) => any): void;
// TODO untested --- TWW
static encode(data: number[]): number[];
// TODO untested --- TWW
static decode(data: number[]): number[];
// TODO untested/incomplete --- TWW
protected _sendOneWireSearch(type: any, event: any, pin: number, callback: () => void): void;
// TODO untested/incomplete --- TWW
protected _sendOneWireRequest(
pin: number,
subcommand: any,
device: any,
numBytesToRead: any,
correlationId: any,
delay: number,
dataToWrite: any,
event: any, callback: () => void): void;
}
declare namespace Board {
// https://github.com/firmata/firmata.js/blob/master/lib/firmata.js#L429-L451
interface Options {
skipCapabilities?: boolean | undefined;
reportVersionTimeout?: number | undefined;
samplingInterval?: number | undefined;
serialport?: SerialPort.Options | undefined;
pins?: Pins[] | undefined;
analogPins?: number[] | undefined;
}
interface PinModes {
INPUT: PIN_MODE;
OUTPUT: PIN_MODE;
ANALOG: PIN_MODE;
PWM: PIN_MODE;
SERVO: PIN_MODE;
SHIFT: PIN_MODE;
I2C: PIN_MODE;
ONEWIRE: PIN_MODE;
STEPPER: PIN_MODE;
SERIAL: PIN_MODE;
PULLUP: PIN_MODE;
IGNORE: PIN_MODE;
PING_READ: PIN_MODE;
UNKOWN: PIN_MODE;
}
interface StepperConstants {
TYPE: {
DRIVER: STEPPER_TYPE,
TWO_WIRE: STEPPER_TYPE,
FOUR_WIRE: STEPPER_TYPE,
};
RUNSTATE: {
STOP: STEPPER_RUN_STATE,
ACCEL: STEPPER_RUN_STATE,
DECEL: STEPPER_RUN_STATE,
RUN: STEPPER_RUN_STATE,
};
DIRECTION: { CCW: STEPPER_DIRECTION, CW: STEPPER_DIRECTION };
}
// tslint:disable-next-line interface-name
interface I2cModes {
WRITE: I2C_MODE;
READ: I2C_MODE;
CONTINUOUS_READ: I2C_MODE;
STOP_READING: I2C_MODE;
}
interface SerialModes {
CONTINUOUS_READ: SERIAL_MODE;
STOP_READING: SERIAL_MODE;
}
interface SerialPortIds {
HW_SERIAL0: SERIAL_PORT_ID;
HW_SERIAL1: SERIAL_PORT_ID;
HW_SERIAL2: SERIAL_PORT_ID;
HW_SERIAL3: SERIAL_PORT_ID;
SW_SERIAL0: SERIAL_PORT_ID;
SW_SERIAL1: SERIAL_PORT_ID;
SW_SERIAL2: SERIAL_PORT_ID;
SW_SERIAL3: SERIAL_PORT_ID;
DEFAULT: SERIAL_PORT_ID;
}
interface SerialPinTypes {
RES_RX0: SERIAL_PIN_TYPE;
RES_TX0: SERIAL_PIN_TYPE;
RES_RX1: SERIAL_PIN_TYPE;
RES_TX1: SERIAL_PIN_TYPE;
RES_RX2: SERIAL_PIN_TYPE;
RES_TX2: SERIAL_PIN_TYPE;
RES_RX3: SERIAL_PIN_TYPE;
RES_TX3: SERIAL_PIN_TYPE;
}
interface Pins {
mode: PIN_MODE;
value: PIN_STATE | number;
supportedModes: PIN_MODE[];
analogChannel: number;
report: REPORTING;
state: PIN_STATE | PULLUP_STATE; // TODO not sure if this exists anymore... --- TWW
}
interface Firmware {
name: string;
version: Version;
}
interface Settings {
reportVersionTimeout: number;
samplingInterval: number;
serialport: {
baudRate: number,
bufferSize: number,
};
}
interface Port {
comName: string;
}
interface Version {
major: number;
minor: number;
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L449-L464
const enum PIN_MODE {
INPUT = 0x00,
OUTPUT = 0x01,
ANALOG = 0x02,
PWM = 0x03,
SERVO = 0x04,
SHIFT = 0x05,
I2C = 0x06,
ONEWIRE = 0x07,
STEPPER = 0x08,
SERIAL = 0x0A,
PULLUP = 0x0B,
IGNORE = 0x7F,
PING_READ = 0x75,
UNKNOWN = 0x10,
}
const enum PIN_STATE {
LOW = 0,
HIGH = 1
}
const enum REPORTING {
ON = 1,
OFF = 0,
}
const enum PULLUP_STATE {
ENABLED = 1,
DISABLED = 0,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L474-L478
const enum STEPPER_TYPE {
DRIVER = 1,
TWO_WIRE = 2,
FOUR_WIRE = 4,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L479-L484
const enum STEPPER_RUN_STATE {
STOP = 0,
ACCEL = 1,
DECEL = 2,
RUN = 3,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L485-L488
const enum STEPPER_DIRECTION {
CCW = 0,
CW = 1,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L466-L471
const enum I2C_MODE {
WRITE = 0,
READ = 1,
CONTINUOUS_READ = 2,
STOP_READING = 3
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L491-L494
const enum SERIAL_MODE {
CONTINUOUS_READ = 0x00,
STOP_READING = 0x01,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L497-L512
const enum SERIAL_PORT_ID {
HW_SERIAL0 = 0x00,
HW_SERIAL1 = 0x01,
HW_SERIAL2 = 0x02,
HW_SERIAL3 = 0x03,
SW_SERIAL0 = 0x08,
SW_SERIAL1 = 0x09,
SW_SERIAL2 = 0x10,
SW_SERIAL3 = 0x11,
DEFAULT = 0x08,
}
// https://github.com/firmata/firmata.js/blob/v0.15.0/lib/firmata.js#L515-L524
const enum SERIAL_PIN_TYPE {
RES_RX0 = 0x00,
RES_TX0 = 0x01,
RES_RX1 = 0x02,
RES_TX1 = 0x03,
RES_RX2 = 0x04,
RES_TX2 = 0x05,
RES_RX3 = 0x06,
RES_TX3 = 0x07,
}
} | 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 Code that can handle the translation of aircraft properties into text or HTML.
*/
namespace VRS
{
/*
* Global options
*/
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.aircraftRendererEnableDebugProperties = VRS.globalOptions.aircraftRendererEnableDebugProperties !== undefined ? VRS.globalOptions.aircraftRendererEnableDebugProperties : false; // True if the debug aircraft properties that expose some internal values are switched on. This needs to be changed BEFORE aircraftRenderer.js is loaded by the browser, it has no effect after.
/**
* The options that can be passed into an aircraft property renderer.
*/
export interface AircraftRenderOptions
{
unitDisplayPreferences: UnitDisplayPreferences;
distinguishOnGround?: boolean;
flagUncertainCallsigns?: boolean;
showUnits?: boolean;
suppressRouteCorrectionLinks?: boolean;
airportDataThumbnails?: number;
plotterOptions?: AircraftPlotterOptions;
mirrorMapJQ?: JQuery;
aircraftList?: AircraftList;
}
/**
* The settings that need to be passed to new instances of RenderPropertyHandler.
*/
export interface RenderPropertyHandler_Settings
{
//
/**
* The VRS.RenderProperty enum value for the aircraft property that this handler can deal with.
*/
property: RenderPropertyEnum;
/**
* A combination of VRS.RenderSurface bitflags that describe which surfaces this handler can render the property onto.
*/
surfaces: RenderSurfaceBitFlags;
/**
* The key into VRS.$$ for the text to display for column headings. Uses the labelKey if not supplied.
*/
headingKey?: string;
/**
* The key into VRS.$$ for the text to display for full display labels. Uses the headingKey if not supplied.
*/
labelKey?: string;
/**
* The key into VRS.$$ for the text to display for configuration UI labels. Uses either headingKey or labelKey if not supplied.
*/
optionsLabelKey?: string;
/**
* The VRS.Alignment enum describing the alignment for column headings - uses alignment if not supplied.
*/
headingAlignment?: AlignmentEnum;
/**
* The VRS.Alignment enum describing the alignment for values in columns - uses alignment if not supplied.
*/
contentAlignment?: AlignmentEnum;
/**
* The VRS.Alignment enum describing the alignment for headings and column values.
*/
alignment?: AlignmentEnum;
/**
* An optional fixed width as a CSS width string (e.g. '20px' or '6em') when rendering within columns.
*/
fixedWidth?: (surface: RenderSurfaceBitFlags) => string;
/**
* Returns true if the content of the property changed in the last update.
*/
hasChangedCallback?: (aircraft?: Aircraft) => boolean;
/**
* Takes an aircraft, options object and surface and returns the text content that represents the property.
*/
contentCallback?: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
/**
* Takes an aircraft, options object and surface and returns HTML that represents the property.
*/
renderCallback?: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
/**
* Takes an aircraft, options object and surface and returns true if the renderCallback should be used or false if the contentCallback should be used. Only supply this if you supply BOTH contentCallback and renderCallback.
*/
useHtmlRendering?: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => boolean;
/**
* Takes a VRS.DisplayUnitDependency enum and returns true if the property display depends upon it. Defaults to method that returns false.
*/
usesDisplayUnit?: (displayUnitDependency: DisplayUnitDependencyEnum) => boolean;
/**
* Returns true if the tooltip has changed in the last update. Defaults to hasChangedCallback if not supplied.
*/
tooltipChangedCallback?: (aircraft?: Aircraft) => boolean;
/**
* Takes an aircraft, options object and render surface and returns the tooltip text for the property. If not supplied then the property has no tooltip.
*/
tooltipCallback?: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
/**
* Takes a VRS.RenderSurface and returns true if the label should not be rendered on the surface. Defaults to a method that returns false.
*/
suppressLabelCallback?: (surface: RenderSurfaceBitFlags) => boolean;
/**
* True if the content takes more than one line of text to display, false if it does not. Defaults to false.
*/
isMultiLine?: boolean;
/**
* An optional reference to the sortable field for the property.
*/
sortableField?: AircraftListSortableFieldEnum;
/**
* Widget support - called after an element has been created for the render property, allows the renderer to add a widget to the element.
*/
createWidget?: (element?: JQuery, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => void;
/**
* Widget support - renders the property into a widget.
*/
renderWidget?: (element?: JQuery, aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => void;
/**
* Destroys the widget attached to the element.
*/
destroyWidget?: (element?: JQuery, surface?: RenderSurfaceBitFlags) => void;
/**
* Passed true if updates are being suspended and false if updates are being resumed.
*/
suspendWidget?: (element: JQuery, surface: RenderSurfaceBitFlags, suspend: boolean) => void;
}
/**
* A class that brings together everything needed to present a piece of information about an aircraft.
*/
export class RenderPropertyHandler
{
private _SuspendWidget: (element: JQuery, surface: RenderSurfaceBitFlags, suspend: boolean) => void;
// Keeping these as public fields for backwards compatibility
property: RenderPropertyEnum;
surfaces: RenderSurfaceBitFlags;
headingKey: string;
labelKey: string;
optionsLabelKey: string;
headingAlignment: AlignmentEnum;
contentAlignment: AlignmentEnum;
fixedWidth: (surface: RenderSurfaceBitFlags) => string;
hasChangedCallback: (aircraft?: Aircraft) => boolean;
contentCallback: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
renderCallback: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
useHtmlRendering: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => boolean;
usesDisplayUnit: (displayUnitDependency: DisplayUnitDependencyEnum) => boolean;
tooltipChangedCallback: (aircraft?: Aircraft) => boolean;
tooltipCallback: (aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => string;
suppressLabelCallback: (surface: RenderSurfaceBitFlags) => boolean;
isMultiLine: boolean;
sortableField: AircraftListSortableFieldEnum;
createWidget: (element?: JQuery, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => void;
renderWidget: (element?: JQuery, aircraft?: Aircraft, options?: AircraftRenderOptions, surface?: RenderSurfaceBitFlags) => void;
destroyWidget: (element?: JQuery, surface?: RenderSurfaceBitFlags) => void;
constructor(settings: RenderPropertyHandler_Settings)
{
if(!settings) throw 'You must supply a settings object';
if(!settings.property) throw 'The settings must specify the property';
if(!settings.surfaces) throw 'The settings must specify the surfaces flags';
if(!settings.hasChangedCallback) throw 'The settings must specify a hasChanged callback';
if(!settings.headingKey && !settings.labelKey) throw 'The settings must specify either a heading or a label key';
if(!settings.alignment) settings.alignment = VRS.Alignment.Left;
if(!settings.tooltipChangedCallback) settings.tooltipChangedCallback = settings.hasChangedCallback;
this.property = settings.property;
this.surfaces = settings.surfaces;
this.headingKey = settings.headingKey || settings.labelKey;
this.labelKey = settings.labelKey || settings.headingKey;
this.optionsLabelKey = settings.optionsLabelKey || settings.labelKey;
this.headingAlignment = settings.headingAlignment || settings.alignment;
this.contentAlignment = settings.contentAlignment || settings.alignment;
this.fixedWidth = settings.fixedWidth || function() { return null; };
this.hasChangedCallback = settings.hasChangedCallback;
this.contentCallback = settings.contentCallback;
this.renderCallback = settings.renderCallback;
this.useHtmlRendering = settings.useHtmlRendering || function() { return !!settings.renderCallback; };
this.usesDisplayUnit = settings.usesDisplayUnit || function() { return false; };
this.tooltipChangedCallback = settings.tooltipChangedCallback;
this.tooltipCallback = settings.tooltipCallback;
this.suppressLabelCallback = settings.suppressLabelCallback || function() { return false; };
this.isMultiLine = !!settings.isMultiLine;
this.sortableField = settings.sortableField || VRS.AircraftListSortableField.None;
this.createWidget = settings.createWidget;
this.renderWidget = settings.renderWidget;
this.destroyWidget = settings.destroyWidget;
this._SuspendWidget = settings.suspendWidget;
}
/**
* Returns true if the property can be rendered onto the VRS.RenderSurface passed across.
*/
isSurfaceSupported(surface: RenderSurfaceBitFlags) : boolean
{
return (this.surfaces & surface) !== 0;
}
/**
* Returns true if the property is rendered using a jQuery UI widget.
*/
isWidgetProperty() : boolean
{
return !!this.createWidget;
}
/**
* Called when a widget is being suspended or resumed.
*/
suspendWidget(jQueryElement: JQuery, surface: RenderSurfaceBitFlags, onOff: boolean)
{
if(this._SuspendWidget) {
this._SuspendWidget(jQueryElement, surface, onOff);
}
}
/**
* Call after creating an element for a property - this lets renderers that use a jQuery widget create their widget.
*/
createWidgetInDom(domElement: HTMLElement, surface: RenderSurfaceBitFlags, options: AircraftRenderOptions)
{
if(this.isWidgetProperty()) {
this.createWidget($(domElement), options, surface);
}
}
/**
* Call after creating an element for a property - this lets renderers that use a jQuery widget create their widget.
*/
createWidgetInJQuery(jQueryElement: JQuery, surface: RenderSurfaceBitFlags, options?: AircraftRenderOptions)
{
if(this.isWidgetProperty()) {
this.createWidget(jQueryElement, options, surface);
}
}
/**
* Call before destroying an element for a property - this lets renderers that use a jQuery widget destroy their widget.
*/
destroyWidgetInDom(domElement: HTMLElement, surface: RenderSurfaceBitFlags)
{
if(this.isWidgetProperty()) {
this.destroyWidget($(domElement), surface);
}
}
/**
* Call before destroying an element for a property - this lets renderers that use a jQuery widget destroy their widget.
*/
destroyWidgetInJQuery(jQueryElement: JQuery, surface: RenderSurfaceBitFlags)
{
if(this.isWidgetProperty()) {
this.destroyWidget(jQueryElement, surface);
}
}
/**
* Renders a property to a native DOM element and returns the new content of the element.
*/
renderToDom(domElement: HTMLElement, surface: RenderSurfaceBitFlags, aircraft: Aircraft, options: AircraftRenderOptions, compareContent?: boolean, existingContent?: string) : string
{
var newContent: string;
if(this.useHtmlRendering(aircraft, options, surface)) {
newContent = this.renderCallback(aircraft, options, surface);
if(!compareContent || newContent !== existingContent) {
domElement.innerHTML = newContent;
}
} else if(this.isWidgetProperty()) {
this.renderWidget($(domElement), aircraft, options, surface);
} else {
newContent = this.contentCallback(aircraft, options, surface);
if(!compareContent || newContent !== existingContent) {
domElement.textContent = newContent;
}
}
return newContent;
}
/**
* Renders a property to a jQuery element.
*/
renderToJQuery(jQueryElement: JQuery, surface: RenderSurfaceBitFlags, aircraft: Aircraft, options: AircraftRenderOptions)
{
if(this.useHtmlRendering(aircraft, options, surface)) {
jQueryElement.html(this.renderCallback(aircraft, options, surface));
} else if(this.isWidgetProperty()) {
this.renderWidget(jQueryElement, aircraft, options, surface);
} else {
jQueryElement.text(this.contentCallback(aircraft, options, surface));
}
}
/**
* Renders the tooltip for the aircraft to the DOM element. Returns true if the element now has a tooltip.
*/
renderTooltipToDom(domElement: HTMLElement, surface: RenderSurfaceBitFlags, aircraft: Aircraft, options: AircraftRenderOptions) : boolean
{
var tooltipText = this.tooltipCallback ? this.tooltipCallback(aircraft, options, surface) || '' : '';
if(tooltipText) {
domElement.setAttribute('title', tooltipText);
} else {
domElement.removeAttribute('title');
}
return !!tooltipText;
}
/**
* Renders the tooltip for the aircraft to the DOM element. Returns true if the element now has a tooltip.
*/
renderTooltipToJQuery(jQueryElement: JQuery, surface: RenderSurfaceBitFlags, aircraft: Aircraft, options: AircraftRenderOptions)
{
var tooltipText = this.tooltipCallback ? this.tooltipCallback(aircraft, options, surface) || '' : '';
jQueryElement.prop('title', tooltipText);
return !!tooltipText;
}
}
/**
* The associative array of VRS.RenderPropertyHandler objects indexed by VRS.RenderProperty.
* @type {Object.<VRS.RenderProperty, VRS.RenderPropertyHandler>}
*/
export var renderPropertyHandlers: { [index: string /* RenderPropertyEnum */]: RenderPropertyHandler } = VRS.renderPropertyHandlers || {};
/*
* NORMAL PROPERTY HANDLERS
*/
VRS.renderPropertyHandlers[VRS.RenderProperty.AirPressure] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AirPressure,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListAirPressure',
labelKey: 'AirPressure',
sortableField: VRS.AircraftListSortableField.AirPressure,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.airPressureInHg.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatAirPressureInHg(
options.unitDisplayPreferences.getPressureUnit(),
options.showUnits
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Pressure; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.AirportDataThumbnails] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AirportDataThumbnails,
surfaces: VRS.RenderSurface.DetailBody,
labelKey: 'AirportDataThumbnails',
alignment: VRS.Alignment.Centre,
hasChangedCallback: function(aircraft) { return aircraft.icao.chg || aircraft.airportDataThumbnails.chg; },
suppressLabelCallback: function(surface) { return true; },
renderCallback: function(aircraft, options) {
var result = '';
if(!aircraft.airportDataThumbnails.chg) {
aircraft.fetchAirportDataThumbnails(options.airportDataThumbnails);
} else {
result = aircraft.formatAirportDataThumbnails(true);
}
return result;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Altitude] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Altitude,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListAltitude',
labelKey: 'Altitude',
sortableField: VRS.AircraftListSortableField.Altitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.geometricAltitude.chg || aircraft.isOnGround.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatMixedAltitude(
options.unitDisplayPreferences.getUsePressureAltitude(),
options.unitDisplayPreferences.getHeightUnit(),
options.distinguishOnGround,
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeBarometric] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeBarometric,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListPressureAltitude',
labelKey: 'PressureAltitude',
sortableField: VRS.AircraftListSortableField.AltitudeBarometric,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.isOnGround.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatAltitude(
options.unitDisplayPreferences.getHeightUnit(),
options.distinguishOnGround,
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeGeometric] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeGeometric,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListGeometricAltitude',
labelKey: 'GeometricAltitude',
sortableField: VRS.AircraftListSortableField.AltitudeGeometric,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.geometricAltitude.chg || aircraft.isOnGround.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatGeometricAltitude(
options.unitDisplayPreferences.getHeightUnit(),
options.distinguishOnGround,
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height; }
});
/*
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeAndSpeedGraph] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeAndSpeedGraph,
surfaces: VRS.RenderSurface.DetailBody,
labelKey: 'AltitudeAndSpeedGraph',
isMultiLine: true,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.speed.chg; },
contentCallback: function() { return '[ Altitude and speed graph goes here - one day :) ]'}
});
*/
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeAndVerticalSpeed] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeAndVerticalSpeed,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListAltitudeAndVerticalSpeed',
labelKey: 'AltitudeAndVerticalSpeed',
sortableField: VRS.AircraftListSortableField.Altitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.isOnGround.chg || aircraft.verticalSpeed.chg; },
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height || displayUnitDependency === VRS.DisplayUnitDependency.VsiSeconds; },
renderCallback: function(aircraft, options) {
return VRS.format.stackedValues(
aircraft.formatAltitude(options.unitDisplayPreferences.getHeightUnit(), options.distinguishOnGround, options.showUnits, options.unitDisplayPreferences.getShowAltitudeType()),
aircraft.formatVerticalSpeed(options.unitDisplayPreferences.getHeightUnit(), options.unitDisplayPreferences.getShowVerticalSpeedPerSecond(), options.showUnits, options.unitDisplayPreferences.getShowVerticalSpeedType())
);
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeType] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeType,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListAltitudeType',
labelKey: 'AltitudeType',
sortableField: VRS.AircraftListSortableField.AltitudeType,
hasChangedCallback: function(aircraft) { return aircraft.altitudeType.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatAltitudeType(); }
});
/*
VRS.renderPropertyHandlers[VRS.RenderProperty.AltitudeGraph] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AltitudeGraph,
surfaces: VRS.RenderSurface.DetailBody,
labelKey: 'AltitudeGraph',
isMultiLine: true,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg; },
contentCallback: function() { return '[ Altitude graph goes here - one day :) ]'}
});
*/
VRS.renderPropertyHandlers[VRS.RenderProperty.AverageSignalLevel] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.AverageSignalLevel,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListAverageSignalLevel',
labelKey: 'AverageSignalLevel',
alignment: VRS.Alignment.Right,
sortableField: VRS.AircraftListSortableField.AverageSignalLevel,
hasChangedCallback: function(aircraft) { return aircraft.averageSignalLevel.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatAverageSignalLevel(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Bearing] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Bearing,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListBearing',
labelKey: 'Bearing',
sortableField: VRS.AircraftListSortableField.Bearing,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.bearingFromHere.chg; },
useHtmlRendering: function(aircraft, options, surface) { return surface === VRS.RenderSurface.DetailHead; },
contentCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.List:
case VRS.RenderSurface.DetailBody:
case VRS.RenderSurface.InfoWindow:
return aircraft.formatBearingFromHere(options.showUnits);
default:
throw 'Unexpected surface ' + surface;
}
},
renderCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.DetailHead:
return aircraft.formatBearingFromHereImage();
default:
throw 'Unexpected surface ' + surface;
}
},
tooltipCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.DetailHead:
return aircraft.formatBearingFromHere(options.showUnits);
default:
return '';
}
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Callsign] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Callsign,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListCallsign',
labelKey: 'Callsign',
sortableField: VRS.AircraftListSortableField.Callsign,
hasChangedCallback: function(aircraft) { return aircraft.callsign.chg || aircraft.callsignSuspect.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatCallsign(options.flagUncertainCallsigns); },
tooltipChangedCallback: function(aircraft) { return aircraft.hasRouteChanged() || aircraft.callsignSuspect.chg; },
tooltipCallback: function(aircraft, options) {
var result = aircraft.formatRouteFull();
if(options.flagUncertainCallsigns && aircraft.callsignSuspect.val) result += '. ' + VRS.$$.CallsignMayNotBeCorrect + '.';
return result;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.CallsignAndShortRoute] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.CallsignAndShortRoute,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListCallsign',
labelKey: 'CallsignAndShortRoute',
sortableField: VRS.AircraftListSortableField.Callsign,
hasChangedCallback: function(aircraft) { return aircraft.callsign.chg || aircraft.callsignSuspect.chg || aircraft.hasRouteChanged(); },
renderCallback: function(aircraft, options) {
return VRS.format.stackedValues(
aircraft.formatCallsign(options.flagUncertainCallsigns),
aircraft.formatRouteShort()
);
},
tooltipChangedCallback: function(aircraft) { return aircraft.hasRouteChanged() || aircraft.callsignSuspect.chg; },
tooltipCallback: function(aircraft, options) {
var result = aircraft.formatRouteFull();
if(options.flagUncertainCallsigns && aircraft.callsignSuspect.val) result += '. ' + VRS.$$.CallsignMayNotBeCorrect + '.';
return result;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.CivOrMil] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.CivOrMil,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListCivOrMil',
labelKey: 'CivilOrMilitary',
sortableField: VRS.AircraftListSortableField.CivOrMil,
hasChangedCallback: function(aircraft) { return aircraft.isMilitary.chg; },
contentCallback: function(aircraft) { return aircraft.formatIsMilitary(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.CountMessages] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.CountMessages,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListCountMessages',
labelKey: 'MessageCount',
sortableField: VRS.AircraftListSortableField.CountMessages,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.countMessages.chg; },
contentCallback: function(aircraft) { return aircraft.formatCountMessages(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Country] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Country,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListCountry',
labelKey: 'Country',
sortableField: VRS.AircraftListSortableField.Country,
hasChangedCallback: function(aircraft) { return aircraft.country.chg; },
contentCallback: function(aircraft) { return aircraft.formatCountry(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Distance] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Distance,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListDistance',
labelKey: 'Distance',
sortableField: VRS.AircraftListSortableField.Distance,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.distanceFromHereKm.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatDistanceFromHere(options.unitDisplayPreferences.getDistanceUnit(), options.showUnits); },
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Distance; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Engines] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Engines,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListEngines',
labelKey: 'Engines',
hasChangedCallback: function(aircraft) { return aircraft.engineType.chg || aircraft.countEngines.chg; },
contentCallback: function(aircraft) { return aircraft.formatEngines(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.FlightLevel] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.FlightLevel,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListFlightLevel',
labelKey: 'FlightLevel',
sortableField: VRS.AircraftListSortableField.Altitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.isOnGround.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatFlightLevel(
options.unitDisplayPreferences.getFlightLevelTransitionAltitude(),
options.unitDisplayPreferences.getFlightLevelTransitionHeightUnit(),
options.unitDisplayPreferences.getFlightLevelHeightUnit(),
options.unitDisplayPreferences.getHeightUnit(),
options.distinguishOnGround,
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
); },
usesDisplayUnit: function(displayUnitDependency) {
switch(displayUnitDependency) {
case VRS.DisplayUnitDependency.Height:
case VRS.DisplayUnitDependency.FLHeightUnit:
case VRS.DisplayUnitDependency.FLTransitionAltitude:
case VRS.DisplayUnitDependency.FLTransitionHeightUnit:
return true;
}
return false;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.FlightLevelAndVerticalSpeed] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.FlightLevelAndVerticalSpeed,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListFlightLevelAndVerticalSpeed',
labelKey: 'FlightLevelAndVerticalSpeed',
sortableField: VRS.AircraftListSortableField.Altitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.altitude.chg || aircraft.isOnGround.chg || aircraft.verticalSpeed.chg; },
renderCallback: function(aircraft, options) {
return VRS.format.stackedValues(
aircraft.formatFlightLevel(
options.unitDisplayPreferences.getFlightLevelTransitionAltitude(),
options.unitDisplayPreferences.getFlightLevelTransitionHeightUnit(),
options.unitDisplayPreferences.getFlightLevelHeightUnit(),
options.unitDisplayPreferences.getHeightUnit(),
options.distinguishOnGround,
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
),
aircraft.formatVerticalSpeed(
options.unitDisplayPreferences.getHeightUnit(),
options.unitDisplayPreferences.getShowVerticalSpeedPerSecond(),
options.showUnits,
options.unitDisplayPreferences.getShowVerticalSpeedType()
)
);
},
usesDisplayUnit: function(displayUnitDependency) {
switch(displayUnitDependency) {
case VRS.DisplayUnitDependency.Height:
case VRS.DisplayUnitDependency.FLHeightUnit:
case VRS.DisplayUnitDependency.FLTransitionAltitude:
case VRS.DisplayUnitDependency.FLTransitionHeightUnit:
case VRS.DisplayUnitDependency.VsiSeconds:
return true;
}
return false;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.FlightsCount] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.FlightsCount,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListFlightsCount',
labelKey: 'FlightsCount',
sortableField: VRS.AircraftListSortableField.FlightsCount,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.countFlights.chg; },
contentCallback: function(aircraft) { return aircraft.formatCountFlights(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Heading] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Heading,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListHeading',
labelKey: 'Heading',
sortableField: VRS.AircraftListSortableField.Heading,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.heading.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatHeading(options.showUnits, options.unitDisplayPreferences.getShowTrackType()); },
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Angle; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.HeadingType] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.HeadingType,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListHeadingType',
labelKey: 'HeadingType',
sortableField: VRS.AircraftListSortableField.HeadingType,
hasChangedCallback: function(aircraft) { return aircraft.headingIsTrue.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatHeadingType(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Icao] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Icao,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListIcao',
labelKey: 'Icao',
sortableField: VRS.AircraftListSortableField.Icao,
hasChangedCallback: function(aircraft) { return aircraft.icao.chg; },
contentCallback: function(aircraft) { return aircraft.formatIcao(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.IdentActive] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.IdentActive,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListIdentActive',
labelKey: 'IdentActive',
hasChangedCallback: function(aircraft) { return aircraft.identActive.chg; },
contentCallback: function(aircraft, options, surface) { return surface === VRS.RenderSurface.Marker ? aircraft.formatIdent() : aircraft.formatIdentActive(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Interesting] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Interesting,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListInteresting',
labelKey: 'Interesting',
hasChangedCallback: function(aircraft) { return aircraft.userInterested.chg; },
contentCallback: function(aircraft) { return aircraft.formatUserInterested(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Latitude] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Latitude,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListLatitude',
labelKey: 'Latitude',
sortableField: VRS.AircraftListSortableField.Latitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.latitude.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatLatitude(options.showUnits); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Longitude] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Longitude,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListLongitude',
labelKey: 'Longitude',
sortableField: VRS.AircraftListSortableField.Longitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.longitude.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatLongitude(options.showUnits); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Manufacturer] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Manufacturer,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListManufacturer',
labelKey: 'Manufacturer',
sortableField: VRS.AircraftListSortableField.Manufacturer,
hasChangedCallback: function(aircraft) { return aircraft.manufacturer.chg; },
contentCallback: function(aircraft) { return aircraft.formatManufacturer(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Mlat] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Mlat,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListMlat',
labelKey: 'Mlat',
sortableField: VRS.AircraftListSortableField.Mlat,
hasChangedCallback: function(aircraft) { return aircraft.isMlat.chg; },
contentCallback: function(aircraft) { return aircraft.formatIsMlat(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Model] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Model,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListModel',
labelKey: 'Model',
sortableField: VRS.AircraftListSortableField.Model,
hasChangedCallback: function(aircraft) { return aircraft.model.chg; },
contentCallback: function(aircraft) { return aircraft.formatModel(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.ModelIcao] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.ModelIcao,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListModelIcao',
labelKey: 'ModelIcao',
sortableField: VRS.AircraftListSortableField.ModelIcao,
hasChangedCallback: function(aircraft) { return aircraft.modelIcao.chg; },
contentCallback: function(aircraft) { return aircraft.formatModelIcao(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.None] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.None,
surfaces: VRS.RenderSurface.Marker,
headingKey: 'None',
labelKey: 'None',
hasChangedCallback: function() { return false; },
contentCallback: function() { return ''; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Operator] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Operator,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListOperator',
labelKey: 'Operator',
sortableField: VRS.AircraftListSortableField.Operator,
hasChangedCallback: function(aircraft) { return aircraft.operator.chg; },
contentCallback: function(aircraft) { return aircraft.formatOperator(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.OperatorFlag] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.OperatorFlag,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListOperatorFlag',
labelKey: 'OperatorFlag',
sortableField: VRS.AircraftListSortableField.OperatorIcao,
headingAlignment: VRS.Alignment.Centre,
suppressLabelCallback: function() { return true; },
fixedWidth: function() { return VRS.globalOptions.aircraftOperatorFlagSize.width.toString() + 'px'; },
hasChangedCallback: function(aircraft) { return aircraft.operatorIcao.chg || aircraft.icao.chg || aircraft.registration.chg; },
renderCallback: function(aircraft) { return aircraft.formatOperatorIcaoImageHtml(); },
tooltipChangedCallback: function(aircraft) { return aircraft.operatorIcao.chg || aircraft.operator.chg; },
tooltipCallback: function(aircraft) { return aircraft.formatOperatorIcaoAndName(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.OperatorIcao] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.OperatorIcao,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListOperatorIcao',
labelKey: 'OperatorCode',
sortableField: VRS.AircraftListSortableField.OperatorIcao,
hasChangedCallback: function(aircraft) { return aircraft.operatorIcao.chg; },
contentCallback: function(aircraft) { return aircraft.formatOperatorIcao(); },
tooltipChangedCallback: function(aircraft) { return aircraft.operator.chg; },
tooltipCallback: function(aircraft) { return aircraft.formatOperator(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Picture] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Picture,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListPicture',
labelKey: 'Picture',
headingAlignment: VRS.Alignment.Centre,
fixedWidth: function(/** VRS.RenderSurface */renderSurface) {
switch(renderSurface) {
case VRS.RenderSurface.InfoWindow:
return VRS.globalOptions.aircraftPictureSizeInfoWindow.width.toString() + 'px';
case VRS.RenderSurface.List:
return VRS.globalOptions.aircraftPictureSizeList.width.toString() + 'px';
default:
return null;
}
},
hasChangedCallback: function(aircraft) { return aircraft.hasPicture.chg; },
suppressLabelCallback: function(surface) { return surface === VRS.RenderSurface.DetailBody; },
renderCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.InfoWindow:
return aircraft.formatPictureHtml(VRS.globalOptions.aircraftPictureSizeInfoWindow);
case VRS.RenderSurface.List:
return aircraft.formatPictureHtml(VRS.globalOptions.aircraftPictureSizeList, true, false, VRS.globalOptions.aircraftPictureSizeList);
case VRS.RenderSurface.DetailBody:
return aircraft.formatPictureHtml(
!VRS.globalOptions.isMobile ? VRS.globalOptions.aircraftPictureSizeDesktopDetail : VRS.globalOptions.aircraftPictureSizeMobileDetail,
false, true
);
default:
throw 'Unexpected surface ' + surface;
}
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.PositionOnMap] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.PositionOnMap,
surfaces: VRS.RenderSurface.DetailBody,
headingKey: 'Map',
labelKey: 'Map',
suppressLabelCallback: function() { return true; },
hasChangedCallback: function(aircraft) { return aircraft.latitude.chg || aircraft.longitude.chg; },
createWidget: function(element, options, surface) {
if(surface === VRS.RenderSurface.DetailBody && !VRS.jQueryUIHelper.getAircraftPositionMapPlugin(element)) {
(<any>element).vrsAircraftPositonMap(VRS.jQueryUIHelper.getAircraftPositionMapOptions(<AircraftPositionMapPlugin_Options>{
plotterOptions: options.plotterOptions,
mirrorMapJQ: options.mirrorMapJQ,
mapOptionOverrides: <IMapOptions>{
draggable: false,
showMapTypeControl: false
},
unitDisplayPreferences: options.unitDisplayPreferences,
autoHideNoPosition: true
}));
}
},
destroyWidget: function(element, surface) {
var aircraftPositionMap = VRS.jQueryUIHelper.getAircraftPositionMapPlugin(element);
if(surface === VRS.RenderSurface.DetailBody && aircraftPositionMap) {
aircraftPositionMap.destroy();
}
},
renderWidget: function(element, aircraft, options, surface) {
var aircraftPositionMap = VRS.jQueryUIHelper.getAircraftPositionMapPlugin(element);
if(surface === VRS.RenderSurface.DetailBody && aircraftPositionMap) {
aircraftPositionMap.renderAircraft(aircraft, options.aircraftList ? options.aircraftList.getSelectedAircraft() === aircraft : false);
}
},
suspendWidget: function(element, surface, onOff)
{
var aircraftPositionMap = VRS.jQueryUIHelper.getAircraftPositionMapPlugin(element);
aircraftPositionMap.suspend(onOff);
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Receiver] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Receiver,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListReceiver',
labelKey: 'Receiver',
sortableField: VRS.AircraftListSortableField.Receiver,
hasChangedCallback: function(aircraft) { return aircraft.receiverId.chg; },
contentCallback: function(aircraft) { return aircraft.formatReceiver(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Registration] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Registration,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListRegistration',
labelKey: 'Registration',
sortableField: VRS.AircraftListSortableField.Registration,
hasChangedCallback: function(aircraft) { return aircraft.registration.chg; },
contentCallback: function(aircraft) { return aircraft.formatRegistration(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.RegistrationAndIcao] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.RegistrationAndIcao,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListRegistration',
labelKey: 'RegistrationAndIcao',
sortableField: VRS.AircraftListSortableField.Registration,
hasChangedCallback: function(aircraft) { return aircraft.registration.chg || aircraft.icao.chg; },
renderCallback: function(aircraft) {
return VRS.format.stackedValues(
aircraft.formatRegistration(),
aircraft.formatIcao()
);
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.RouteShort] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.RouteShort,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListRoute',
labelKey: 'Route',
optionsLabelKey: 'RouteShort',
hasChangedCallback: function(aircraft) { return aircraft.callsign.chg || aircraft.hasRouteChanged(); },
useHtmlRendering: function(aircraft, options, surface) { return surface === VRS.RenderSurface.DetailBody; },
contentCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.InfoWindow:
case VRS.RenderSurface.List:
case VRS.RenderSurface.Marker: return aircraft.formatRouteShort();
default: throw 'Unexpected surface ' + surface;
}
},
renderCallback: function(aircraft, options, surface) {
switch(surface) {
case VRS.RenderSurface.DetailBody: return aircraft.formatRouteShort(false, true);
default: throw 'Unexpected surface ' + surface;
}
},
tooltipCallback: function(aircraft) { return aircraft.formatRouteFull(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.RouteFull] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.RouteFull,
surfaces: VRS.RenderSurface.DetailBody,
headingKey: 'ListRoute',
labelKey: 'Route',
optionsLabelKey: 'RouteFull',
isMultiLine: true,
hasChangedCallback: function(aircraft) { return aircraft.callsign.chg || aircraft.hasRouteChanged(); },
renderCallback: function(aircraft, options) { return aircraft.formatRouteMultiLine(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Serial] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Serial,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSerialNumber',
labelKey: 'SerialNumber',
sortableField: VRS.AircraftListSortableField.Serial,
hasChangedCallback: function(aircraft) { return aircraft.serial.chg; },
contentCallback: function(aircraft) { return aircraft.formatSerial(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.SignalLevel] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.SignalLevel,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSignalLevel',
labelKey: 'SignalLevel',
optionsLabelKey: 'SignalLevel',
alignment: VRS.Alignment.Right,
sortableField: VRS.AircraftListSortableField.SignalLevel,
hasChangedCallback: function(aircraft) { return aircraft.signalLevel.chg; },
contentCallback: function(aircraft) { return aircraft.formatSignalLevel(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Silhouette] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Silhouette,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailHead + VRS.RenderSurface.InfoWindow,
headingKey: 'ListModelSilhouette',
labelKey: 'Silhouette',
sortableField: VRS.AircraftListSortableField.ModelIcao,
headingAlignment: VRS.Alignment.Centre,
suppressLabelCallback: function() { return true; },
fixedWidth: function() { return VRS.globalOptions.aircraftSilhouetteSize.width.toString() + 'px'; },
hasChangedCallback: function(aircraft) { return aircraft.modelIcao.chg || aircraft.icao.chg || aircraft.registration.chg; },
renderCallback: function(aircraft) { return aircraft.formatModelIcaoImageHtml(); },
tooltipChangedCallback: function(aircraft) { return aircraft.model.chg || aircraft.modelIcao.chg || aircraft.countEngines.chg || aircraft.engineType.chg || aircraft.species.chg || aircraft.wakeTurbulenceCat.chg; },
tooltipCallback: function(aircraft) { return aircraft.formatModelIcaoNameAndDetail(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.SilhouetteAndOpFlag] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.SilhouetteAndOpFlag,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListModelSilhouetteAndOpFlag',
labelKey: 'SilhouetteAndOpFlag',
headingAlignment: VRS.Alignment.Centre,
sortableField: VRS.AircraftListSortableField.OperatorIcao,
fixedWidth: function() { return Math.max(VRS.globalOptions.aircraftSilhouetteSize.width, VRS.globalOptions.aircraftOperatorFlagSize.width).toString() + 'px'; },
hasChangedCallback: function(aircraft) { return aircraft.modelIcao.chg || aircraft.operatorIcao.chg || aircraft.registration.chg; },
renderCallback: function(aircraft) { return aircraft.formatModelIcaoImageHtml() + aircraft.formatOperatorIcaoImageHtml(); },
tooltipChangedCallback: function(aircraft) { return aircraft.model.chg || aircraft.modelIcao.chg || aircraft.countEngines.chg || aircraft.engineType.chg || aircraft.species.chg || aircraft.wakeTurbulenceCat.chg || aircraft.operatorIcao.chg || aircraft.operator.chg; },
tooltipCallback: function(aircraft) {
var silhouetteTooltip = aircraft.formatModelIcaoNameAndDetail();
var opFlagTooltip = aircraft.formatOperatorIcaoAndName();
return silhouetteTooltip && opFlagTooltip ? silhouetteTooltip + '. ' + opFlagTooltip : silhouetteTooltip ? silhouetteTooltip : opFlagTooltip;
}
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Species] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Species,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSpecies',
labelKey: 'Species',
hasChangedCallback: function(aircraft) { return aircraft.species.chg; },
contentCallback: function(aircraft) { return aircraft.formatSpecies(false); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Speed] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Speed,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSpeed',
labelKey: 'Speed',
sortableField: VRS.AircraftListSortableField.Speed,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.speed.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatSpeed(
options.unitDisplayPreferences.getSpeedUnit(),
options.showUnits,
options.unitDisplayPreferences.getShowSpeedType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Speed; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.SpeedType] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.SpeedType,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSpeedType',
labelKey: 'SpeedType',
sortableField: VRS.AircraftListSortableField.SpeedType,
hasChangedCallback: function(aircraft) { return aircraft.speedType.chg; },
contentCallback: function(aircraft, /** VRS_OPTIONS_AIRCRAFTRENDER */ options) { return aircraft.formatSpeedType(); }
});
/*
VRS.renderPropertyHandlers[VRS.RenderProperty.SpeedGraph] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.SpeedGraph,
surfaces: VRS.RenderSurface.DetailBody,
labelKey: 'SpeedGraph',
isMultiLine: true,
hasChangedCallback: function(aircraft) { return aircraft.speed.chg; },
contentCallback: function() { return '[ Speed graph goes here - one day :) ]'}
});
*/
VRS.renderPropertyHandlers[VRS.RenderProperty.Squawk] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Squawk,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListSquawk',
labelKey: 'Squawk',
sortableField: VRS.AircraftListSortableField.Squawk,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.squawk.chg; },
contentCallback: function(aircraft) { return aircraft.formatSquawk(); },
tooltipCallback: function(aircraft, options, surface) { return aircraft.formatSquawkDescription(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.SquawkAndIdent] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.SquawkAndIdent,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListSquawk',
labelKey: 'SquawkAndIdent',
sortableField: VRS.AircraftListSortableField.Squawk,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.squawk.chg || aircraft.identActive.chg; },
renderCallback: function(aircraft) {
return VRS.format.stackedValues(
aircraft.formatSquawk(),
aircraft.formatIdent()
);
},
});
VRS.renderPropertyHandlers[VRS.RenderProperty.TargetAltitude] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.TargetAltitude,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListTargetAltitude',
labelKey: 'TargetAltitude',
sortableField: VRS.AircraftListSortableField.TargetAltitude,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.targetAltitude.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatTargetAltitude(
options.unitDisplayPreferences.getHeightUnit(),
options.showUnits,
options.unitDisplayPreferences.getShowAltitudeType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.TargetHeading] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.TargetHeading,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListTargetHeading',
labelKey: 'TargetHeading',
sortableField: VRS.AircraftListSortableField.TargetHeading,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.targetHeading.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatTargetHeading(
options.showUnits,
options.unitDisplayPreferences.getShowTrackType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Angle; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.TimeTracked] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.TimeTracked,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListDuration',
labelKey: 'TimeTracked',
sortableField: VRS.AircraftListSortableField.TimeTracked,
alignment: VRS.Alignment.Right,
hasChangedCallback: function() { return true; },
contentCallback: function(aircraft) { return aircraft.formatSecondsTracked(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.PositionAgeSeconds] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.PositionAgeSeconds,
surfaces: VRS.RenderSurface.DetailBody | VRS.RenderSurface.InfoWindow | VRS.RenderSurface.List | VRS.RenderSurface.Marker,
headingKey: 'ListPositionAge',
labelKey: 'PositionAge',
sortableField: VRS.AircraftListSortableField.PositionAgeSeconds,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft: Aircraft) { return aircraft.positionAgeSeconds.chg; },
contentCallback: function(aircraft) { return aircraft.formatPositionAgeSeconds(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Tisb] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Tisb,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListTisb',
labelKey: 'Tisb',
hasChangedCallback: function(aircraft) { return aircraft.isTisb.chg; },
contentCallback: function(aircraft) { return aircraft.formatIsTisb(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.TransponderType] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.TransponderType,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListTransponderType',
labelKey: 'TransponderType',
sortableField: VRS.AircraftListSortableField.TransponderType,
hasChangedCallback: function(aircraft) { return aircraft.transponderType.chg; },
contentCallback: function(aircraft) { return aircraft.formatTransponderType(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.TransponderTypeFlag] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.TransponderTypeFlag,
surfaces: VRS.RenderSurface.List,
headingKey: 'ListTransponderTypeFlag',
labelKey: 'TransponderTypeFlag',
sortableField: VRS.AircraftListSortableField.TransponderType,
suppressLabelCallback: function() { return true; },
fixedWidth: function() { return VRS.globalOptions.aircraftTransponderTypeSize.width.toString() + 'px'; },
hasChangedCallback: function(aircraft) { return aircraft.transponderType.chg; },
renderCallback: function(aircraft) { return aircraft.formatTransponderTypeImageHtml(); },
tooltipChangedCallback: function(aircraft) { return aircraft.transponderType.chg; },
tooltipCallback: function(aircraft) { return aircraft.formatTransponderType(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.UserNotes] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.UserNotes,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListNotes',
labelKey: 'Notes',
isMultiLine: true,
hasChangedCallback: function(aircraft) { return aircraft.userNotes.chg; },
useHtmlRendering: function(aircraft, options, surface) { return surface === VRS.RenderSurface.DetailBody || surface === VRS.RenderSurface.InfoWindow; },
contentCallback: function(aircraft) { return aircraft.formatUserNotes(); },
renderCallback: function(aircraft) { return aircraft.formatUserNotesMultiline(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.UserTag] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.UserTag,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow + VRS.RenderSurface.Marker,
headingKey: 'ListUserTag',
labelKey: 'UserTag',
sortableField: VRS.AircraftListSortableField.UserTag,
hasChangedCallback: function(aircraft) { return aircraft.userTag.chg; },
contentCallback: function(aircraft) { return aircraft.formatUserTag(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.VerticalSpeed] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.VerticalSpeed,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListVerticalSpeed',
labelKey: 'VerticalSpeed',
sortableField: VRS.AircraftListSortableField.VerticalSpeed,
alignment: VRS.Alignment.Right,
hasChangedCallback: function(aircraft) { return aircraft.verticalSpeed.chg; },
contentCallback: function(aircraft, options) {
return aircraft.formatVerticalSpeed(
options.unitDisplayPreferences.getHeightUnit(),
options.unitDisplayPreferences.getShowVerticalSpeedPerSecond(),
options.showUnits,
options.unitDisplayPreferences.getShowVerticalSpeedType()
);
},
usesDisplayUnit: function(displayUnitDependency) { return displayUnitDependency === VRS.DisplayUnitDependency.Height || displayUnitDependency === VRS.DisplayUnitDependency.VsiSeconds; }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.VerticalSpeedType] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.VerticalSpeedType,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListVerticalSpeedType',
labelKey: 'VerticalSpeedType',
sortableField: VRS.AircraftListSortableField.VerticalSpeedType,
hasChangedCallback: function(aircraft) { return aircraft.verticalSpeedType.chg; },
contentCallback: function(aircraft, options) { return aircraft.formatVerticalSpeedType(); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.Wtc] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.Wtc,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.InfoWindow,
headingKey: 'ListWtc',
labelKey: 'WakeTurbulenceCategory',
hasChangedCallback: function(aircraft) { return aircraft.wakeTurbulenceCat.chg; },
contentCallback: function(aircraft) { return aircraft.formatWakeTurbulenceCat(false, false); },
tooltipCallback: function(aircraft) { return aircraft.formatWakeTurbulenceCat(true, true); }
});
VRS.renderPropertyHandlers[VRS.RenderProperty.YearBuilt] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.YearBuilt,
surfaces: VRS.RenderSurface.List + VRS.RenderSurface.DetailBody + VRS.RenderSurface.Marker + VRS.RenderSurface.InfoWindow,
headingKey: 'ListYearBuilt',
labelKey: 'YearBuilt',
sortableField: VRS.AircraftListSortableField.YearBuilt,
hasChangedCallback: function(aircraft) { return aircraft.yearBuilt.chg; },
contentCallback: function(aircraft) { return aircraft.formatYearBuilt(); }
});
/*
* PROPERTY HANDLERS THAT DEPEND ON OTHER PROPERTY HANDLERS BEING REGISTERED BEFORE THEM
*/
var pictureHandler = VRS.renderPropertyHandlers[VRS.RenderProperty.Picture];
var airportDataThumbnailsHandler = VRS.renderPropertyHandlers[VRS.RenderProperty.AirportDataThumbnails];
if(pictureHandler && airportDataThumbnailsHandler) {
VRS.renderPropertyHandlers[VRS.RenderProperty.PictureOrThumbnails] = new VRS.RenderPropertyHandler({
property: VRS.RenderProperty.PictureOrThumbnails,
surfaces: VRS.RenderSurface.DetailBody,
labelKey: 'PictureOrThumbnails',
alignment: VRS.Alignment.Centre,
hasChangedCallback: function(aircraft) { return aircraft.icao.chg || aircraft.hasPicture.chg || aircraft.airportDataThumbnails.chg; },
suppressLabelCallback: function(surface) { return true; },
renderCallback: function(aircraft, options, surface) {
return aircraft.hasPicture.val ? pictureHandler.renderCallback(aircraft, options, surface)
: airportDataThumbnailsHandler.renderCallback(aircraft, options, surface);
}
});
}
/**
* The settings object to pass to RenderPropertyHelper.addRenderPropertiesListOptionsToPane
*/
export interface RenderPropertyHelper_ListOptionsToPane
{
/**
* The pane to add the field to.
*/
pane: OptionPane;
/**
* The VRS.RenderSurface to show properties for. The user will be able to select any property that can be rendered to this surface.
*/
surface: RenderSurfaceBitFlags;
/**
* The index into VRS.$$ for the field's label.
*/
fieldLabel: string;
/**
* A method that returns a list of VRS.RenderProperty strings representing the properties selected by the user.
*/
getList: () => RenderPropertyEnum[];
/**
* A method that takes a list of VRS.RenderProperty strings selected by the user and copies them to the object being configured.
*/
setList: (properties: RenderPropertyEnum[]) => void;
/**
* A method that can save the state of the object being configured.
*/
saveState: () => void;
}
/**
* A helper object that can deal with the mundane tasks when working with VRS.RenderPropertyHandler objects.
*/
export class RenderPropertyHelper
{
/**
* Removes invalid render properties from a list, usually called as part of loading a previous session's state.
*/
buildValidRenderPropertiesList(renderPropertiesList: RenderPropertyEnum[], surfaces: RenderSurfaceBitFlags[] = [], maximumProperties: number = -1) : RenderPropertyEnum[]
{
if(surfaces.length === 0) {
for(var surfaceName in VRS.RenderSurface) {
surfaces.push(VRS.RenderSurface[surfaceName]);
}
}
var countSurfaces = surfaces.length;
var validProperties: RenderPropertyEnum[] = [];
$.each(renderPropertiesList, function(idx, property) {
if(maximumProperties === -1 || validProperties.length <= maximumProperties) {
var handler = VRS.renderPropertyHandlers[property];
if(handler) {
var surfaceSupported = false;
for(var i = 0;i < countSurfaces;++i) {
surfaceSupported = handler.isSurfaceSupported(surfaces[i]);
if(surfaceSupported) {
validProperties.push(property);
break;
}
}
}
}
});
return validProperties;
}
/**
* Returns an array of render property handlers that support a surface.
*/
getHandlersForSurface(surface: RenderSurfaceBitFlags) : RenderPropertyHandler[]
{
var result: RenderPropertyHandler[] = [];
$.each(VRS.renderPropertyHandlers, function(idx, handler) {
if(handler instanceof VRS.RenderPropertyHandler && handler.isSurfaceSupported(surface)) {
result.push(handler);
}
});
return result;
}
/**
* Sorts the handlers array into labelKey order. Modifies the array passed in. Set putNoneFirst to true if the handler
* for RenderProperty.None should always appear before every other handler.
*/
sortHandlers(handlers: RenderPropertyHandler[], putNoneFirst: boolean)
{
putNoneFirst = !!putNoneFirst;
handlers.sort(function(lhs, rhs) {
if(putNoneFirst && lhs.property === VRS.RenderProperty.None) return rhs.property === VRS.RenderProperty.None ? 0 : -1;
if(putNoneFirst && rhs.property === VRS.RenderProperty.None) return 1;
var lhsText = VRS.globalisation.getText(lhs.labelKey) || '';
var rhsText = VRS.globalisation.getText(rhs.labelKey) || '';
return lhsText.localeCompare(rhsText);
});
}
/**
* Adds an orderedSubset field to an options pane that allows the user to configure a list of VRS.RenderProperty
* strings for a given VRS.RenderSurface.
*/
addRenderPropertiesListOptionsToPane(settings: RenderPropertyHelper_ListOptionsToPane) : OptionFieldOrderedSubset
{
var pane = settings.pane;
var surface = settings.surface;
var fieldLabel = settings.fieldLabel;
var getList = settings.getList;
var setList = settings.setList;
var saveState = settings.saveState;
var values: ValueText[] = [];
for(var propertyName in VRS.RenderProperty) {
var property = VRS.RenderProperty[propertyName];
var handler = VRS.renderPropertyHandlers[property];
if(!handler) throw 'Cannot find the handler for property ' + property;
if(!handler.isSurfaceSupported(surface)) continue;
values.push(new VRS.ValueText({ value: property, textKey: handler.optionsLabelKey }));
}
values.sort(function(lhs, rhs) {
var lhsText = lhs.getText() || '';
var rhsText = rhs.getText() || '';
return lhsText.localeCompare(rhsText);
});
var field = new VRS.OptionFieldOrderedSubset({
name: 'renderProperties',
labelKey: fieldLabel,
getValue: getList,
setValue: setList,
saveState: saveState,
values: values
});
pane.addField(field);
return field;
}
/**
* Returns a list of VRS.ValueText objects with the value set to the render property and the textKey set to the labelKey
* for every handler in the list passed across.
*/
createValueTextListForHandlers(handlers: RenderPropertyHandler[]) : ValueText[]
{
var result: ValueText[] = [];
$.each(handlers, function(idx, handler) {
result.push(new VRS.ValueText({
value: handler.property,
textKey: handler.labelKey
}));
});
return result;
}
}
/*
* Pre-builts
*/
export var renderPropertyHelper = new VRS.RenderPropertyHelper();
} | the_stack |
import { AnyListener, ArrayField, ObjectField, ErrorMap, Field, useForm } from "typed-react-form";
import tv, { SchemaType } from "typed-object-validator";
import React from "react";
import { VisualRender } from "./VisualRender";
// Example validation schema using typed-object-validator
const FormDataSchema = tv.object({
text: tv.string().min(1).max(30),
longText: tv.string(),
enum: tv.value("option1").or(tv.value("option2")).or(tv.value("option3")),
number: tv.number(),
boolean: tv.boolean(),
date: tv.date(),
tags: tv.array(tv.value("food").or(tv.value("tech").or(tv.value("sports")))),
object: tv.object({
childText: tv.string(),
childNumber: tv.number()
}),
array: tv.array(tv.string()),
customText: tv.string(),
objectArray: tv.array(
tv.object({
text: tv.string(),
boolean: tv.boolean()
})
)
});
type FormData = SchemaType<typeof FormDataSchema>;
function validate(data: FormData) {
return (FormDataSchema.validate(data) as ErrorMap<FormData, string>) ?? {};
}
export function ExampleForm() {
// Initial values as first argument
const form = useForm(
{
longText: "",
text: "",
customText: "nice",
number: 123,
enum: "option1",
boolean: false,
object: { childText: "", childNumber: 0 },
date: new Date(),
array: ["Item 1", "Item 2"],
objectArray: [
{ boolean: true, text: "Item 1" },
{ boolean: false, text: "Item 2" }
],
tags: ["food"]
} as FormData,
validate
);
function submit() {
console.log(form.values);
}
return (
<form
onSubmit={form.handleSubmit(submit)}
style={{ display: "grid", gridTemplateColumns: "125px 300px 1fr", width: "300px", margin: "2em", gap: "1em 2em", alignItems: "center" }}
>
{/* Show JSON representation */}
<AnyListener
form={form}
render={() => (
<pre style={{ gridColumn: "span 3" }}>
<VisualRender>{JSON.stringify(form.values, null, 2)}</VisualRender>
</pre>
)}
/>
{/* A simple text input */}
<label>Text</label>
<Field form={form} name="text" />
<pre>{`<Field form={form} name="fieldName" />`}</pre>
{/* A simple text input */}
<label>Deserializer text</label>
<Field form={form} name="customText" serializer={(e) => e?.toLowerCase()} deserializer={(e) => (e as string).toUpperCase()} />
<pre>{`<Field form={form} name="fieldName" />`}</pre>
{/* A textarea */}
<label>Long text</label>
<Field form={form} name="longText" as="textarea" />
<pre>{`<Field as="textarea" form={form} name="fieldName" />`}</pre>
{/* A number input */}
<label>Number</label>
<Field form={form} type="number" name="number" />
<pre>{`<Field form={form} type="number" name="fieldName" />`}</pre>
{/* A select input */}
<label>Enum</label>
<Field form={form} as="select" name="enum">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</Field>
<pre>{`
<Field as="select" form={form} name="fieldName">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</Field>
`}</pre>
{/* A checkbox input */}
<label>Boolean</label>
<Field form={form} type="checkbox" name="boolean" />
<pre>{`<Field form={form} type="checkbox" name="fieldName" />`}</pre>
<label>Tags</label>
<div>
<label>
Food
<Field form={form} type="checkbox" name="tags" value="food" />
</label>
<label>
Sports
<Field form={form} type="checkbox" name="tags" value="sports" />
</label>
<label>
Tech
<Field form={form} type="checkbox" name="tags" value="tech" />
</label>
</div>
<pre>{`<Field form={form} type="checkbox" name="fieldName" />`}</pre>
{/* A radio input */}
<label>Enum</label>
<div>
<label>
<Field form={form} type="radio" name="enum" value="option1" /> Option 1
</label>
<label>
<Field form={form} type="radio" name="enum" value="option2" /> Option 2
</label>
<label>
<Field form={form} type="radio" name="enum" value="option3" /> Option 3
</label>
</div>
<pre>{`
<Field form={form} type="radio" name="fieldName" value="option1" /> Option 1
<Field form={form} type="radio" name="fieldName" value="option2" /> Option 2
<Field form={form} type="radio" name="fieldName" value="option3" /> Option 3
`}</pre>
{/* A date input */}
<label>Date</label>
<Field form={form} type="date" name="date" />
<pre>{`<Field form={form} type="date" name="fieldName" />`}</pre>
{/* A date timestamp input */}
<label>Timestamp (number)</label>
<Field form={form} type="date" name="number" dateAsNumber />
<pre>{`<Field form={form} type="date" name="fieldName" dateAsNumber />`}</pre>
{/* Toggle field */}
<label>Toggle text</label>
<div>
<Field form={form} type="checkbox" name="text" setUndefinedOnUncheck value="" />
<Field form={form} name="text" hideWhenNull />
</div>
<pre>
{`
<Field form={form} type="checkbox" name="text" setUndefinedOnUncheck value="" />
<Field form={form} name="text" hideWhenNull />
`}
</pre>
{/* Object field */}
<label>Object field</label>
<div>
<ObjectField
form={form}
name="object"
render={(form) => (
<div style={{ background: "#0001" }}>
<p>Text</p>
<Field form={form} name="childText" />
<p>Number</p>
<Field form={form} name="childNumber" type="number" />
</div>
)}
/>
</div>
<pre>
{`
<ObjectField
form={form}
name="parentObjectFieldName"
render={(childForm) => (
<div>
<Field form={childForm} name="childFieldName" />
</div>
)}
/>
`}
</pre>
{/* Set object field to undefined on uncheck */}
<label>Toggle object</label>
<Field form={form} type="checkbox" name="object" setUndefinedOnUncheck value={{ childNumber: 0, childText: "" }} />
<pre>
{`
<Field
form={form}
type="checkbox"
name="fieldName"
setUndefinedOnUncheck
value={{ childDefaultFieldValue: "" }}
/> `}
</pre>
{/* Simple string array */}
<label>String array</label>
<ArrayField
form={form}
name="array"
render={({ form }) => (
<ul>
{form.values.map((_, i) => (
<li key={i}>
<Field form={form} name={i} />
</li>
))}
</ul>
)}
/>
<pre>
{`
<ArrayField
form={form}
name="array"
render={({ form }) => (
<ul>
{form.values.map((_, i) => (
<li key={i}>
<Field form={form} name={i} />
</li>
))}
</ul>
)}
/>`}
</pre>
{/* Dynamic string array */}
<label>Dynamic string array</label>
<ArrayField
form={form}
name="array"
render={({ form, append, remove }) => (
<ul>
{form.values.map((_, i) => (
<li key={i}>
<Field form={form} name={i} />
<button onClick={() => remove(i)}>Remove</button>
</li>
))}
<button type="button" onClick={() => append("")}>
Add
</button>
</ul>
)}
/>
<pre>
{`
<ArrayField
form={form}
name="arrayFieldName"
render={({ form, append, remove }) => (
<div>
<ul>
{form.values.map((_, i) => (
<li key={i}>
<Field form={form} name={i} />
<button onClick={() => remove(i)}>Remove</button>
</li>
))}
</ul>
<button type="button" onClick={() => append("")}>
Add
</button>
</div>
)}
/> `}
</pre>
{/* Object array */}
<label>Object array</label>
<ArrayField
form={form}
name="objectArray"
render={({ form }) => (
<ul>
{form.values.map((_, i) => (
<ObjectField
form={form}
name={i}
render={(form) => (
<div>
<Field form={form} name="text" />
<Field form={form} name="boolean" type="checkbox" />
</div>
)}
/>
))}
</ul>
)}
/>
<pre>
{`
<ArrayField
form={form}
name="objectArrayField"
render={({ form }) => (
<ul>
{form.values.map((_, i) => (
<ObjectField
form={form}
name={i}
render={(form) => (
<div>
<Field form={form} name="objectFieldName" />
</div>
)}
/>
))}
</ul>
)}
/> `}
</pre>
{/* Dynamic object array */}
<label>Dynamic object array</label>
<ArrayField
form={form}
name="objectArray"
render={({ form, append, remove }) => (
<ul>
{form.values.map((_, i) => (
<ObjectField
form={form}
name={i}
render={(form) => (
<div>
<Field form={form} name="text" />
<Field form={form} name="boolean" type="checkbox" />
<button type="button" onClick={() => remove(i)}>
Remove
</button>
</div>
)}
/>
))}
<button type="button" onClick={() => append({ text: "", boolean: false })}>
Add item
</button>
</ul>
)}
/>
<pre>
{`
<ArrayField
form={form}
name="objectArrayField"
render={({ form, append, remove }) => (
<ul>
{form.values.map((_, i) => (
<ObjectField
form={form}
name={i}
render={(form) => (
<div>
<Field form={form} name="objectFieldName" />
<button type="button" onClick={() => remove(i)}>
Remove
</button>
</div>
)}
/>
))}
<button type="button" onClick={() => append({ objectFieldName: "default value" })}>
Add item
</button>
</ul>
)}
/>`}
</pre>
</form>
);
} | the_stack |
import DataUtil from '../misc/DataUtil';
import {
glTF1,
glTF2,
Gltf2Image,
GltfFileBuffers,
GltfLoadOption,
} from '../../types/glTF';
declare let Rn: any;
export default class Gltf1Importer {
private static __instance: Gltf1Importer;
private constructor() {}
/**
* the method to load glTF1 file.
* @param uri - uri of glTF file
* @param options - options for loading process
* @returns a glTF2 based JSON pre-processed
*/
async import(uri: string, options?: GltfLoadOption): Promise<glTF2> {
if (options && options.files) {
for (const fileName in options.files) {
const fileExtension = DataUtil.getExtension(fileName);
if (fileExtension === 'gltf' || fileExtension === 'glb') {
return await this.importGltfOrGlbFromArrayBuffers(
(options.files as any)[fileName],
options.files,
options,
uri
);
}
}
}
const arrayBuffer = await DataUtil.fetchArrayBuffer(uri);
return await this.importGltfOrGlbFromArrayBuffers(
arrayBuffer,
options?.files ?? {},
options,
uri
);
}
async importGltfOrGlbFromFile(
uri: string,
options?: GltfLoadOption
): Promise<glTF2 | undefined> {
const arrayBuffer = await DataUtil.fetchArrayBuffer(uri);
const glTFJson = await this.importGltfOrGlbFromArrayBuffers(
arrayBuffer,
{},
options,
uri
).catch(err => {
console.log('this.__loadFromArrayBuffer error', err);
return undefined;
});
return glTFJson;
}
/**
* Import glTF1 array buffer.
* @param arrayBuffer .gltf/.glb file in ArrayBuffer
* @param otherFiles other resource files data in ArrayBuffers
* @param options options for loading process (Optional)
* @param uri .gltf file's uri (Optional)
* @returns a glTF2 based JSON pre-processed
*/
async importGltfOrGlbFromArrayBuffers(
arrayBuffer: ArrayBuffer,
otherFiles: GltfFileBuffers,
options?: GltfLoadOption,
uri?: string
): Promise<glTF2> {
const dataView = new DataView(arrayBuffer, 0, 20);
// Magic field
const magic = dataView.getUint32(0, true);
// 0x46546C67 is 'glTF' in ASCII codes.
if (magic !== 0x46546c67) {
//const json = await response.json();
const gotText = DataUtil.arrayBufferToString(arrayBuffer);
const json = JSON.parse(gotText);
const gltfJson = await this.importGltf(json, otherFiles, options!, uri);
return gltfJson;
} else {
const gltfJson = await this.importGlb(arrayBuffer, otherFiles, options!);
return gltfJson;
}
}
_getOptions(defaultOptions: any, json: glTF1, options: any): GltfLoadOption {
if (json.asset && json.asset.extras && json.asset.extras.rnLoaderOptions) {
for (const optionName in json.asset.extras.rnLoaderOptions) {
defaultOptions[optionName] =
json.asset.extras.rnLoaderOptions[optionName];
}
}
for (const optionName in options) {
defaultOptions[optionName] = options[optionName];
}
if (
options &&
options.loaderExtensionName &&
typeof options.loaderExtensionName === 'string'
) {
if (Rn[options.loaderExtensionName] != null) {
defaultOptions.loaderExtension =
Rn[options.loaderExtensionName].getInstance();
} else {
console.error(`${options.loaderExtensionName} not found!`);
defaultOptions.loaderExtension = void 0;
}
}
return defaultOptions;
}
async importGlb(
arrayBuffer: ArrayBuffer,
files: GltfFileBuffers,
options: GltfLoadOption
): Promise<glTF2> {
const dataView = new DataView(arrayBuffer, 0, 20);
const gltfVer = dataView.getUint32(4, true);
if (gltfVer !== 1) {
throw new Error('invalid version field in this binary glTF file.');
}
const lengthOfJSonChunkData = dataView.getUint32(12, true);
const chunkType = dataView.getUint32(16, true);
// 0 means JSON format
if (chunkType !== 0) {
throw new Error('invalid chunkType of chunk0 in this binary glTF file.');
}
const uint8ArrayJSonContent = new Uint8Array(
arrayBuffer,
20,
lengthOfJSonChunkData
);
const gotText = DataUtil.uint8ArrayToString(uint8ArrayJSonContent);
const gltfJson = JSON.parse(gotText);
const defaultOptions = DataUtil.createDefaultGltfOptions();
options = this._getOptions(defaultOptions, gltfJson, options);
const uint8array = new Uint8Array(arrayBuffer, 20 + lengthOfJSonChunkData);
if (gltfJson.asset === undefined) {
gltfJson.asset = {};
}
if (gltfJson.asset.extras === undefined) {
gltfJson.asset.extras = {fileType: 'glTF', version: '1'};
}
this._mergeExtendedJson(gltfJson, options.extendedJson);
gltfJson.asset.extras.rnLoaderOptions = options;
const result = await this._loadInner(gltfJson, files, options, uint8array);
return (result[0] as any)[0];
}
async importGltf(
gltfJson: glTF1,
files: GltfFileBuffers,
options: GltfLoadOption,
uri?: string
): Promise<glTF2> {
const basePath = uri?.substring(0, uri?.lastIndexOf('/')) + '/'; // location of model file as basePath
if (gltfJson.asset === undefined) {
gltfJson.asset = {};
}
if (gltfJson.asset.extras === undefined) {
gltfJson.asset.extras = {fileType: 'glTF', version: '1'};
}
const defaultOptions = DataUtil.createDefaultGltfOptions();
options = this._getOptions(defaultOptions, gltfJson, options);
this._mergeExtendedJson(gltfJson, options.extendedJson);
gltfJson.asset.extras.rnLoaderOptions = options;
const result = await this._loadInner(
gltfJson,
files,
options,
undefined,
basePath
);
return (result[0] as any)[0];
}
_loadInner(
gltfJson: glTF1,
files: GltfFileBuffers,
options: GltfLoadOption,
uint8array?: Uint8Array,
basePath?: string
): Promise<any> {
const promises = [] as Promise<any>[];
promises.push(
this._loadResources(uint8array!, gltfJson, files, options, basePath)
);
promises.push(
new Promise((resolve, reject) => {
this._loadJsonContent(gltfJson, options);
resolve();
}) as Promise<void>
);
return Promise.all(promises);
}
_loadJsonContent(gltfJson: glTF1, options: GltfLoadOption) {
this._convertToGltf2LikeStructure(gltfJson);
// Scene
this._loadDependenciesOfScenes(gltfJson);
// Node
this._loadDependenciesOfNodes(gltfJson);
// Mesh
this._loadDependenciesOfMeshes(gltfJson);
// Material
this._loadDependenciesOfMaterials(gltfJson);
// Texture
this._loadDependenciesOfTextures(gltfJson);
// Joint
this._loadDependenciesOfJoints(gltfJson);
// Animation
this._loadDependenciesOfAnimations(gltfJson);
// Accessor
this._loadDependenciesOfAccessors(gltfJson);
// BufferView
this._loadDependenciesOfBufferViews(gltfJson);
}
private _convertToGltf2LikeStructure(gltfJson: glTF1) {
gltfJson.bufferDic = gltfJson.buffers;
this.__createProperty(gltfJson, gltfJson.bufferDic, 'buffers');
gltfJson.sceneDic = gltfJson.scenes;
this.__createProperty(gltfJson, gltfJson.sceneDic, 'scenes');
gltfJson.meshDic = gltfJson.meshes;
{
let count = 0;
gltfJson.nodeDic = gltfJson.nodes;
gltfJson.nodes = [];
gltfJson.nodesIndices = [];
for (const nodeName in gltfJson.nodeDic) {
gltfJson.nodesIndices.push(count);
const node = (gltfJson.nodeDic as any)[nodeName];
node._index = count++;
gltfJson.nodes.push(node);
}
}
gltfJson.skinDic = gltfJson.skins;
this.__createProperty(gltfJson, gltfJson.skinDic, 'skins');
gltfJson.materialDic = gltfJson.materials;
this.__createProperty(gltfJson, gltfJson.materialDic, 'materials');
gltfJson.animationDic = gltfJson.animations as any;
this.__createProperty(gltfJson, gltfJson.animationDic, 'animations');
gltfJson.accessorDic = gltfJson.accessors;
gltfJson.bufferViewDic = gltfJson.bufferViews;
gltfJson.cameraDic = gltfJson.cameras;
gltfJson.imageDic = gltfJson.images;
gltfJson.samplerDic = gltfJson.samplers;
gltfJson.shaderDic = gltfJson.shaders;
gltfJson.textureDic = gltfJson.textures;
}
private __createProperty(
gltfJson: glTF1,
gltfPropertyDic: any,
gltfPropertyName: string
) {
if ((gltfJson as any)[gltfPropertyName] == null) {
return;
}
const propertyNumber = Object.keys(gltfPropertyDic).length;
const propertyArray = ((gltfJson as any)[gltfPropertyName] = new Array(
propertyNumber
));
let i = 0;
for (const propertyName in gltfPropertyDic) {
propertyArray[i] = gltfPropertyDic[propertyName];
i++;
}
}
_loadDependenciesOfScenes(gltfJson: glTF1) {
for (const sceneName in gltfJson.sceneDic) {
const scene = (gltfJson.sceneDic as any)[sceneName];
scene.nodeNames = scene.nodes;
scene.nodes = [];
scene.nodesIndices = [];
for (const name of scene.nodeNames) {
scene.nodes.push((gltfJson.nodeDic as any)[name]);
// calc index of 'name' in gltfJson.nodeDic enumerate
let count = 0;
for (const nodeName in gltfJson.nodeDic) {
if (nodeName === name) {
break;
}
count++;
}
scene.nodesIndices.push(count);
}
}
}
_loadDependenciesOfNodes(gltfJson: glTF1) {
for (const node of gltfJson.nodes) {
//const node = (gltfJson.nodeDic as any)[nodeName];
// Hierarchy
if (node.children) {
node.childrenNames = node.children.concat();
node.children = [];
node.childrenIndices = [];
for (const name of node.childrenNames) {
const childNode = (gltfJson.nodeDic as any)[name];
node.children.push(childNode);
node.childrenIndices.push(childNode._index);
}
}
// Mesh
if (node.meshes !== void 0 && gltfJson.meshes !== void 0) {
node.meshNames = node.meshes;
node.meshes = [];
for (const name of node.meshNames) {
node.meshes.push((gltfJson.meshDic as any)[name]);
}
node.mesh = node.meshes[1];
if (node.meshes == null || node.meshes.length === 0) {
node.mesh = node.meshes[0];
} else {
const mergedMesh = {
name: '',
primitives: [],
};
for (let i = 0; i < node.meshes.length; i++) {
mergedMesh.name += '_' + node.meshes[i].name;
Array.prototype.push.apply(
mergedMesh.primitives,
node.meshes[i].primitives
);
}
mergedMesh.name += '_merged';
node.mesh = mergedMesh;
node.meshes = void 0;
}
}
// Skin
if (node.skin !== void 0 && gltfJson.skins !== void 0) {
if (typeof node.skin === 'string') {
node.skinName = node.skin;
node.skin = (gltfJson.skinDic as any)[node.skinName];
}
// if (node.mesh.extras === void 0) {
// node.mesh.extras = {};
// }
//node.mesh.extras._skin = node.skin;
}
// Camera
if (node.camera !== void 0 && gltfJson.cameras !== void 0) {
node.cameraName = node.camera;
node.camera = (gltfJson.cameraDic as any)[node.cameraName];
}
}
}
_loadDependenciesOfMeshes(gltfJson: glTF1) {
// Mesh
for (const meshName in gltfJson.meshDic) {
const mesh = (gltfJson.meshDic as any)[meshName];
for (const primitive of mesh.primitives) {
if (primitive.material !== void 0) {
primitive.materialName = primitive.material;
primitive.material = (gltfJson.materialDic as any)[
primitive.materialName
];
primitive.materialIndex = gltfJson.materials.indexOf(
primitive.material
);
}
primitive.attributeNames = Object.assign({}, primitive.attributes);
primitive.attributes = [];
for (let attributeName in primitive.attributeNames) {
if (primitive.attributeNames[attributeName] != null) {
const accessorName = primitive.attributeNames[attributeName];
const accessor = (gltfJson.accessorDic as any)[accessorName];
if (attributeName === 'JOINT') {
attributeName = 'JOINTS_0';
delete primitive.attributes['JOINT'];
} else if (attributeName === 'WEIGHT') {
attributeName = 'WEIGHTS_0';
delete primitive.attributes['WEIGHT'];
}
accessor.extras = {
toGetAsTypedArray: true,
attributeName: attributeName,
};
primitive.attributes.push(accessor);
} else {
//primitive.attributes[attributeName] = void 0;
}
}
if (primitive.indices !== void 0) {
primitive.indicesName = primitive.indices;
primitive.indices = (gltfJson.accessorDic as any)[
primitive.indicesName
];
}
}
}
}
_isKHRMaterialsCommon(materialJson: any) {
if (
typeof materialJson.extensions !== 'undefined' &&
typeof materialJson.extensions.KHR_materials_common !== 'undefined'
) {
return true;
} else {
return false;
}
}
_loadDependenciesOfMaterials(gltfJson: glTF1) {
// Material
if (gltfJson.materials) {
for (const materialStr in gltfJson.materials) {
let material = gltfJson.materials[materialStr];
const origMaterial = material;
if (this._isKHRMaterialsCommon(material)) {
material = material.extensions.KHR_materials_common;
}
const setParameters = (values: any[], isParameter: boolean) => {
for (const valueName in values) {
let value = null;
if (isParameter) {
value = values[valueName].value;
if (typeof value === 'undefined') {
continue;
}
} else {
value = values[valueName];
}
if (typeof value === 'string') {
const textureStr = value;
let texturePurpose;
if (
valueName === 'diffuse' ||
(material.technique === 'CONSTANT' && valueName === 'ambient')
) {
origMaterial.diffuseColorTexture = {};
origMaterial.diffuseColorTexture.texture = (
gltfJson.textures as any
)[value];
} else if (
valueName === 'emission' &&
textureStr.match(/_normal$/)
) {
origMaterial.emissionTexture = {};
origMaterial.emissionTexture.texture = (
gltfJson.textures as any
)[value];
}
origMaterial.extras = {};
origMaterial.extras.technique = material.technique;
} else {
if (valueName === 'diffuse') {
origMaterial.diffuseColorFactor = value;
}
}
}
};
setParameters(material.values, false);
if (material.technique && gltfJson.techniques) {
if (typeof gltfJson.techniques[material.technique] !== 'undefined') {
setParameters(
gltfJson.techniques[material.technique].parameters,
true
);
}
}
}
}
}
_loadDependenciesOfTextures(gltfJson: glTF1) {
// Texture
if (gltfJson.textures) {
for (const textureName in gltfJson.textureDic) {
const texture = (gltfJson.textureDic as any)[textureName];
if (texture.sampler !== void 0) {
texture.samplerName = texture.sampler;
texture.sampler = (gltfJson.samplerDic as any)[texture.samplerName];
}
if (texture.source !== void 0) {
texture.sourceName = texture.source;
texture.image = (gltfJson.imageDic as any)[texture.sourceName];
}
}
}
}
_loadDependenciesOfJoints(gltfJson: glTF1) {
if (gltfJson.skins) {
for (const skinName in gltfJson.skinDic) {
const skin = (gltfJson.skinDic as any)[skinName];
skin.joints = [];
skin.jointsIndices = [];
for (const jointName of skin.jointNames) {
const joint = (gltfJson.nodeDic as any)[jointName];
skin.joints.push(joint);
skin.jointsIndices.push(joint._index);
}
skin.skeletonNames = skin.skeletons;
if (skin.skeletonNames) {
for (const name of skin.skeletonNames) {
skin.skeleton = skin.skeletons.push(
(gltfJson.nodeDic as any)[name]
);
}
} else {
skin.skeleton = skin.joints[0];
}
skin.skeletonIndex = skin.skeleton._index;
skin.inverseBindMatricesName = skin.inverseBindMatrices;
skin.inverseBindMatrices = (gltfJson.accessorDic as any)[
skin.inverseBindMatricesName
];
skin.joints_tmp = skin.joints;
skin.joints = [];
for (const joint of skin.joints_tmp) {
skin.joints.push((gltfJson.nodeDic as any)[joint.name]);
}
skin.joints_tmp = void 0;
}
}
}
_loadDependenciesOfAnimations(gltfJson: glTF1) {
if (gltfJson.animations) {
for (const animationName in gltfJson.animationDic) {
const animation = (gltfJson.animationDic as any)[animationName];
animation.samplerDic = animation.samplers;
animation.samplers = [];
for (const channel of animation.channels) {
channel.sampler = animation.samplerDic[channel.sampler];
channel.target.node = (gltfJson.nodeDic as any)[channel.target.id];
channel.target.nodeIndex = channel.target.node._index;
channel.sampler.input =
gltfJson.accessors[animation.parameters['TIME']];
channel.sampler.output =
gltfJson.accessors[animation.parameters[channel.target.path]];
animation.samplers.push(channel.sampler);
if (channel.target.path === 'rotation') {
if (channel.sampler.output.extras === void 0) {
channel.sampler.output.extras = {};
}
channel.sampler.output.extras.quaternionIfVec4 = true;
}
}
animation.channelDic = animation.channels;
animation.channels = [];
for (const channel of animation.channelDic) {
animation.channels.push(channel);
}
}
}
}
_loadDependenciesOfAccessors(gltfJson: glTF1) {
// Accessor
for (const accessorName in gltfJson.accessorDic) {
const accessor = (gltfJson.accessorDic as any)[accessorName];
if (accessor.bufferView !== void 0) {
accessor.bufferViewName = accessor.bufferView;
accessor.bufferView = (gltfJson.bufferViewDic as any)[
accessor.bufferViewName
];
}
}
}
_loadDependenciesOfBufferViews(gltfJson: glTF1) {
// BufferView
for (const bufferViewName in gltfJson.bufferViewDic) {
const bufferView = (gltfJson.bufferViewDic as any)[bufferViewName];
if (bufferView.buffer !== void 0) {
bufferView.bufferName = bufferView.buffer;
bufferView.buffer = (gltfJson.bufferDic as any)[bufferView.bufferName];
let bufferIdx = 0;
for (const bufferName in gltfJson.bufferDic) {
if (bufferName === bufferView.bufferName) {
bufferView.bufferIndex = bufferIdx;
}
bufferIdx++;
}
}
}
}
_mergeExtendedJson(gltfJson: glTF1, extendedData: any) {
let extendedJson = null;
if (extendedData instanceof ArrayBuffer) {
const extendedJsonStr = DataUtil.arrayBufferToString(extendedData);
extendedJson = JSON.parse(extendedJsonStr);
} else if (typeof extendedData === 'string') {
extendedJson = JSON.parse(extendedData);
} else if (typeof extendedData === 'object') {
extendedJson = extendedData;
}
Object.assign(gltfJson, extendedJson);
}
_loadResources(
uint8Array: Uint8Array,
gltfJson: glTF1,
files: GltfFileBuffers,
options: GltfLoadOption,
basePath?: string
) {
const promisesToLoadResources = [];
// Buffers Async load
for (const i in gltfJson.buffers) {
const bufferInfo = gltfJson.buffers[i];
let filename = '';
if (bufferInfo.uri) {
const splitUri = bufferInfo.uri.split('/');
filename = splitUri[splitUri.length - 1];
}
if (typeof bufferInfo.uri === 'undefined') {
promisesToLoadResources.push(
new Promise((resolve, rejected) => {
bufferInfo.buffer = uint8Array;
resolve(gltfJson);
})
);
} else if (bufferInfo.uri === '' || bufferInfo.uri === 'data:,') {
promisesToLoadResources.push(
new Promise((resolve, rejected) => {
bufferInfo.buffer = uint8Array;
resolve(gltfJson);
})
);
} else if (bufferInfo.uri.match(/^data:application\/(.*);base64,/)) {
promisesToLoadResources.push(
new Promise((resolve, rejected) => {
const arrayBuffer = DataUtil.dataUriToArrayBuffer(bufferInfo.uri);
bufferInfo.buffer = new Uint8Array(arrayBuffer);
resolve(gltfJson);
})
);
} else if (files && this.__containsFileName(files, filename)) {
promisesToLoadResources.push(
new Promise((resolve, reject) => {
const fullPath = this.__getFullPathOfFileName(files, filename);
const arrayBuffer = files[fullPath!];
bufferInfo.buffer = new Uint8Array(arrayBuffer);
resolve(gltfJson);
})
);
} else {
// Need to async load other files
promisesToLoadResources.push(
DataUtil.loadResourceAsync(
basePath + bufferInfo.uri,
true,
(resolve: Function, response: any) => {
bufferInfo.buffer = new Uint8Array(response);
resolve(gltfJson);
},
(reject: Function, error: any) => {}
)
);
}
}
// Textures Async load
for (const imageJson of gltfJson.images ?? []) {
let imageUri: string;
if (
typeof imageJson.extensions !== 'undefined' &&
typeof imageJson.extensions.KHR_binary_glTF !== 'undefined'
) {
const imageUint8Array = DataUtil.createUint8ArrayFromBufferViewInfo(
gltfJson,
imageJson.extensions.KHR_binary_glTF.bufferView,
uint8Array
);
imageUri = DataUtil.createBlobImageUriFromUint8Array(
imageUint8Array,
imageJson.extensions.KHR_binary_glTF.mimeType!
);
} else if (typeof imageJson.uri === 'undefined') {
const imageUint8Array = DataUtil.createUint8ArrayFromBufferViewInfo(
gltfJson,
imageJson.bufferView!,
uint8Array
);
imageUri = DataUtil.createBlobImageUriFromUint8Array(
imageUint8Array,
imageJson.mimeType!
);
} else {
const imageFileStr = imageJson.uri;
const splitUri = imageFileStr.split('/');
const filename = splitUri[splitUri.length - 1];
if (files && this.__containsFileName(files, filename)) {
const fullPath = this.__getFullPathOfFileName(files, filename);
const arrayBuffer = files[fullPath!];
imageUri = DataUtil.createBlobImageUriFromUint8Array(
new Uint8Array(arrayBuffer),
imageJson.mimeType!
);
} else if (imageFileStr.match(/^data:/)) {
imageUri = imageFileStr;
} else {
imageUri = basePath + imageFileStr;
}
}
promisesToLoadResources.push(
this.__loadImageUri(imageUri, imageJson, files)
);
}
if (options.defaultTextures) {
const basePath = options.defaultTextures.basePath;
const textureInfos = options.defaultTextures.textureInfos;
for (const textureInfo of textureInfos) {
const fileName = textureInfo.fileName;
const uri = basePath + fileName;
const fileExtension = DataUtil.getExtension(fileName);
const mimeType = DataUtil.getMimeTypeFromExtension(fileExtension);
const promise = DataUtil.createImageFromUri(uri, mimeType).then(
image => {
image.crossOrigin = 'Anonymous';
textureInfo.image = {image: image};
}
);
promisesToLoadResources.push(promise);
}
}
return Promise.all(promisesToLoadResources);
}
private __containsFileName(
optionsFiles: {[s: string]: ArrayBuffer},
filename: string
) {
for (const key in optionsFiles) {
const split = key.split('/');
const last = split[split.length - 1];
if (last === filename) {
return true;
}
}
return false;
}
private __getFullPathOfFileName(
optionsFiles: {[s: string]: ArrayBuffer},
filename: string
) {
for (const key in optionsFiles) {
const split = key.split('/');
const last = split[split.length - 1];
if (last === filename) {
return key;
}
}
return undefined;
}
private __loadImageUri(
imageUri: string,
imageJson: Gltf2Image,
files: GltfFileBuffers
) {
let loadImagePromise: Promise<void>;
if (imageUri.match(/basis$/)) {
// load basis file from uri
loadImagePromise = new Promise(resolve => {
fetch(imageUri, {mode: 'cors'}).then(response => {
response.arrayBuffer().then(buffer => {
const uint8Array = new Uint8Array(buffer);
imageJson.basis = uint8Array;
resolve();
});
});
});
} else if (imageJson.uri?.match(/basis$/)) {
// find basis file from files option
loadImagePromise = new Promise(resolve => {
imageJson.basis = new Uint8Array(files[imageJson.uri!]);
resolve();
});
} else if (
imageUri.match(/ktx2$/) ||
(imageJson.bufferView != null && imageJson.mimeType === 'image/ktx2')
) {
// load ktx2 file from uri or bufferView
loadImagePromise = new Promise(resolve => {
fetch(imageUri, {mode: 'cors'}).then(response => {
response.arrayBuffer().then(buffer => {
const uint8Array = new Uint8Array(buffer);
imageJson.ktx2 = uint8Array;
resolve();
});
});
});
} else if (imageJson.uri?.match(/ktx2$/)) {
// find ktx2 file from files option
loadImagePromise = new Promise(resolve => {
imageJson.ktx2 = new Uint8Array(files[imageJson.uri!]);
resolve();
});
} else {
loadImagePromise = DataUtil.createImageFromUri(
imageUri,
imageJson.mimeType!
).then(image => {
image.crossOrigin = 'Anonymous';
imageJson.image = image;
});
}
return loadImagePromise;
}
static getInstance() {
if (!this.__instance) {
this.__instance = new Gltf1Importer();
}
return this.__instance;
}
} | the_stack |
import { Player } from '@/player/player'
import { Danmaku, DanmakuType } from '@/player/danmaku/danmaku'
import { DanmakuDrawer, DanmakuFixedDrawer, DanmakuFlowDrawer, } from './danmakuDrawer'
import { EventEmitter } from 'events'
import { Canvas } from '@/player/danmaku/canvas'
export enum LimitType {
UnLimited = 'unLimited', // 不限
UnOverlap = 'unOverlap', // 防重叠
Percent25 = 'percent25', // 25%屏显示弹幕
Half = 'half', // 50%屏显示弹幕
Percent75 = 'percent75', // 75%屏显示弹幕
}
export interface DanmakuLayerOptions {
// 弹幕层的弹幕文字透明度,0~1,默认为1
alpha: number
// 是否显示弹幕层,默认为true
enable: boolean
// 流式弹幕的时间,毫秒
flowDuration: number
// 固定式弹幕的时间,毫秒
fadeoutDuration: number,
// 弹幕的字体大小
fontSize: number,
// 弹幕的显示区域限制
limit: LimitType // 防重叠选项
// 弹幕的右键菜单
contextMenu: ((danmaku: Danmaku) => { [name: string]: () => void }) | undefined
}
export function MakeDanmakuLayerOptions ({
alpha = 1,
enable = true,
flowDuration = 8,
fadeoutDuration = 5,
fontSize = 28,
limit = LimitType.UnOverlap,
contextMenu = undefined,
}: Partial<DanmakuLayerOptions> = {}): DanmakuLayerOptions {
return {
alpha,
enable,
flowDuration,
fontSize,
limit,
fadeoutDuration,
contextMenu,
}
}
const template = '<div class="content"></div><div class="buttons"></div>'
function MakeDanmakuDrawerMenu (
d: DanmakuDrawer,
menus: { [p: string]: () => void },
): HTMLDivElement {
const $div = document.createElement('div')
$div.innerHTML = template
const $content = $div.querySelector('.content') as HTMLElement
$content.innerText = d.danmaku.text
const $buttons = $div.querySelector('.buttons') as HTMLDivElement
for (const key in menus) {
const $span = document.createElement('span')
$span.innerText = key
$span.addEventListener('click', menus[key])
$buttons.prepend($span)
}
return $div
}
function copyText (text: string) {
const el = document.createElement('textarea')
el.value = text
document.body.appendChild(el)
el.select()
document.execCommand('copy')
document.body.removeChild(el)
}
export class DanmakuLayer {
private player: Player
private readonly canvas: Canvas
private $menu!: HTMLElement
// 弹幕内容池
danmakus: Danmaku[] = []
showed: Danmaku[] = []
// 池
topEnables: DanmakuFixedDrawer[] = []
topAndBottomDisables: DanmakuFixedDrawer[] = []
bottomEnables: DanmakuFixedDrawer[] = []
flowEnables: DanmakuFlowDrawer[] = []
flowDisables: DanmakuFlowDrawer[] = []
private readonly lineHeights: number[] = []
private readonly topLines: { [height: string]: DanmakuDrawer | null } = {}
private readonly bottomLines: { [height: string]: DanmakuDrawer | null } = {}
private readonly flowLines: { [height: string]: DanmakuDrawer | null } = {}
private displayArea: number = 0
private topLineIndex = 0
private flowY = 0
private bottomY = 0
// 上一帧的生成时间
private frameTime: number = 0
// 计算弹幕坐标的时间
private updateDanmakuTime: number = 0
isShow = true
private width = 0
private height = 0
private calcTopInterval: number = -1
private destroied: boolean = false
private event: EventEmitter
private addDanmakuToCanvasTime: number = 0
private lastFrame: number = 0
private lineHeight!: number
constructor (player: Player) {
// @ts-ignore
window.danmaku = this
this.player = player
this.event = new EventEmitter()
this.canvas = new Canvas(player)
const hideMenu = () => {
document.removeEventListener('click', hideMenu)
document.removeEventListener('contextmenu', hideMenu)
this.$menu.remove()
}
this.canvas.$canvas.addEventListener('contextmenu', (e: MouseEvent) => {
const found = this.findDrawers(e)
if (found.length > 0) {
this.createDanmakuMenu(found)
let x = e.pageX
let y = e.pageY
const right = e.clientX + this.$menu.clientWidth
const bottom = e.clientY + this.$menu.clientHeight
if (right > document.body.clientWidth) {
x -= right - document.body.clientWidth
}
if (bottom > document.body.clientHeight) {
y -= bottom - document.body.clientHeight
}
this.$menu.style.left = x + 'px'
this.$menu.style.top = y + 'px'
document.addEventListener('click', hideMenu)
document.addEventListener('touchstart', hideMenu)
document.addEventListener('contextmenu', hideMenu)
}
e.preventDefault()
e.stopPropagation()
})
this.canvas.$canvas.addEventListener('dblclick', () => {
this.player.toggleFullScreen()
})
this.player.$video.addEventListener('seeked', () => {
this.clear()
})
this.loop()
}
private createDanmakuMenu (drawers: DanmakuDrawer[]) {
if (this.$menu) this.$menu.remove()
this.$menu = document.createElement('div')
this.$menu.classList.add('danplayer-danmaku-context-menu')
for (let i = 0; i < drawers.length; i++) {
const drawer = drawers[i]
if (this.player.options.danmaku.contextMenu) {
const menus = this.player.options.danmaku.contextMenu(drawer.danmaku)
menus[this.player.options.ui.copy] = () => {
console.log('复制按钮', drawer.danmaku.text)
copyText(drawer.danmaku.text)
}
const $menu = MakeDanmakuDrawerMenu(drawer, menus)
this.$menu.append($menu)
}
}
document.body.append(this.$menu)
}
show () {
this.isShow = true
}
hide () {
this.isShow = false
}
clear () {
this.showed.length = 0
this.canvas.clear()
this.canvas.clearCache()
this.topAndBottomDisables.push(...this.topEnables)
this.topAndBottomDisables.push(...this.bottomEnables)
this.topEnables.length = 0
this.bottomEnables.length = 0
this.flowDisables.push(...this.flowEnables)
this.flowEnables.length = 0
for (const key in this.flowLines) this.flowLines[key] = null
for (const key in this.topLines) this.topLines[key] = null
for (const key in this.bottomLines) this.bottomLines[key] = null
}
resize () {
this.width = this.player.$root.clientWidth
this.height = this.player.$root.clientHeight
this.lineHeight = Math.round(
this.canvas.fontHeight(this.player.options.danmaku.fontSize))
this.lineHeights.length = 0
// 每次resize都计算屏幕最大行数,因为有可能在多个不同分辨率的屏幕切换
for (let y = 0; y < window.screen.height; y++) {
const height = y * this.lineHeight
if (height > window.screen.height) break
this.lineHeights.push(height)
if (!Object.prototype.hasOwnProperty.call(this.topLines, height)) {
this.topLines[height] = null
}
if (!Object.prototype.hasOwnProperty.call(this.bottomLines, height)) {
this.bottomLines[height] = null
}
if (!Object.prototype.hasOwnProperty.call(this.flowLines, height)) {
this.flowLines[height] = null
}
}
this.canvas.resize()
// 检查限高
const limit = this.player.options.danmaku.limit
if (limit === LimitType.Percent75) {
this.displayArea = this.player.height * 0.75
} else if (limit === LimitType.Half) {
this.displayArea = this.player.height * 0.5
} else if (limit === LimitType.Percent25) {
this.displayArea = this.player.height * 0.25
} else {
this.displayArea = this.player.height
}
console.log('弹幕层 displayArea', this.displayArea)
this.canvas.alpha = this.player.options.danmaku.alpha
this.canvas.clear()
this.canvas.renderAll()
}
toggle (): void {
if (this.isShow) {
this.hide()
} else {
this.show()
}
}
send (d: Danmaku) {
d.text = d.text.trim()
this.danmakus.push(d)
}
private findDrawers (e: MouseEvent): DanmakuDrawer[] {
return [
...this.topEnables.filter(drawer => DanmakuLayer.find(e, drawer)),
...this.bottomEnables.filter(drawer => DanmakuLayer.find(e, drawer)),
...this.flowEnables.filter(drawer => DanmakuLayer.find(e, drawer)),
]
}
private static find (e: MouseEvent, drawer: DanmakuDrawer): boolean {
if (e.offsetX > drawer.left && e.offsetX < (drawer.left + drawer.width)) {
if (e.offsetY > drawer.top && e.offsetY < (drawer.top + drawer.height)) {
return true
}
}
return false
}
private createDrawer (danmaku: Danmaku) {
let top
if (danmaku.type === DanmakuType.Flow) {
const drawer = this.flowDisables.shift() || new DanmakuFlowDrawer()
top = this.calcFlowY()
if (top > -1) {
drawer.enable = true
drawer.set(danmaku, this.width, top)
drawer.update(this.width, this.player.options.danmaku.flowDuration, 0)
this.flowEnables.push(drawer)
this.flowLines[top] = drawer
this.canvas.addDrawer(drawer)
} else {
this.flowDisables.push(drawer)
}
} else {
const drawer = this.topAndBottomDisables.shift() ||
new DanmakuFixedDrawer()
if (danmaku.type === DanmakuType.Top) {
top = this.calcTopY()
if (top > -1) {
drawer.enable = true
drawer.set(danmaku, this.player.options.danmaku.fadeoutDuration,
this.width, top)
this.topLines[top] = drawer
console.log('渲染', top, danmaku.text)
drawer.update(0)
this.topEnables.push(drawer)
this.canvas.addDrawer(drawer)
} else {
this.topAndBottomDisables.push(drawer)
}
} else {
let top = this.calcBottomY()
if (top > -1) {
drawer.enable = true
this.bottomLines[top] = drawer
top = this.height - (top + this.lineHeight)
drawer.set(danmaku, this.player.options.danmaku.fadeoutDuration,
this.width, top)
this.bottomEnables.push(drawer)
drawer.update(0)
this.canvas.addDrawer(drawer)
} else {
this.topAndBottomDisables.push(drawer)
}
}
}
}
private addDanmakuToCanvas () {
if (this.danmakus.length === 0 ||
!this.player.options.danmaku.enable) return
// 直播
if (this.player.options.live) {
this.danmakus.forEach(danmaku => {
this.createDrawer(danmaku)
})
this.danmakus.length = 0
} else { // VOD
for (let i = 0; i < this.danmakus.length; i++) {
const danmaku = this.danmakus[i]
if (this.showed.includes(danmaku)) continue
const time = Math.abs(this.player.currentTime - danmaku.currentTime)
if (time > 0.1) continue
this.showed.push(danmaku)
this.createDrawer(danmaku)
}
}
this.canvas.renderAll()
}
private calcFlowY (): number {
for (const key in this.flowLines) {
const _d = this.flowLines[key]
if (_d && _d.enable) {
const right = _d.left + _d.width
if (right > this.width) continue
}
const height = Number(key)
if (height > this.displayArea) break
console.log('发现空行', key)
this.flowY = height
return height
}
if (this.player.options.danmaku.limit !== LimitType.UnLimited) {
return -1
}
// 无限制,就可以重复将新的弹幕显示到屏幕上
this.flowY += this.lineHeight
if (this.flowY > this.displayArea) this.flowY = 0
return this.flowY
}
private calcTopY (): number {
for (const key in this.topLines) {
const _d = this.topLines[key]
const height = Number(key)
if (_d && _d.enable) continue
if (height > this.displayArea) break
this.topLineIndex = height
return height
}
if (this.player.options.danmaku.limit !== LimitType.UnLimited) {
return -1
}
// 无限制,就可以重复将新的弹幕显示到屏幕上
this.topLineIndex += this.lineHeight
if (this.topLineIndex > this.displayArea) {
this.topLineIndex = 0
}
return this.topLineIndex
}
private calcBottomY (): number {
if (this.player.options.danmaku.limit === LimitType.Percent25 ||
this.player.options.danmaku.limit === LimitType.Half ||
this.player.options.danmaku.limit === LimitType.Percent75) {
return -1
}
for (const key in this.bottomLines) {
const _d = this.bottomLines[key]
const height = Number(key)
if (_d && _d.enable) continue
if (height > this.displayArea) break
console.log('发现空行', key)
this.bottomY = height
return height
}
if (this.player.options.danmaku.limit !== LimitType.UnLimited) {
return -1
}
// 无限制,就可以重复将新的弹幕显示到屏幕上
this.bottomY += this.lineHeight
if (this.bottomY > this.displayArea) {
this.bottomY = 0
}
return this.bottomY
}
/**
* 绘制弹幕
*/
private updateDanmaku () {
this.topEnables = this.topEnables.filter(drawer => {
if (drawer.enable) {
drawer.update(this.frameTime)
return true
} else {
console.log('topLines', drawer.height, this.topLines[drawer.height],
this.topLines[drawer.height] === drawer)
if (this.topLines[drawer.height] === drawer) {
this.topLines[drawer.height] = null
}
this.canvas.removeDrawer(drawer)
this.topAndBottomDisables.push(drawer)
return false
}
})
this.bottomEnables = this.bottomEnables.filter(drawer => {
if (drawer.enable) {
drawer.update(this.frameTime)
return true
} else {
if (this.bottomLines[drawer.height] === drawer) {
this.bottomLines[drawer.height] = null
}
this.canvas.removeDrawer(drawer)
this.topAndBottomDisables.push(drawer)
return false
}
})
this.flowEnables = this.flowEnables.filter(drawer => {
if (drawer.enable) {
drawer.update(this.width, this.player.options.danmaku.flowDuration,
this.frameTime)
return true
} else {
if (this.flowLines[drawer.height] === drawer) {
this.flowLines[drawer.height] = null
}
this.canvas.removeDrawer(drawer)
this.flowDisables.push(drawer)
return false
}
})
}
update () {
if (this.player.options.danmaku.enable && this.isShow) {
console.log('显示弹幕')
this.show()
} else {
console.log('隐藏弹幕')
this.hide()
}
}
private loop () {
if (this.destroied) return
this.addDanmakuToCanvas()
this.addDanmakuToCanvasTime = (Date.now() - this.lastFrame) / 1000
this.canvas.clear()
if (!this.player.paused) {
this.updateDanmaku()
this.updateDanmakuTime = (Date.now() - this.lastFrame) / 1000
}
if (this.player.options.danmaku.enable && this.isShow) {
this.canvas.renderAll()
}
this.frameTime = (Date.now() - this.lastFrame) / 1000
this.lastFrame = Date.now()
window.requestAnimationFrame(() => { this.loop() })
}
destroy () {
this.destroied = true
clearInterval(this.calcTopInterval)
if (this.$menu) {
this.$menu.remove()
}
}
get debug (): Object {
return {
enable: this.player.options.danmaku.enable,
isShow: this.isShow,
all: this.danmakus.length,
showed: this.showed.length,
// 耗时
time: {
addDanmakuToCanvas: this.addDanmakuToCanvasTime,
drawDanmaku: this.updateDanmakuTime,
frameTime: this.frameTime,
},
'on screen danmakus': {
top: this.topEnables.length,
bottom: this.bottomEnables.length,
flow: this.flowEnables.length,
},
'danmaku pool': {
fixed: this.topAndBottomDisables.length,
flow: this.flowDisables.length,
},
positionY: {
top: this.topLineIndex,
flow: this.flowY,
bottom: this.bottomY,
},
}
}
} | the_stack |
import {CanvasRenderingContext} from "../../common";
import {WebGLShader} from '../WebGLShader';
import {WebGLFramebuffer} from '../WebGLFramebuffer';
import {WebGLTexture} from '../WebGLTexture';
import {WebGLProgram} from '../WebGLProgram';
import {WebGLUniformLocation} from '../WebGLUniformLocation';
import {WebGLActiveInfo} from '../WebGLActiveInfo';
import {WebGLRenderbuffer} from '../WebGLRenderbuffer';
import {WebGLShaderPrecisionFormat} from '../WebGLShaderPrecisionFormat';
export abstract class WebGLRenderingContextBase
implements CanvasRenderingContext {
abstract readonly drawingBufferHeight: number;
abstract readonly drawingBufferWidth: number;
public static isDebug = false;
public static filter: 'both' | 'error' | 'args' = 'both';
protected constructor(context) {
this._native = context;
}
_native: any;
get native() {
return this._native;
}
_canvas: any;
get canvas(): any {
return this._canvas;
}
_type: string = 'none';
get type() {
return this._type;
}
// get EXTENSIONS(): number {
// return 7939;
// }
public get DEPTH_BUFFER_BIT(): number {
return 0x00000100;
}
public get STENCIL_BUFFER_BIT(): number {
return 0x00000400;
}
public get COLOR_BUFFER_BIT(): number {
return 0x00004000;
}
public get POINTS(): number {
return 0x0000;
}
public get LINES(): number {
return 0x0001;
}
public get LINE_LOOP(): number {
return 0x0002;
}
public get LINE_STRIP(): number {
return 0x0003;
}
public get TRIANGLES(): number {
return 0x0004;
}
public get TRIANGLE_STRIP(): number {
return 0x0005;
}
public get TRIANGLE_FAN(): number {
return 0x0006;
}
public get ZERO(): number {
return 0;
}
public get ONE(): number {
return 1;
}
public get SRC_COLOR(): number {
return 0x0300;
}
public get ONE_MINUS_SRC_COLOR(): number {
return 0x0301;
}
public get SRC_ALPHA(): number {
return 0x0302;
}
public get ONE_MINUS_SRC_ALPHA(): number {
return 0x0303;
}
public get DST_ALPHA(): number {
return 0x0304;
}
public get ONE_MINUS_DST_ALPHA(): number {
return 0x0305;
}
public get DST_COLOR(): number {
return 0x0306;
}
public get ONE_MINUS_DST_COLOR(): number {
return 0x0307;
}
public get SRC_ALPHA_SATURATE(): number {
return 0x0308;
}
public get CONSTANT_COLOR(): number {
return 0x8001;
}
public get ONE_MINUS_CONSTANT_COLOR(): number {
return 0x8002;
}
public get CONSTANT_ALPHA(): number {
return 0x8003;
}
public get ONE_MINUS_CONSTANT_ALPHA(): number {
return 0x8004;
}
/* Blending equations */
public get FUNC_ADD(): number {
return 0x8006;
}
public get FUNC_SUBTRACT(): number {
return 0x800A;
}
public get FUNC_REVERSE_SUBTRACT(): number {
return 0x800B;
}
public get BLEND_EQUATION(): number {
return 0x8009;
}
public get BLEND_EQUATION_RGB(): number {
return 0x8009;
}
public get BLEND_EQUATION_ALPHA(): number {
return 0x883D;
}
public get BLEND_DST_RGB(): number {
return 0x80C8;
}
public get BLEND_SRC_RGB(): number {
return 0x80C9;
}
public get BLEND_DST_ALPHA(): number {
return 0x80CA;
}
public get BLEND_SRC_ALPHA(): number {
return 0x80CB;
}
public get BLEND_COLOR(): number {
return 0x8005;
}
public get ARRAY_BUFFER_BINDING(): number {
return 0x8894;
}
public get ELEMENT_ARRAY_BUFFER_BINDING(): number {
return 0x8895;
}
public get LINE_WIDTH(): number {
return 0x0B21;
}
public get ALIASED_POINT_SIZE_RANGE(): number {
return 0x846D;
}
public get ALIASED_LINE_WIDTH_RANGE(): number {
return 0x846E;
}
public get CULL_FACE_MODE(): number {
return 0x0B45;
}
public get FRONT_FACE(): number {
return 0x0B46;
}
public get DEPTH_RANGE(): number {
return 0x0B70;
}
public get DEPTH_WRITEMASK(): number {
return 0x0B72;
}
public get DEPTH_CLEAR_VALUE(): number {
return 0x0B73;
}
public get DEPTH_FUNC(): number {
return 0x0B74;
}
public get STENCIL_CLEAR_VALUE(): number {
return 0x0B91;
}
public get STENCIL_FUNC(): number {
return 0x0B92;
}
public get STENCIL_FAIL(): number {
return 0x0B94;
}
public get STENCIL_PASS_DEPTH_FAIL(): number {
return 0x0B95;
}
public get STENCIL_PASS_DEPTH_PASS(): number {
return 0x0B96;
}
public get STENCIL_REF(): number {
return 0x0B97;
}
public get STENCIL_VALUE_MASK(): number {
return 0x0B93;
}
public get STENCIL_WRITEMASK(): number {
return 0x0B98;
}
public get STENCIL_BACK_FUNC(): number {
return 0x8800;
}
public get STENCIL_BACK_FAIL(): number {
return 0x8801;
}
public get STENCIL_BACK_PASS_DEPTH_FAIL(): number {
return 0x8802;
}
public get STENCIL_BACK_PASS_DEPTH_PASS(): number {
return 0x8803;
}
public get STENCIL_BACK_REF(): number {
return 0x8CA3;
}
public get STENCIL_BACK_VALUE_MASK(): number {
return 0x8CA4;
}
public get STENCIL_BACK_WRITEMASK(): number {
return 0x8CA5;
}
// getCanvas(): Canvas;
public get VIEWPORT(): number {
return 0x0BA2;
}
public get SCISSOR_BOX(): number {
return 0x0C10;
}
public get COLOR_CLEAR_VALUE(): number {
return 0x0C22;
}
public get COLOR_WRITEMASK(): number {
return 0x0C23;
}
public get UNPACK_ALIGNMENT(): number {
return 0x0CF5;
}
public get PACK_ALIGNMENT(): number {
return 0x0D05;
}
public get MAX_TEXTURE_SIZE(): number {
return 0x0D33;
}
public get MAX_VIEWPORT_DIMS(): number {
return 0x0D3A;
}
public get SUBPIXEL_BITS(): number {
return 0x0D50;
}
public get RED_BITS(): number {
return 0x0D52;
}
public get GREEN_BITS(): number {
return 0x0D53;
}
public get BLUE_BITS(): number {
return 0x0D54;
}
public get ALPHA_BITS(): number {
return 0x0D55;
}
public get DEPTH_BITS(): number {
return 0x0D56;
}
public get STENCIL_BITS(): number {
return 0x0D57;
}
public get POLYGON_OFFSET_UNITS(): number {
return 0x2A00;
}
public get POLYGON_OFFSET_FACTOR(): number {
return 0x8038;
}
public get TEXTURE_BINDING_2D(): number {
return 0x8069;
}
public get SAMPLE_BUFFERS(): number {
return 0x80A8;
}
public get SAMPLES(): number {
return 0x80A9;
}
public get SAMPLE_COVERAGE_VALUE(): number {
return 0x80AA;
}
public get SAMPLE_COVERAGE_INVERT(): number {
return 0x80AB;
}
public get COMPRESSED_TEXTURE_FORMATS(): number {
return 0x86A3;
}
public get VENDOR(): number {
return 0x1F00;
}
public get RENDERER(): number {
return 0x1F01;
}
public get VERSION(): number {
return 0x1F02;
}
public get IMPLEMENTATION_COLOR_READ_TYPE(): number {
return 0x8B9A;
}
public get IMPLEMENTATION_COLOR_READ_FORMAT(): number {
return 0x8B9B;
}
public get BROWSER_DEFAULT_WEBGL(): number {
return 0x9244;
}
public get STATIC_DRAW(): number {
return 0x88E4;
}
public get STREAM_DRAW(): number {
return 0x88E0;
}
public get DYNAMIC_DRAW(): number {
return 0x88E8;
}
public get ARRAY_BUFFER(): number {
return 0x8892;
}
public get ELEMENT_ARRAY_BUFFER(): number {
return 0x8893;
}
public get BUFFER_SIZE(): number {
return 0x8764;
}
public get BUFFER_USAGE(): number {
return 0x8765;
}
public get CURRENT_VERTEX_ATTRIB(): number {
return 0x8626;
}
public get VERTEX_ATTRIB_ARRAY_ENABLED(): number {
return 0x8622;
}
public get VERTEX_ATTRIB_ARRAY_SIZE(): number {
return 0x8623;
}
public get VERTEX_ATTRIB_ARRAY_STRIDE(): number {
return 0x8624;
}
public get VERTEX_ATTRIB_ARRAY_TYPE(): number {
return 0x8625;
}
public get VERTEX_ATTRIB_ARRAY_NORMALIZED(): number {
return 0x886A;
}
public get VERTEX_ATTRIB_ARRAY_POINTER(): number {
return 0x8645;
}
public get VERTEX_ATTRIB_ARRAY_BUFFER_BINDING(): number {
return 0x889F;
}
public get CULL_FACE(): number {
return 0x0B44;
}
public get FRONT(): number {
return 0x0404;
}
public get BACK(): number {
return 0x0405;
}
public get FRONT_AND_BACK(): number {
return 0x0408;
}
public get BLEND(): number {
return 0x0BE2;
}
public get DEPTH_TEST(): number {
return 0x0B71;
}
public get DITHER(): number {
return 0x0BD0;
}
public get POLYGON_OFFSET_FILL(): number {
return 0x8037;
}
public get SAMPLE_ALPHA_TO_COVERAGE(): number {
return 0x809E;
}
public get SAMPLE_COVERAGE(): number {
return 0x80A0;
}
public get SCISSOR_TEST(): number {
return 0x0C11;
}
public get STENCIL_TEST(): number {
return 0x0B90;
}
/* Errors */
public get NO_ERROR(): number {
return 0;
}
public get INVALID_ENUM(): number {
return 0x0500;
}
public get INVALID_VALUE(): number {
return 0x0501;
}
public get INVALID_OPERATION(): number {
return 0x0502;
}
public get OUT_OF_MEMORY(): number {
return 0x0505;
}
public get CONTEXT_LOST_WEBGL(): number {
return 0x9242;
}
public get CW(): number {
return 0x0900;
}
public get CCW(): number {
return 0x0901;
}
public get DONT_CARE(): number {
return 0x1100;
}
public get FASTEST(): number {
return 0x1101;
}
public get NICEST(): number {
return 0x1102;
}
public get GENERATE_MIPMAP_HINT(): number {
return 0x8192;
}
public get BYTE(): number {
return 0x1400;
}
public get UNSIGNED_BYTE(): number {
return 0x1401;
}
public get SHORT(): number {
return 0x1402;
}
public get UNSIGNED_SHORT(): number {
return 0x1403;
}
public get INT(): number {
return 0x1404;
}
public get UNSIGNED_INT(): number {
return 0x1405;
}
public get FLOAT(): number {
return 0x1406;
}
public get DEPTH_COMPONENT(): number {
return 0x1902;
}
public get ALPHA(): number {
return 0x1906;
}
public get RGB(): number {
return 0x1907;
}
/* Clearing buffers */
public get RGBA(): number {
return 0x1908;
}
public get LUMINANCE(): number {
return 0x1909;
}
public get LUMINANCE_ALPHA(): number {
return 0x190A;
}
/* Clearing buffers */
/* Rendering primitives */
public get UNSIGNED_SHORT_4_4_4_4(): number {
return 0x8033;
}
public get UNSIGNED_SHORT_5_5_5_1(): number {
return 0x8034;
}
public get UNSIGNED_SHORT_5_6_5(): number {
return 0x8363;
}
public get FRAGMENT_SHADER(): number {
return 0x8B30;
}
public get VERTEX_SHADER(): number {
return 0x8B31;
}
public get COMPILE_STATUS(): number {
return 0x8B81;
}
public get DELETE_STATUS(): number {
return 0x8B80;
}
/* Rendering primitives */
/* Blending modes */
public get LINK_STATUS(): number {
return 0x8B82;
}
public get VALIDATE_STATUS(): number {
return 0x8B83;
}
public get ATTACHED_SHADERS(): number {
return 0x8B85;
}
public get ACTIVE_ATTRIBUTES(): number {
return 0x8B89;
}
public get ACTIVE_UNIFORMS(): number {
return 0x8B86;
}
public get MAX_VERTEX_ATTRIBS(): number {
return 0x8869;
}
public get MAX_VERTEX_UNIFORM_VECTORS(): number {
return 0x8DFB;
}
public get MAX_VARYING_VECTORS(): number {
return 0x8DFC;
}
public get MAX_COMBINED_TEXTURE_IMAGE_UNITS(): number {
return 0x8B4D;
}
public get MAX_VERTEX_TEXTURE_IMAGE_UNITS(): number {
return 0x8B4C;
}
public get MAX_TEXTURE_IMAGE_UNITS(): number {
return 0x8872;
}
public get MAX_FRAGMENT_UNIFORM_VECTORS(): number {
return 0x8DFD;
}
public get SHADER_TYPE(): number {
return 0x8B4F;
}
public get SHADING_LANGUAGE_VERSION(): number {
return 0x8B8C;
}
public get CURRENT_PROGRAM(): number {
return 0x8B8D;
}
/* Blending modes */
public get NEVER(): number {
return 0x0200;
}
public get LESS(): number {
return 0x0201;
}
public get EQUAL(): number {
return 0x0202;
}
/* Blending equations */
/* Getting GL parameter information */
public get LEQUAL(): number {
return 0x0203;
}
public get GREATER(): number {
return 0x0204;
}
public get NOTEQUAL(): number {
return 0x0205;
}
public get GEQUAL(): number {
return 0x0206;
}
public get ALWAYS(): number {
return 0x0207;
}
public get KEEP(): number {
return 0x1E00;
}
public get REPLACE(): number {
return 0x1E01;
}
public get INCR(): number {
return 0x1E02;
}
public get DECR(): number {
return 0x1E03;
}
public get INVERT(): number {
return 0x150A;
}
public get INCR_WRAP(): number {
return 0x8507;
}
public get DECR_WRAP(): number {
return 0x8508;
}
public get NEAREST(): number {
return 0x2600;
}
public get LINEAR(): number {
return 0x2601;
}
public get NEAREST_MIPMAP_NEAREST(): number {
return 0x2700;
}
public get LINEAR_MIPMAP_NEAREST(): number {
return 0x2701;
}
public get NEAREST_MIPMAP_LINEAR(): number {
return 0x2702;
}
public get LINEAR_MIPMAP_LINEAR(): number {
return 0x2703;
}
public get TEXTURE_MAG_FILTER(): number {
return 0x2800;
}
public get TEXTURE_MIN_FILTER(): number {
return 0x2801;
}
public get TEXTURE_WRAP_S(): number {
return 0x2802;
}
public get TEXTURE_WRAP_T(): number {
return 0x2803;
}
public get TEXTURE_2D(): number {
return 0x0DE1;
}
public get TEXTURE(): number {
return 0x1702;
}
public get TEXTURE_CUBE_MAP(): number {
return 0x8513;
}
public get TEXTURE_BINDING_CUBE_MAP(): number {
return 0x8514;
}
public get TEXTURE_CUBE_MAP_POSITIVE_X(): number {
return 0x8515;
}
public get TEXTURE_CUBE_MAP_NEGATIVE_X(): number {
return 0x8516;
}
public get TEXTURE_CUBE_MAP_POSITIVE_Y(): number {
return 0x8517;
}
public get TEXTURE_CUBE_MAP_NEGATIVE_Y(): number {
return 0x8518;
}
public get TEXTURE_CUBE_MAP_POSITIVE_Z(): number {
return 0x8519;
}
public get TEXTURE_CUBE_MAP_NEGATIVE_Z(): number {
return 0x851A;
}
public get MAX_CUBE_MAP_TEXTURE_SIZE(): number {
return 0x851C;
}
public get TEXTURE0(): number {
return 0x84C0;
}
public get TEXTURE1(): number {
return 0x84C1;
}
public get TEXTURE2(): number {
return 0x84C2;
}
public get TEXTURE3(): number {
return 0x84C3;
}
public get TEXTURE4(): number {
return 0x84C4;
}
public get TEXTURE5(): number {
return 0x84C5;
}
public get TEXTURE6(): number {
return 0x84C6;
}
public get TEXTURE7(): number {
return 0x84C7;
}
public get TEXTURE8(): number {
return 0x84C8;
}
public get TEXTURE9(): number {
return 0x84C9;
}
public get TEXTURE10(): number {
return 0x84CA;
}
public get TEXTURE11(): number {
return 0x84CB;
}
public get TEXTURE12(): number {
return 0x84CC;
}
public get TEXTURE13(): number {
return 0x84CD;
}
public get TEXTURE14(): number {
return 0x84CE;
}
public get TEXTURE15(): number {
return 0x84CF;
}
public get TEXTURE16(): number {
return 0x84D0;
}
public get TEXTURE17(): number {
return 0x84D1;
}
public get TEXTURE18(): number {
return 0x84D2;
}
public get TEXTURE19(): number {
return 0x84D3;
}
public get TEXTURE20(): number {
return 0x84D4;
}
public get TEXTURE21(): number {
return 0x84D5;
}
public get TEXTURE22(): number {
return 0x84D6;
}
public get TEXTURE23(): number {
return 0x84D7;
}
public get TEXTURE24(): number {
return 0x84D8;
}
public get TEXTURE25(): number {
return 0x84D9;
}
public get TEXTURE26(): number {
return 0x84DA;
}
public get TEXTURE27(): number {
return 0x84DB;
}
public get TEXTURE28(): number {
return 0x84DC;
}
public get TEXTURE29(): number {
return 0x84DD;
}
/* Getting GL parameter information */
/* Buffers */
public get TEXTURE30(): number {
return 0x84DE;
}
public get TEXTURE31(): number {
return 0x84DF;
}
public get ACTIVE_TEXTURE(): number {
return 0x84E0;
}
public get REPEAT(): number {
return 0x2901;
}
public get CLAMP_TO_EDGE(): number {
return 0x812F;
}
public get MIRRORED_REPEAT(): number {
return 0x8370;
}
public get FLOAT_VEC2(): number {
return 0x8B50;
}
/* Buffers */
/* Vertex attributes */
public get FLOAT_VEC3(): number {
return 0x8B51;
}
public get FLOAT_VEC4(): number {
return 0x8B52;
}
public get INT_VEC2(): number {
return 0x8B53;
}
public get INT_VEC3(): number {
return 0x8B54;
}
public get INT_VEC4(): number {
return 0x8B55;
}
public get BOOL(): number {
return 0x8B56;
}
public get BOOL_VEC2(): number {
return 0x8B57;
}
public get BOOL_VEC3(): number {
return 0x8B58;
}
/* Vertex attributes */
/* Culling */
public get BOOL_VEC4(): number {
return 0x8B59;
}
public get FLOAT_MAT2(): number {
return 0x8B5A;
}
public get FLOAT_MAT3(): number {
return 0x8B5B;
}
public get FLOAT_MAT4(): number {
return 0x8B5C;
}
/* Culling */
/* Enabling and disabling */
public get SAMPLER_2D(): number {
return 0x8B5E;
}
public get SAMPLER_CUBE(): number {
return 0x8B60;
}
public get LOW_FLOAT(): number {
return 0x8DF0;
}
public get MEDIUM_FLOAT(): number {
return 0x8DF1;
}
public get HIGH_FLOAT(): number {
return 0x8DF2;
}
public get LOW_INT(): number {
return 0x8DF3;
}
public get MEDIUM_INT(): number {
return 0x8DF4;
}
public get HIGH_INT(): number {
return 0x8DF5;
}
/* Enabling and disabling */
public get FRAMEBUFFER(): number {
return 0x8D40;
}
public get RENDERBUFFER(): number {
return 0x8D41;
}
public get RGBA4(): number {
return 0x8056;
}
public get RGB5_A1(): number {
return 0x8057;
}
public get RGB565(): number {
return 0x8D62;
}
public get DEPTH_COMPONENT16(): number {
return 0x81A5;
}
public get STENCIL_INDEX8(): number {
return 0x8D48;
}
/* Errors */
/* Front face directions */
public get DEPTH_STENCIL(): number {
return 0x84F9;
}
public get RENDERBUFFER_WIDTH(): number {
return 0x8D42;
}
/* Front face directions */
/* Hints */
public get RENDERBUFFER_HEIGHT(): number {
return 0x8D43;
}
public get RENDERBUFFER_INTERNAL_FORMAT(): number {
return 0x8D44;
}
public get RENDERBUFFER_RED_SIZE(): number {
return 0x8D50;
}
public get RENDERBUFFER_GREEN_SIZE(): number {
return 0x8D51;
}
/* Hints */
/* Data types */
public get RENDERBUFFER_BLUE_SIZE(): number {
return 0x8D52;
}
public get RENDERBUFFER_ALPHA_SIZE(): number {
return 0x8D53;
}
public get RENDERBUFFER_DEPTH_SIZE(): number {
return 0x8D54;
}
public get RENDERBUFFER_STENCIL_SIZE(): number {
return 0x8D55;
}
public get FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE(): number {
return 0x8CD0;
}
public get FRAMEBUFFER_ATTACHMENT_OBJECT_NAME(): number {
return 0x8CD1;
}
public get FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL(): number {
return 0x8CD2;
}
/* Data types */
/* Pixel formats */
public get FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE(): number {
return 0x8CD3;
}
public get COLOR_ATTACHMENT0(): number {
return 0x8CE0;
}
public get DEPTH_ATTACHMENT(): number {
return 0x8D00;
}
public get STENCIL_ATTACHMENT(): number {
return 0x8D20;
}
public get DEPTH_STENCIL_ATTACHMENT(): number {
return 0x821A;
}
public get NONE(): number {
return 0;
}
/* Pixel formats */
/* Pixel types */
// public get UNSIGNED_BYTE(): number { return this.native.UNSIGNED_BYTE }
public get FRAMEBUFFER_COMPLETE(): number {
return 0x8CD5;
}
public get FRAMEBUFFER_INCOMPLETE_ATTACHMENT(): number {
return 0x8CD6;
}
public get FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT(): number {
return 0x8CD7;
}
/* Pixel types */
/* Shaders */
public get FRAMEBUFFER_INCOMPLETE_DIMENSIONS(): number {
return 0x8CD9;
}
public get FRAMEBUFFER_UNSUPPORTED(): number {
return 0x8CDD;
}
public get FRAMEBUFFER_BINDING(): number {
return 0x8CA6;
}
public get RENDERBUFFER_BINDING(): number {
return 0x8CA7;
}
public get MAX_RENDERBUFFER_SIZE(): number {
return 0x84E8;
}
public get INVALID_FRAMEBUFFER_OPERATION(): number {
return 0x0506;
}
public get UNPACK_FLIP_Y_WEBGL(): number {
return 0x9240;
}
public get UNPACK_PREMULTIPLY_ALPHA_WEBGL(): number {
return 0x9241;
}
public get UNPACK_COLORSPACE_CONVERSION_WEBGL(): number {
return 0x9243;
}
toNativeArray(value: any[], type: string): any {
return [];
}
abstract activeTexture(texture: number): void;
abstract attachShader(program: WebGLProgram, shader: WebGLShader): void;
abstract bindAttribLocation(
program: WebGLProgram,
index: number,
name: string
): void;
abstract bindBuffer(target: number, buffer: WebGLBuffer): void;
abstract bindFramebuffer(target: number, framebuffer: WebGLFramebuffer): void;
abstract bindRenderbuffer(
target: number,
renderbuffer: WebGLRenderbuffer
): void;
abstract bindTexture(target: number, texture: WebGLTexture): void;
abstract blendColor(
red: number,
green: number,
blue: number,
alpha: number
): void;
abstract blendEquationSeparate(modeRGB: number, modeAlpha: number): void;
abstract blendEquation(mode: number): void;
/* Shaders */
/* Depth or stencil tests */
abstract blendFuncSeparate(
srcRGB: number,
dstRGB: number,
srcAlpha: number,
dstAlpha: number
): void;
abstract blendFunc(sfactor: number, dfactor: number): void;
abstract bufferData(target: number, size: number, usage: number): void;
abstract bufferData(
target: number,
srcData: ArrayBuffer | ArrayBufferView,
usage: number
): void;
abstract bufferSubData(
target: number,
offset: number,
srcData: ArrayBuffer | ArrayBufferView
): void;
abstract checkFramebufferStatus(target: number): number;
abstract clearColor(
red: number,
green: number,
blue: number,
alpha: number
): void;
abstract clearDepth(depth: number): void;
/* Depth or stencil tests */
/* Stencil actions */
abstract clearStencil(stencil: number): void;
abstract clear(mask: number): void;
abstract colorMask(
red: boolean,
green: boolean,
blue: boolean,
alpha: boolean
): void;
abstract commit(): void;
abstract compileShader(shader: WebGLShader): void;
abstract compressedTexImage2D(
target: number,
level: number,
internalformat: number,
width: number,
height: number,
border: number,
pixels: ArrayBufferView
): void;
abstract compressedTexSubImage2D(
target: number,
level: number,
xoffset: number,
yoffset: number,
width: number,
height: number,
format: number,
pixels: ArrayBufferView
): void;
/* Stencil actions */
/* Textures */
abstract copyTexImage2D(
target: number,
level: number,
internalformat: number,
x: number,
y: number,
width: number,
height: number,
border: number
): void;
abstract copyTexSubImage2D(
target: number,
level: number,
xoffset: number,
yoffset: number,
x: number,
y: number,
width: number,
height: number
): void;
abstract createBuffer(): WebGLBuffer;
abstract createFramebuffer(): WebGLFramebuffer;
abstract createProgram(): WebGLProgram;
abstract createRenderbuffer(): WebGLRenderbuffer;
abstract createShader(type: number): WebGLShader;
abstract createTexture(): WebGLTexture;
abstract cullFace(mode: number): void;
abstract deleteBuffer(buffer: WebGLBuffer): void;
abstract deleteFramebuffer(frameBuffer: WebGLFramebuffer): void;
abstract deleteProgram(program: WebGLProgram): void;
abstract deleteRenderbuffer(renderBuffer: WebGLRenderbuffer): void;
abstract deleteShader(shader: WebGLRenderbuffer): void;
abstract deleteTexture(texture: WebGLTexture): void;
abstract depthFunc(func: number): void;
abstract depthMask(flag: boolean): void;
abstract depthRange(zNear: number, zFar: number): void;
abstract detachShader(program: WebGLProgram, shader: WebGLShader): void;
abstract disableVertexAttribArray(index: number): void;
abstract disable(cap: number): void;
abstract drawArrays(mode: number, first: number, count: number): void;
abstract drawElements(
mode: number,
count: number,
type: number,
offset: number
): void;
abstract enableVertexAttribArray(index: number): void;
abstract enable(cap: number): void;
abstract finish(): void;
abstract flush(): void;
abstract framebufferRenderbuffer(
target: number,
attachment: number,
renderbuffertarget: number,
renderbuffer: WebGLRenderbuffer
): void;
abstract framebufferTexture2D(
target: number,
attachment: number,
textarget: number,
texture: WebGLTexture,
level: number
): void;
abstract frontFace(mode: number): void;
abstract generateMipmap(target: number): void;
abstract getActiveAttrib(
program: WebGLProgram,
index: number
): WebGLActiveInfo;
abstract getActiveUniform(
program: WebGLProgram,
index: number
): WebGLActiveInfo;
abstract getAttachedShaders(program: WebGLProgram): WebGLShader[];
abstract getAttribLocation(program: WebGLProgram, name: string): number;
abstract getBufferParameter(target: number, pname: number): number;
abstract getContextAttributes(): any;
abstract getError(): number;
abstract getExtension(name: string): any;
abstract getFramebufferAttachmentParameter(
target: number,
attachment: number,
pname: number
): WebGLRenderbuffer | WebGLTexture | number;
abstract getParameter(pname: number): any;
abstract getProgramInfoLog(program: WebGLProgram): string;
abstract getProgramParameter(program: WebGLProgram, pname: number): any;
abstract getRenderbufferParameter(target: number, pname: number): number;
abstract getShaderInfoLog(shader: WebGLShader): string;
abstract getShaderParameter(shader: WebGLShader, pname: number): any;
abstract getShaderPrecisionFormat(
shaderType: number,
precisionType: number
): WebGLShaderPrecisionFormat | null;
abstract getShaderSource(shader: WebGLShader): string;
abstract getSupportedExtensions(): string[];
abstract getTexParameter(target: number, pname: number): number;
abstract getUniformLocation(
program: WebGLProgram,
name: string
): WebGLUniformLocation;
abstract getUniform(
program: WebGLProgram,
location: WebGLUniformLocation
): number;
abstract getVertexAttribOffset(index: number, pname: number): void;
abstract getVertexAttrib(index: number, pname: number): any;
abstract hint(target: number, mode: number): void;
abstract isBuffer(buffer: WebGLBuffer): boolean;
abstract isContextLost(): boolean;
/* Textures */
/* Uniform types */
abstract isEnabled(cap: number): boolean;
abstract isFramebuffer(framebuffer: WebGLFramebuffer): boolean;
abstract isProgram(program: WebGLProgram): boolean;
abstract isRenderbuffer(renderbuffer: WebGLRenderbuffer): boolean;
abstract isShader(shader: WebGLShader): boolean;
abstract isTexture(texture: WebGLTexture): boolean;
abstract lineWidth(width: number): void;
abstract linkProgram(program: WebGLProgram): void;
abstract pixelStorei(pname: number, param: any): void;
abstract polygonOffset(factor: number, units: number): void;
abstract readPixels(
x: number,
y: number,
width: number,
height: number,
format: number,
type: number,
pixels: ArrayBufferView
): void;
abstract renderbufferStorage(
target: number,
internalFormat: number,
width: number,
height: number
): void;
abstract sampleCoverage(value: number, invert: boolean): void;
abstract scissor(x: number, y: number, width: number, height: number): void;
abstract shaderSource(shader: WebGLShader, source: string): void;
/* Uniform types */
/* Shader precision-specified types */
abstract stencilFuncSeparate(
face: number,
func: number,
ref: number,
mask: number
): void;
abstract stencilFunc(func: number, ref: number, mask: number): void;
abstract stencilMaskSeparate(face: number, mask: number): void;
abstract stencilMask(mask: number): void;
abstract stencilOpSeparate(
face: number,
fail: number,
zfail: number,
zpass: number
): void;
abstract stencilOp(fail: number, zfail: number, zpass: number): void;
/* Shader precision-specified types */
/* Framebuffers and renderbuffers */
abstract texImage2D(
target: number,
level: number,
internalformat: number,
format: number,
type: number,
pixels: any
): void;
abstract texImage2D(
target: number,
level: number,
internalformat: number,
width: number,
height: number,
border: number,
format: number,
type: number,
pixels: ArrayBufferView
): void;
abstract texParameterf(target: number, pname: number, param: number): void;
abstract texParameteri(target: number, pname: number, param: number): void;
abstract texSubImage2D(
target: number,
level: number,
xoffset: number,
yoffset: number,
width: number,
height: number,
format: number,
type: number,
pixels: ArrayBufferView
): void;
abstract texSubImage2D(
target: number,
level: number,
xoffset: number,
yoffset: number,
format: number,
type: number,
pixels: any
): void;
abstract uniform1f(location: WebGLUniformLocation, v0: number): void;
abstract uniform1iv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform1fv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform1i(location: WebGLUniformLocation, v0: number): void;
abstract uniform2f(
location: WebGLUniformLocation,
v0: number,
v1: number
): void;
abstract uniform2iv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform2fv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform2i(
location: WebGLUniformLocation,
v0: number,
v1: number
): void;
abstract uniform3f(
location: WebGLUniformLocation,
v0: number,
v1: number,
v2: number
): void;
abstract uniform3iv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform3fv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform3i(
location: WebGLUniformLocation,
v0: number,
v1: number,
v2: number
): void;
abstract uniform4f(
location: WebGLUniformLocation,
v0: number,
v1: number,
v2: number,
v3: number
): void;
abstract uniform4iv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform4fv(location: WebGLUniformLocation, value: number[]): void;
abstract uniform4i(
location: WebGLUniformLocation,
v0: number,
v1: number,
v2: number,
v3: number
): void;
abstract uniformMatrix2fv(
location: WebGLUniformLocation,
transpose: boolean,
value: number[]
): void;
abstract uniformMatrix3fv(
location: WebGLUniformLocation,
transpose: boolean,
value: number[]
): void;
abstract uniformMatrix4fv(
location: WebGLUniformLocation,
transpose: boolean,
value: number[]
): void;
abstract useProgram(program: WebGLProgram): void;
abstract validateProgram(program: WebGLProgram): void;
abstract vertexAttrib1f(index: number, v0: number): void;
abstract vertexAttrib1fv(index: number, value: number[]): void;
abstract vertexAttrib2f(index: number, v0: number, v1: number): void;
abstract vertexAttrib2fv(index: number, value: number[]): void;
abstract vertexAttrib3f(
index: number,
v0: number,
v1: number,
v2: number
): void;
abstract vertexAttrib3fv(index: number, value: number[]): void;
abstract vertexAttrib4f(
index: number,
v0: number,
v1: number,
v2: number,
v3: number
): void;
// public get INVALID_FRAMEBUFFER_OPERATION(): number { return this.native.INVALID_FRAMEBUFFER_OPERATION }
/* Framebuffers and renderbuffers */
/* Pixel storage modes */
abstract vertexAttrib4fv(index: number, value: number[]): void;
abstract vertexAttribPointer(
index: number,
size: number,
type: number,
normalized: boolean,
stride: number,
offset: number
): void;
abstract viewport(x: number, y: number, width: number, height: number): void;
/* Pixel storage modes */
} | the_stack |
import { BehaviorSubject } from 'rxjs/BehaviorSubject'
import { DOMInjectable } from './../shared/services/injection.service'
import { ChangeDetectionStrategy, Component, HostBinding, ViewChild } from '@angular/core'
import { QuillEditorComponent } from './../shared/quill-editor/quill-editor.component'
import { FirebaseDatabaseService } from './../shared/services/firebase-database.service'
import { AuthService } from './../shared/services/auth.service'
import { FormControl, FormGroup, Validators } from '@angular/forms'
import { ServerResponseService } from './../shared/services/server-response.service'
import { ActivatedRoute, Router } from '@angular/router'
import { Observable } from 'rxjs/Observable'
import { filter } from 'rxjs/operators'
import { SEONode, SEOService } from '../shared/services/seo.service'
import { MatChipInputEvent, MatDialog, MatSnackBar } from '@angular/material'
import { ModalConfirmationComponent } from '../shared/modal-confirmation/modal-confirmation.component'
import { ENTER } from '@angular/cdk/keycodes'
const COMMA = 188
export interface Page {
readonly content: string
readonly title: string
readonly isDraft: boolean
readonly userCommentsEnabled?: boolean
readonly cache?: { readonly [key: string]: boolean | string | number }
readonly imgWidth?: number,
readonly imgHeight?: number,
readonly imgAlt?: string,
readonly imgUrl?: string,
readonly imgMime?: string
readonly articleTag?: ReadonlyArray<string>
}
type types = 'script' | 'style'
interface InjectionMap { readonly [key: string]: { readonly type: types, readonly injectable: DOMInjectable } }
@Component({
selector: 'pm-not-found',
templateUrl: './not-found.component.html',
styleUrls: ['./not-found.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NotFoundComponent {
@HostBinding('class.vert-flex-fill') readonly flexFill = true
@ViewChild(QuillEditorComponent) readonly editor: QuillEditorComponent
readonly addOnBlur = true
readonly separatorKeysCodes: ReadonlyArray<any> = [ENTER, COMMA]
tags: ReadonlyArray<string> = []
readonly injections$ = new BehaviorSubject<InjectionMap>({})
readonly injectionsToSave$ = new BehaviorSubject<InjectionMap>({})
readonly styleInjDefault = {
element: 'link',
attributes: {
href: 'https://',
type: 'text/css',
rel: 'stylesheet'
}
}
cacheSettings = {} as any
injectionFormChange(key: string, type: types, injectable: DOMInjectable) {
console.log(key)
// this.injectionsToSave$.next({
// ...this.injections$.getValue(),
// [key]: {
// type,
// injectable
// }
// })
}
addInjectable(type: types) {
this.injections$.next({
...this.injections$.getValue(),
[`${type.toString()}_${Math.random().toPrecision(4)}`]: {
type,
injectable: {} as any
}
})
}
insertInjectable(key: string, type: types, injectable: DOMInjectable) {
this.injections$.next({
...this.injections$.getValue(),
[key]: {
type,
injectable
}
})
}
removeInjectable(key: string) {
const current = this.injections$.getValue()
this.injections$.next({
...Object.keys(current)
.filter(k => k !== key)
.reduce((a, c) => ({ ...a, [c]: current[c] }), {})
})
}
add(event: MatChipInputEvent): void {
if (event.input) event.input.value = '' // clear input value
this.tags = [...this.tags, event.value.trim()]
.filter(a => a !== '')
.filter((elem, pos, arr) => arr.indexOf(elem) === pos)
this.updateTags()
}
remove(tag: any): void {
this.tags = [...this.tags].filter(a => a !== tag)
this.updateTags()
}
updateTags() {
this.settingsForm.controls['articleTag'].setValue(this.tags)
}
updateTabParam(tab: number) {
this.router.navigate([this.router.url.split('?')[0]], { queryParams: { tab }, queryParamsHandling: 'merge' })
}
private readonly params$ = this.ar.queryParams.shareReplay()
private readonly isEditMode$ = this.params$
.map(a => a.edit ? true : false)
private readonly currentTab$ = this.params$
.map(a => a.tab ? +a.tab : 0)
private readonly url$ = Observable.of(this.router.url.split('?')[0])
.pipe(filter(a => !a.includes('.')))
.shareReplay()
public readonly settingsForm = new FormGroup({
type: new FormControl('website', [Validators.required]),
title: new FormControl('', [Validators.required]),
description: new FormControl('', [Validators.required, Validators.max(158)]),
imgUrl: new FormControl('', []),
imgAlt: new FormControl('', []),
imgMime: new FormControl('', []),
imgHeight: new FormControl('', [Validators.min(1)]),
imgWidth: new FormControl('', [Validators.min(1)]),
articlePublishedTime: new FormControl(new Date(), []),
articleModifiedTime: new FormControl('', []),
articleExpirationTime: new FormControl('', []),
articleAuthor: new FormControl('', []),
articleSection: new FormControl('', []),
articleTag: new FormControl('', []),
userCommentsEnabled: new FormControl('', []),
isDraft: new FormControl('', [])
})
public readonly page$ = this.url$
.flatMap(url => this.db
.get<Page & SEONode>(`/pages/${url}`)
.flatMap(page => this.isEditMode$, (page, editMode) => ({ page, editMode }))
.map(res => {
if (res && res.page && (res.editMode || !res.page.isDraft)) {
if (!res.editMode) {
const pageCacheSettings = res.page.cache || {}
const cacheControl = Object.keys(pageCacheSettings)
.filter(key => pageCacheSettings[key])
.reduce((acc, curr) => {
const ret = typeof pageCacheSettings[curr] === 'boolean'
? curr
: `${curr}=${pageCacheSettings[curr]}`
return acc.concat(', ').concat(ret)
}, '')
.replace(/(^,)|(,$)/g, '')
.trim()
if (cacheControl) {
this.rs.setHeader('Cache-Control', cacheControl)
} else {
this.rs.setCacheNone()
}
} else {
this.rs.setCacheNone()
}
return {
...res.page,
content: res.page.content
}
}
this.rs.setNotFound()
this.rs.setCacheNone()
return {
...res.page,
content: 'not found'
} as Page & SEONode
})
.do(page => {
this.cacheSettings = page.cache
this.seo.updateNode({
title: page.title,
description: page.description,
img: {
width: page.imgWidth,
height: page.imgHeight,
type: page.imgMime,
alt: page.imgAlt,
url: page.imgUrl
},
tags: page.articleTag
})
// tslint:disable:no-null-keyword
const formValues = Object.keys(this.settingsForm.controls)
.reduce((acc: any, controlKey) =>
({ ...acc, [controlKey]: (page as any)[controlKey] || this.settingsForm.controls[controlKey].value || null }), {})
this.settingsForm.setValue(formValues)
this.tags = page.articleTag || []
})
.catch(err => {
if (err.code === 'PERMISSION_DENIED') {
this.rs.setStatus(401)
return Observable.of({
content: 'unauthorized'
})
} else {
this.rs.setError()
return Observable.of({
content: err || 'server error'
})
}
}))
readonly view$ = Observable.combineLatest(this.auth.user$, this.page$, this.currentTab$,
this.ar.queryParams.pluck('edit').map(a => a === 'true'),
(user, page, currentTab, isEditing) => {
return {
currentTab,
canEdit: true, // for demo only, user && user.roles && user.roles.admin,
isEditing,
page
}
})
.catch(err => {
this.rs.setError()
return Observable.of({
content: 'server error'
})
})
publish() {
const injections = this.injectionsToSave$.getValue()
const cache = this.cacheSettings
const settings = Object.keys(this.settingsForm.value)
.filter(key => typeof this.settingsForm.value[key] !== 'undefined')
.reduce((acc, curr) => ({ ...acc, [curr]: this.settingsForm.value[curr] }) as any, {})
this.url$.flatMap(url => this.db.getObjectRef(`/pages/${url}`)
.update({
...settings,
injections,
cache,
content: this.editor.textValue.getValue()
}), (url, update) => ({ url, update }))
.take(1)
.subscribe(a => {
this.router.navigate([a.url])
this.showSnack('Published! Page is now live.')
})
}
showSnack(message: string) {
this.snackBar.open(message, 'dismiss', {
duration: 2000,
horizontalPosition: 'left',
verticalPosition: 'bottom'
})
}
confirmDelete() {
return this.dialog.open(ModalConfirmationComponent, {
width: '460px',
position: {
top: '30px'
},
data: {
message: 'Deleting this page will immediately remove it from the database and anyone reading it',
title: 'Are you sure?'
}
})
}
delete() {
this.confirmDelete()
.afterClosed()
.filter(Boolean)
.flatMap(() => this.url$)
.flatMap(url => this.db.getObjectRef(`/pages/${url}`).remove(), (url, update) => ({ url, update }))
.take(1)
.subscribe(a => {
this.router.navigate(['/pages'])
this.showSnack('Page removed!')
})
}
viewCurrent() {
this.url$
.take(1)
.subscribe(url => this.router.navigate([url]))
}
edit() {
this.url$
.take(1)
.subscribe(url => this.router.navigate([url], { queryParams: { edit: true } }))
}
constructor(private rs: ServerResponseService, private db: FirebaseDatabaseService, private seo: SEOService,
public auth: AuthService, private ar: ActivatedRoute, private router: Router, private dialog: MatDialog,
private snackBar: MatSnackBar) {
}
updateCache(cache: any) {
this.cacheSettings = cache
}
trackByInjection(index: number, item: any) {
return item.key
}
trackByTag(index: number, item: string) {
return item
}
} | the_stack |
import { sqlRequest, translateSmartQuery } from '@app/api'
import { isExecuteableBlockType } from '@app/components/editor/Blocks/utils'
import { QuerySelectorFamily } from '@app/components/editor/store/queries'
import { charts } from '@app/components/v11n/charts'
import { Type } from '@app/components/v11n/types'
import { createTranscation } from '@app/context/editorTranscations'
import { useWorkspace } from '@app/hooks/useWorkspace'
import { QuerySnapshotIdAtom, useCreateSnapshot } from '@app/store/block'
import { Editor, Story } from '@app/types'
import { blockIdGenerator } from '@app/utils'
import dayjs from 'dayjs'
import { dequal } from 'dequal'
import { isEqual } from 'lodash'
import React, { useCallback, useContext, useEffect, useMemo, useRef } from 'react'
import { useIsMutating, useQueryClient } from 'react-query'
import { useRecoilCallback, useRecoilValue, waitForAll } from 'recoil'
import invariant from 'tiny-invariant'
import { useBlockSuspense, useFetchStoryChunk, useGetBlock, useGetSnapshot } from './api'
import { useCommit } from './useCommit'
import { useGetCompiledQuery } from './useCompiledQuery'
import { useStoryPermissions } from './useStoryPermissions'
import { useStoryResources } from './useStoryResources'
export const useRefreshSnapshot = (storyId: string) => {
const commit = useCommit()
const workspace = useWorkspace()
const queryClient = useQueryClient()
const createSnapshot = useCreateSnapshot()
const getSnapshot = useGetSnapshot()
const getBlock = useGetBlock()
const getCompiledQuery = useGetCompiledQuery()
const execute = useRecoilCallback(
({ set, reset }) =>
async (queryBlock: Editor.QueryBlock) => {
const originalBlockId = queryBlock.id
const { query, isTemp } = await getCompiledQuery(storyId, queryBlock.id)
let sql = ''
if (query.type === 'sql') {
sql = query.data
} else if (query.type === 'smart') {
const { queryBuilderId, metricIds, dimensions, filters } = JSON.parse(query.data)
sql = (
await translateSmartQuery(
workspace.id,
workspace.preferences?.connectorId!,
queryBuilderId,
metricIds,
dimensions,
filters
)
).data.sql
}
const mutations = queryClient
.getMutationCache()
.getAll()
.filter(
(mutation) =>
(mutation.options.mutationKey as string)?.endsWith(originalBlockId) && mutation.state.status === 'loading'
)
mutations.forEach((mutation) => {
mutation.cancel()
})
return queryClient.executeMutation({
mutationFn: sqlRequest,
variables: {
workspaceId: workspace.id,
sql,
questionId: originalBlockId,
connectorId: workspace.preferences.connectorId!,
profile: workspace.preferences.profile!
},
mutationKey: ['story', queryBlock.storyId, queryBlock.id, originalBlockId].join('/'),
onSuccess: async (data) => {
if (typeof data !== 'object' || data.errMsg) {
// const snapshotId = questionBlock.content!.snapshotId
commit({
storyId: queryBlock.storyId!,
transcation: createTranscation({
operations: [
{
cmd: 'update',
id: originalBlockId,
path: ['content', 'lastRunAt'],
table: 'block',
args: Date.now()
},
{
cmd: 'update',
id: originalBlockId,
path: ['content', 'error'],
table: 'block',
args: data.errMsg ?? data
}
]
})
})
return
}
const snapshotId = blockIdGenerator()
await createSnapshot({
snapshotId,
questionId: originalBlockId,
sql: sql,
data: data,
workspaceId: workspace.id
})
const prevSnapshot = await getSnapshot({ snapshotId: queryBlock?.content?.snapshotId })
if (!isEqual(prevSnapshot?.data.fields, data.fields)) {
const visualizationBlock = (await getBlock(queryBlock.parentId)) as Editor.VisualizationBlock
const dimensions =
queryBlock.type === Editor.BlockType.SmartQuery
? (queryBlock as Editor.SmartQueryBlock).content.dimensions
: undefined
commit({
storyId: storyId!,
transcation: createTranscation({
operations: [
{
cmd: 'update',
id: queryBlock.parentId,
path: ['content', 'visualization'],
table: 'block',
args: charts[visualizationBlock.content?.visualization?.type || Type.TABLE].initializeConfig(
data,
{ cache: {}, dimensions }
)
}
]
})
})
}
if (isTemp) {
set(QuerySnapshotIdAtom({ blockId: queryBlock.id }), snapshotId)
} else {
reset(QuerySnapshotIdAtom({ blockId: queryBlock.id }))
commit({
storyId: storyId!,
transcation: createTranscation({
operations: [
{
cmd: 'update',
id: originalBlockId,
path: ['content', 'lastRunAt'],
table: 'block',
args: Date.now()
},
{
cmd: 'update',
id: originalBlockId,
path: ['content', 'error'],
table: 'block',
args: ''
},
{
cmd: 'update',
id: originalBlockId,
path: ['content', 'snapshotId'],
table: 'block',
args: snapshotId
}
]
})
})
}
}
})
},
[
commit,
createSnapshot,
getSnapshot,
getBlock,
getCompiledQuery,
queryClient,
storyId,
workspace.id,
workspace.preferences.connectorId,
workspace.preferences.profile
]
)
const cancel = useCallback(
(blockId) => {
const mutations = queryClient.getMutationCache().getAll()
mutations
.filter((mutation) => (mutation.options.mutationKey as string)?.endsWith(blockId))
.forEach((mutation) => {
queryClient.getMutationCache().remove(mutation)
})
// executeSQL.reset()
},
[queryClient]
)
const snapshotMutation = useMemo(
() => ({
execute,
cancel
}),
[cancel, execute]
)
return snapshotMutation
}
function usePreviousCompare<T>(value: T) {
const ref = useRef<null | typeof value>()
useEffect(() => {
if (dequal(ref.current, value) === false) {
ref.current = value
}
}, [value])
return ref.current as T
}
export const useStorySnapshotManagerProvider = (storyId: string) => {
useFetchStoryChunk(storyId)
const storyBlock = useBlockSuspense<Story>(storyId)
const resourcesBlocks = useStoryResources(storyId)
const queryClient = useQueryClient()
const executeableQuestionBlocks = useMemo(() => {
return resourcesBlocks.filter((block) => isExecuteableBlockType(block.type))
}, [resourcesBlocks])
const compiledQueries = useRecoilValue(
waitForAll(executeableQuestionBlocks.map((block) => QuerySelectorFamily({ storyId, queryId: block.id })))
)
const previousComipledQueriesRef = usePreviousCompare(compiledQueries)
const refreshOnInit = storyBlock?.format?.refreshOnOpen
const permissions = useStoryPermissions(storyId)
const refreshSnapshot = useRefreshSnapshot(storyId)
useEffect(() => {
if (refreshOnInit && permissions.canWrite) {
executeableQuestionBlocks.forEach((questionBlock: Editor.DataAssetBlock) => {
if (dayjs().diff(dayjs(questionBlock.content?.lastRunAt ?? 0)) > 1000 * 5 * 60) {
refreshSnapshot.execute(questionBlock)
}
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refreshOnInit, refreshSnapshot])
useEffect(() => {
for (const queryBlock of executeableQuestionBlocks) {
const snapshotId = queryBlock?.content?.snapshotId
const blockId = queryBlock.id
const mutatingCount = queryClient.isMutating({
predicate: (mutation) => (mutation.options.mutationKey as string)?.endsWith(blockId)
})
if (blockId && !snapshotId && mutatingCount === 0 && !queryBlock.content?.error) {
if (
(queryBlock.type === Editor.BlockType.SQL && (queryBlock as Editor.SQLBlock).content?.sql) ||
queryBlock.type === Editor.BlockType.SmartQuery
) {
refreshSnapshot.execute(queryBlock)
}
}
}
}, [queryClient, refreshSnapshot, executeableQuestionBlocks])
useEffect(() => {
if (!previousComipledQueriesRef) return
for (let i = 0; i < compiledQueries.length; i++) {
const currentQuery = compiledQueries[i]
const previousQuery = previousComipledQueriesRef.find(
(previousQuery) => previousQuery.query.id === currentQuery.query.id
)
if (!previousQuery || !currentQuery) continue
if (dequal(previousQuery, currentQuery) !== true) {
const queryBlock = executeableQuestionBlocks[i]
refreshSnapshot.execute(queryBlock)
}
}
}, [previousComipledQueriesRef, compiledQueries, executeableQuestionBlocks, refreshSnapshot])
const runAll = useCallback(() => {
executeableQuestionBlocks.forEach((questionBlock: Editor.DataAssetBlock) => {
refreshSnapshot.execute(questionBlock)
})
}, [executeableQuestionBlocks, refreshSnapshot])
const cancelAll = useCallback(() => {
executeableQuestionBlocks.forEach((questionBlock: Editor.DataAssetBlock) => {
refreshSnapshot.cancel(questionBlock.id)
})
}, [executeableQuestionBlocks, refreshSnapshot])
const refreshingSnapshot = useIsMutating({
predicate: (mutation) => (mutation.options.mutationKey as string)?.startsWith(`story/${storyId}`)
})
return useMemo(
() => ({
total: executeableQuestionBlocks.length,
mutating: refreshingSnapshot,
runAll,
cancelAll
}),
[cancelAll, executeableQuestionBlocks.length, refreshingSnapshot, runAll]
)
}
export const StorySnapshotMangerContext = React.createContext<ReturnType<
typeof useStorySnapshotManagerProvider
> | null>(null)
export const useStorySnapshotManager = () => {
const context = useContext(StorySnapshotMangerContext)
invariant(context, 'useBlockTranscations must use in provider')
return context
}
export const useSnapshotMutating = (blockId: string) => {
const refreshingSnapshot = useIsMutating({
predicate: (mutation) => (mutation.options.mutationKey as string)?.endsWith(blockId)
})
return refreshingSnapshot
}
export interface SnapshotMutation {
execute: (questionBlock: Editor.DataAssetBlock) => Promise<void>
cancel: (blockId: string) => void
} | the_stack |
function id(d: any[]): any { return d[0]; }
declare var annotStart: any;
declare var annotName: any;
declare var blockStart: any;
declare var blockName: any;
declare var ws: any;
declare var blockTextStart: any;
declare var blockTextEnd: any;
declare var text: any;
declare var textBeforeComment: any;
declare var escape: any;
declare var argsStart: any;
declare var argsEnd: any;
declare var comma: any;
declare var literalSq: any;
declare var literalDq: any;
declare var integer: any;
declare var float: any;
declare var arrayStart: any;
declare var arrayEnd: any;
declare var objStart: any;
declare var objEnd: any;
declare var colon: any;
declare var ident: any;
import {
Ast,
Utils,
Constraint,
ConstraintCollection,
} from './modules';
const mlexer = require("./lexer");
const lexer = mlexer.lexer;
function extractBlockChildren(children: any []): any [] {
return children.map((child: any) => {
return child instanceof Array ? child[0] : child;
});
}
function extractExprs(d: any) {
let output: any = [d[0]];
for (let i in d[1]) {
output.push(d[1][i][3]);
}
return output;
}
function extractLiteral(value: string) {
if(value.startsWith("'")){
return JSON.parse(Utils.sq2Dq(value));
}
if(value.startsWith('"')){
return JSON.parse(value);
}
return value;
}
function extractSymbol(d: any) {
const value = extractLiteral(d[0].value);
const codePos = {
startLine: d[0].line - 1,
endLine: d[0].line - 1,
startColumn: d[0].col - 1,
endColumn: d[0].col - 1 + d[0].value.length,
};
return {value, codePos};
}
function extractPair(d: any) {
const symbol = d[0];
const key = symbol.value;
const value = d[4];
return new Constraint(key, value, symbol.codePos);
}
function extractPairs(d: any) {
let output: Constraint [] = [];
output.push(d[0]);
for (let i in d[1]) {
output.push(d[1][i][3]);
}
return new ConstraintCollection(output);
}
interface NearleyToken { value: any;
[key: string]: any;
};
interface NearleyLexer {
reset: (chunk: string, info: any) => void;
next: () => NearleyToken | undefined;
save: () => any;
formatError: (token: NearleyToken) => string;
has: (tokenType: string) => boolean;
};
interface NearleyRule {
name: string;
symbols: NearleySymbol[];
postprocess?: (d: any[], loc?: number, reject?: {}) => any;
};
type NearleySymbol = string | { literal: any } | { test: (token: any) => boolean };
interface Grammar {
Lexer: NearleyLexer | undefined;
ParserRules: NearleyRule[];
ParserStart: string;
};
const grammar: Grammar = {
Lexer: lexer,
ParserRules: [
{"name": "main$ebnf$1", "symbols": []},
{"name": "main$ebnf$1$subexpression$1", "symbols": ["stmt"]},
{"name": "main$ebnf$1", "symbols": ["main$ebnf$1", "main$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "main", "symbols": ["main$ebnf$1"], "postprocess": id},
{"name": "stmt", "symbols": ["plain"], "postprocess": id},
{"name": "stmt", "symbols": ["annot"], "postprocess": id},
{"name": "stmt", "symbols": ["block"], "postprocess": id},
{"name": "plain", "symbols": ["text"], "postprocess":
(d) => {
const value = d[0].value;
const codePos = {
startLine: d[0].line - 1,
endLine: d[0].line - 1 + value.split('\n').length - 1,
startColumn: d[0].col - 1,
endColumn: d[0].col - 1 + value.length
};
// console.log('text:%o, at %o', d[0], codePos);
return new Ast({
type: 'text',
name: '(text)',
args: [],
value,
children: [],
codePos,
});
}
},
{"name": "annot", "symbols": [(lexer.has("annotStart") ? {type: "annotStart"} : annotStart), (lexer.has("annotName") ? {type: "annotName"} : annotName), "args"], "postprocess":
(d) => {
const codePos = {
startLine: d[0].line - 1,
endLine: d[0].line - 1,
startColumn: d[0].col - 1,
endColumn: d[0].col + d[1].value.length, // d[0].col - 1 + d[1].value.length + 1
};
// console.log('annot:%o, at %o', d[0], codePos);
return new Ast({
type:'annot',
name: d[1].value,
args: d[2] || [],
value: '',
children: [],
codePos,
});
}
},
{"name": "block$ebnf$1", "symbols": []},
{"name": "block$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "block$ebnf$1", "symbols": ["block$ebnf$1", "block$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "block$ebnf$2", "symbols": []},
{"name": "block$ebnf$2$subexpression$1", "symbols": ["stmt"]},
{"name": "block$ebnf$2", "symbols": ["block$ebnf$2", "block$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "block", "symbols": [(lexer.has("blockStart") ? {type: "blockStart"} : blockStart), (lexer.has("blockName") ? {type: "blockName"} : blockName), "args", "block$ebnf$1", (lexer.has("blockTextStart") ? {type: "blockTextStart"} : blockTextStart), "block$ebnf$2", (lexer.has("blockTextEnd") ? {type: "blockTextEnd"} : blockTextEnd)], "postprocess":
(d) => {
const codePos = {
startLine: d[0].line - 1,
endLine: d[6].line - 1,
startColumn: d[0].col - 1,
endColumn: d[6].col - 1,
};
// console.log('block start:%o, at %o', d[0], codePos);
return new Ast({
type: 'block',
name: d[1].value,
args: d[2] || [],
value: '',
children: extractBlockChildren(d[5]),
codePos,
});
}
},
{"name": "text", "symbols": [(lexer.has("text") ? {type: "text"} : text)], "postprocess": id},
{"name": "text", "symbols": [(lexer.has("textBeforeComment") ? {type: "textBeforeComment"} : textBeforeComment)], "postprocess": id},
{"name": "text", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)], "postprocess": id},
{"name": "text", "symbols": [(lexer.has("escape") ? {type: "escape"} : escape)], "postprocess":
(d) => {
d[0].value = d[0].value.substring(1);
return d[0];
}
},
{"name": "args$ebnf$1", "symbols": []},
{"name": "args$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "args$ebnf$1", "symbols": ["args$ebnf$1", "args$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "args$ebnf$2$subexpression$1", "symbols": ["exprs"]},
{"name": "args$ebnf$2", "symbols": ["args$ebnf$2$subexpression$1"], "postprocess": id},
{"name": "args$ebnf$2", "symbols": [], "postprocess": () => null},
{"name": "args$ebnf$3", "symbols": []},
{"name": "args$ebnf$3$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "args$ebnf$3", "symbols": ["args$ebnf$3", "args$ebnf$3$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "args", "symbols": [(lexer.has("argsStart") ? {type: "argsStart"} : argsStart), "args$ebnf$1", "args$ebnf$2", "args$ebnf$3", (lexer.has("argsEnd") ? {type: "argsEnd"} : argsEnd)], "postprocess": (d) => d[2]? d[2][0] : []},
{"name": "exprs$ebnf$1", "symbols": []},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$1", "symbols": []},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$1", "symbols": ["exprs$ebnf$1$subexpression$1$ebnf$1", "exprs$ebnf$1$subexpression$1$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$2", "symbols": []},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$2$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "exprs$ebnf$1$subexpression$1$ebnf$2", "symbols": ["exprs$ebnf$1$subexpression$1$ebnf$2", "exprs$ebnf$1$subexpression$1$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "exprs$ebnf$1$subexpression$1", "symbols": ["exprs$ebnf$1$subexpression$1$ebnf$1", (lexer.has("comma") ? {type: "comma"} : comma), "exprs$ebnf$1$subexpression$1$ebnf$2", "expr"]},
{"name": "exprs$ebnf$1", "symbols": ["exprs$ebnf$1", "exprs$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "exprs", "symbols": ["expr", "exprs$ebnf$1"], "postprocess": extractExprs},
{"name": "expr", "symbols": ["literal"], "postprocess": id},
{"name": "expr", "symbols": ["number"], "postprocess": id},
{"name": "expr", "symbols": ["array"], "postprocess": id},
{"name": "expr", "symbols": ["object"], "postprocess": id},
{"name": "literal", "symbols": [(lexer.has("literalSq") ? {type: "literalSq"} : literalSq)], "postprocess": (d) => extractLiteral(d[0].value)},
{"name": "literal", "symbols": [(lexer.has("literalDq") ? {type: "literalDq"} : literalDq)], "postprocess": (d) => extractLiteral(d[0].value)},
{"name": "number", "symbols": [(lexer.has("integer") ? {type: "integer"} : integer)], "postprocess": (d) => parseInt(d[0].value, 10)},
{"name": "number", "symbols": [(lexer.has("float") ? {type: "float"} : float)], "postprocess": (d) => parseFloat(d[0].value)},
{"name": "array$ebnf$1", "symbols": []},
{"name": "array$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "array$ebnf$1", "symbols": ["array$ebnf$1", "array$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "array", "symbols": [(lexer.has("arrayStart") ? {type: "arrayStart"} : arrayStart), "array$ebnf$1", (lexer.has("arrayEnd") ? {type: "arrayEnd"} : arrayEnd)], "postprocess": (d) => []},
{"name": "array$ebnf$2", "symbols": []},
{"name": "array$ebnf$2$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "array$ebnf$2", "symbols": ["array$ebnf$2", "array$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "array$ebnf$3", "symbols": []},
{"name": "array$ebnf$3$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "array$ebnf$3", "symbols": ["array$ebnf$3", "array$ebnf$3$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "array", "symbols": [(lexer.has("arrayStart") ? {type: "arrayStart"} : arrayStart), "array$ebnf$2", "exprs", "array$ebnf$3", (lexer.has("arrayEnd") ? {type: "arrayEnd"} : arrayEnd)], "postprocess": (d) => d[2]},
{"name": "object$ebnf$1", "symbols": []},
{"name": "object$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "object$ebnf$1", "symbols": ["object$ebnf$1", "object$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "object", "symbols": [(lexer.has("objStart") ? {type: "objStart"} : objStart), "object$ebnf$1", (lexer.has("objEnd") ? {type: "objEnd"} : objEnd)], "postprocess": (d) => { return {}; }},
{"name": "object$ebnf$2", "symbols": []},
{"name": "object$ebnf$2$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "object$ebnf$2", "symbols": ["object$ebnf$2", "object$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "object", "symbols": [(lexer.has("objStart") ? {type: "objStart"} : objStart), "object$ebnf$2", "pairs", (lexer.has("objEnd") ? {type: "objEnd"} : objEnd)], "postprocess": (d) => d[2]},
{"name": "pairs$ebnf$1", "symbols": []},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$1", "symbols": []},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$1", "symbols": ["pairs$ebnf$1$subexpression$1$ebnf$1", "pairs$ebnf$1$subexpression$1$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$2", "symbols": []},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$2$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "pairs$ebnf$1$subexpression$1$ebnf$2", "symbols": ["pairs$ebnf$1$subexpression$1$ebnf$2", "pairs$ebnf$1$subexpression$1$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pairs$ebnf$1$subexpression$1", "symbols": ["pairs$ebnf$1$subexpression$1$ebnf$1", (lexer.has("comma") ? {type: "comma"} : comma), "pairs$ebnf$1$subexpression$1$ebnf$2", "pair"]},
{"name": "pairs$ebnf$1", "symbols": ["pairs$ebnf$1", "pairs$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pairs$ebnf$2$subexpression$1", "symbols": [(lexer.has("comma") ? {type: "comma"} : comma)]},
{"name": "pairs$ebnf$2", "symbols": ["pairs$ebnf$2$subexpression$1"], "postprocess": id},
{"name": "pairs$ebnf$2", "symbols": [], "postprocess": () => null},
{"name": "pairs$ebnf$3", "symbols": []},
{"name": "pairs$ebnf$3$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "pairs$ebnf$3", "symbols": ["pairs$ebnf$3", "pairs$ebnf$3$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pairs", "symbols": ["pair", "pairs$ebnf$1", "pairs$ebnf$2", "pairs$ebnf$3"], "postprocess": extractPairs},
{"name": "pair$ebnf$1", "symbols": []},
{"name": "pair$ebnf$1$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "pair$ebnf$1", "symbols": ["pair$ebnf$1", "pair$ebnf$1$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pair$ebnf$2", "symbols": []},
{"name": "pair$ebnf$2$subexpression$1", "symbols": [(lexer.has("ws") ? {type: "ws"} : ws)]},
{"name": "pair$ebnf$2", "symbols": ["pair$ebnf$2", "pair$ebnf$2$subexpression$1"], "postprocess": (d) => d[0].concat([d[1]])},
{"name": "pair", "symbols": ["symbol", "pair$ebnf$1", (lexer.has("colon") ? {type: "colon"} : colon), "pair$ebnf$2", "expr"], "postprocess": extractPair},
{"name": "symbol", "symbols": [(lexer.has("ident") ? {type: "ident"} : ident)], "postprocess": extractSymbol},
{"name": "symbol", "symbols": [(lexer.has("literalSq") ? {type: "literalSq"} : literalSq)], "postprocess": extractSymbol},
{"name": "symbol", "symbols": [(lexer.has("literalSq") ? {type: "literalSq"} : literalSq)], "postprocess": extractSymbol}
],
ParserStart: "main",
};
export default grammar; | the_stack |
import React, { CSSProperties, ReactNode } from 'react';
// components
import SuccessIcon from './SuccessIcon';
import ErrorIcon from './ErrorIcon';
import InfoIcon from './InfoIcon';
import WarningIcon from './WarningIcon';
import CustomIcon from './CustomIcon';
import Buttons from './Buttons';
import Input from './Input';
import ValidationMessage from './ValidationMessage';
import Title from './Title';
import Content from './Content';
import Overlay from './Overlay';
// other
import * as styles from '../styles/SweetAlertStyles';
import * as Patterns from '../constants/patterns';
import {
SweetAlertAnimationProps,
SweetAlertOptionalPropsWithDefaults,
SweetAlertProps,
SweetAlertPropsTypes, SweetAlertRenderProps,
SweetAlertState,
} from '../types';
import { SWEET_ALERT_PROP_TYPES } from '../prop-types';
import { SWEET_ALERT_DEFAULT_PROPS } from '../default-props';
const SWEET_ALERT_DEFAULT_STYLES = styles.sweetAlert;
const _resetting: { [alertId:string]: boolean } = {};
const debugLogger = (...args: any[]): void => {
// uncomment the next line to get some debugging logs.
// console.log(...args);
};
export default class SweetAlert extends React.Component<SweetAlertProps, SweetAlertState> {
static propTypes: SweetAlertPropsTypes = SWEET_ALERT_PROP_TYPES;
static defaultProps: SweetAlertOptionalPropsWithDefaults = SWEET_ALERT_DEFAULT_PROPS;
static SuccessIcon = SuccessIcon;
static ErrorIcon = ErrorIcon;
static InfoIcon = InfoIcon;
static WarningIcon = WarningIcon;
static CustomIcon = CustomIcon;
static Buttons = Buttons;
static Input = Input;
static ValidationMessage = ValidationMessage;
static Title = Title;
static Content = Content;
readonly state: SweetAlertState;
private inputElement: HTMLInputElement|HTMLTextAreaElement = null;
constructor(props: SweetAlertProps) {
super(props);
if (this.props.beforeUpdate) {
this.unsupportedProp('beforeUpdate', 'use props.afterUpdate');
}
const newState: SweetAlertState = Object.assign(SweetAlert.getDefaultState(), {
hideTimeoutHandlerFunc: this.hideTimeoutHandler.bind(this)
});
if (this.props.defaultValue != null) {
newState.inputValue = this.props.defaultValue;
}
this.state = newState;
this.props.beforeMount();
}
componentDidMount() {
document.body.classList.add('sweetalert-overflow-hidden');
this.focusInput();
if (this.props.afterMount) {
this.props.afterMount();
}
}
static generateId(): string {
return '' + Date.now() + Math.ceil(Math.random() * 10000000000) + Math.ceil(Math.random() * 10000000000);
}
static getDefaultState(): SweetAlertState {
return {
id: SweetAlert.generateId(),
show: true,
focusConfirmBtn: true,
focusCancelBtn: false,
inputValue: '',
showValidationMessage: false,
timer: null,
animation: "",
prevTimeout: 0,
closingAction: null,
dependencies: [],
}
}
static getDerivedStateFromProps(nextProps: SweetAlertProps, nextState: SweetAlertState) {
if (_resetting[nextState.id]) {
return {};
}
let newState = {};
const typeChanged = nextState.type !== SweetAlert.getTypeFromProps(nextProps);
const dependenciesChanged = nextState.dependencies !== nextProps.dependencies;
const timeoutChanged = nextState.prevTimeout !== nextProps.timeout;
// if the type of the alert changed, or the dependencies changed, then update the state from props
if (typeChanged || dependenciesChanged) {
newState = {
...newState,
...SweetAlert.getStateFromProps(nextProps),
};
}
// if the state is changing, or the timeout changed, then reset the timeout timer
if (JSON.stringify(newState) !== '{}' || timeoutChanged) {
newState = {
...newState,
...SweetAlert.handleTimeout(nextProps, nextState.timer)
};
}
// return the partially updated state
return {
...newState,
...SweetAlert.handleAnimState(nextProps, nextState, nextState.hideTimeoutHandlerFunc),
};
}
componentDidUpdate(prevProps: SweetAlertProps, prevState: SweetAlertState) {
if (this.props.beforeUpdate) {
this.props.beforeUpdate(prevProps, prevState);
}
if (!prevState.show && this.state.show) {
this.focusInput();
}
this.props.afterUpdate(this.props, this.state);
}
componentWillUnmount() {
document.body.classList.remove('sweetalert-overflow-hidden');
if (this.state.timer) {
clearTimeout(this.state.timer);
}
if (this.props.beforeUnmount) {
this.props.beforeUnmount();
}
}
hideTimeoutHandler(time: number) {
setTimeout(() => {
const closingAction = this.state.closingAction;
/**
* Removing the closing action (shouldn't trigger another animation timeout)
*/
this.setState({ show: false, closingAction: null }, (): void => {
// handle the action that was started before the closing animation was started
switch (closingAction) {
case 'confirm':
this.onConfirm(false);
break;
case 'cancel':
this.onCancel(false);
break;
default:
break;
}
});
}, time);
};
static handleTimeout(props: SweetAlertProps, currentTimer: any) {
if (currentTimer) {
clearTimeout(currentTimer);
}
if (props.timeout && props.timeout > 0) {
const timer: any = setTimeout(() => props.onConfirm(), props.timeout);
return { timer: timer, prevTimeout: props.timeout };
}
return null;
}
static isAnimation(animProp?: boolean|SweetAlertAnimationProps): boolean {
return animProp && typeof animProp !== 'boolean';
}
static animationFromProp(animProp: SweetAlertAnimationProps) {
return animProp.name + ' ' + animProp.duration + 'ms';
}
static handleAnimState(props: SweetAlertProps, state: SweetAlertState, hideTimeout: Function) {
const userDefinedShow = typeof props.show === 'boolean';
let show = (userDefinedShow && !state.closingAction) ? props.show : state.show;
let animation = '';
if (show) {
if (props.openAnim) {
if (SweetAlert.isAnimation(props.openAnim)) {
animation = SweetAlert.animationFromProp(props.openAnim as SweetAlertAnimationProps);
} else if (SweetAlert.isAnimation(SweetAlert.defaultProps.openAnim)) {
animation = SweetAlert.animationFromProp(SweetAlert.defaultProps.openAnim as SweetAlertAnimationProps);
}
}
} else if (state.closingAction && props.closeAnim) {
let animProp: SweetAlertAnimationProps;
if (SweetAlert.isAnimation(props.closeAnim)) {
animProp = props.closeAnim as SweetAlertAnimationProps;
} else if (SweetAlert.isAnimation(SweetAlert.defaultProps.closeAnim)) {
animProp = SweetAlert.defaultProps.closeAnim as SweetAlertAnimationProps;
}
if (animProp) {
animation = SweetAlert.animationFromProp(animProp);
hideTimeout(animProp.duration);
show = true;
}
}
return { show, animation };
};
static getStateFromProps = (props: SweetAlertProps) => {
const type = SweetAlert.getTypeFromProps(props);
return {
type,
focusConfirmBtn: props.focusConfirmBtn && type !== 'input',
focusCancelBtn: props.focusCancelBtn && type !== 'input',
dependencies: props.dependencies,
};
};
static getTypeFromProps = (props: SweetAlertProps) => {
if (props.type) return props.type;
if (props.secondary) return 'secondary';
if (props.info) return 'info';
if (props.success) return 'success';
if (props.warning) return 'warning';
if (props.danger || props.error) return 'danger';
if (props.input) return 'input';
if (props.custom) return 'custom';
return 'default';
};
unsupportedProp = (oldProp: string, message: string) => {
try {
console.warn(`react-bootstrap-sweetalert: Unsupported prop '${oldProp}'. Please ${message}`);
} catch (e) {
// do nothing
}
};
focusInput = () => {
debugLogger('inputElement', this.inputElement);
if (this.inputElement) {
debugLogger('inputElement trying to focus', this.inputElement);
try {
this.inputElement.focus();
} catch (e) {
debugLogger('inputElement focus error', e);
// whoops
}
}
}
getIcon = (): React.ReactNode => {
switch (this.state.type) {
case 'danger':
case 'error':
return <ErrorIcon />;
case 'warning':
return <WarningIcon />;
case 'info':
return <InfoIcon />;
case 'success':
return <SuccessIcon />;
case 'custom':
if (this.props.customIcon) {
if (typeof this.props.customIcon == 'string') {
return <CustomIcon iconUrl={this.props.customIcon} />
}
return this.props.customIcon;
}
return null;
default:
return null;
}
};
onChangeInput = (e: React.ChangeEvent) => {
const target = e.target as HTMLTextAreaElement|HTMLInputElement;
this.setState({
inputValue: target.value,
showValidationMessage: false
});
};
isValidInput = () => {
if (!this.props.required) {
return true;
}
const regex = this.props.validationRegex || (this.props.inputType === 'email' ? Patterns.emailRegex : Patterns.defaultRegex);
return regex.test(this.state.inputValue);
};
isDisabled = (): boolean => {
return this.props.onCancel && this.props.disabled;
};
onAlertClose = (callback: () => void) => {
_resetting[this.state.id] = true;
debugLogger('onAlertClose resetting state');
this.setState({
...SweetAlert.getDefaultState(),
id: this.state.id,
}, () => {
_resetting[this.state.id] = false;
callback();
});
};
beforeCloseAlert = (closingAction: 'confirm'|'cancel', callback: () => void) => {
debugLogger('in beforeCloseAlert: setting show to false');
this.setState({ show: false, closingAction }, (): void => {
debugLogger('state updated', this.state.show);
if (!this.state.show) {
debugLogger('invoking callback');
callback();
}
});
};
onConfirm = (handleCloseAnimations: boolean = true) => {
if (this.isDisabled()) {
return;
}
// if this is an input alert, then we will send the input value to the props.onConfirm function
const isInput: boolean = this.state.type === 'input';
const inputValue: string = this.state.inputValue;
// if this is a controlled alert, then we will send the dependencies value to the props.onConfirm function
const isControlled: boolean = this.state.type === 'controlled';
const dependencies: any[] = [...this.state.dependencies];
if (isInput && !this.isValidInput()) {
this.setState({
showValidationMessage: true
});
return;
}
const confirm = (): void => {
debugLogger('in confirm callback');
if (isInput) {
this.onAlertClose(() => {
this.props.onConfirm(inputValue);
});
} else if (isControlled) {
this.onAlertClose(() => {
this.props.onConfirm(dependencies);
});
} else {
this.onAlertClose(() => this.props.onConfirm());
}
};
if (handleCloseAnimations) {
debugLogger('calling beforeCloseAlert');
this.beforeCloseAlert('confirm', () => confirm());
} else {
confirm();
}
};
onCancel = (handleCloseAnimations: boolean = true) => {
const cancel = (): void => {
this.onAlertClose(() => {
if (this.props.onCancel) {
this.props.onCancel();
}
});
};
if (handleCloseAnimations) {
this.beforeCloseAlert('cancel', () => cancel());
} else {
cancel();
}
};
onInputKeyDown = (e: React.KeyboardEvent) => {
if (e.keyCode == 13) {
e.stopPropagation();
this.onConfirm();
}
};
onKeyDown = (e: React.KeyboardEvent) => {
if (e.keyCode == 27) {
if (this.props.allowEscape && this.props.onCancel) {
e.stopPropagation();
this.onCancel();
}
}
};
onClickInside = (e: React.MouseEvent) => {
e.stopPropagation();
};
onClickOutside = () => {
if (this.props.closeOnClickOutside && this.props.onCancel) {
this.onCancel();
}
};
setAutoFocusInputRef = (element: HTMLInputElement|HTMLTextAreaElement) => {
this.inputElement = element;
};
getComposedStyle = (): CSSProperties => {
return Object.assign(
{},
SWEET_ALERT_DEFAULT_STYLES,
this.props.style,
{ animation: this.state.animation }
);
};
getAlertContent = (): ReactNode => {
// Support for render props for content of alert
if (typeof this.props.children === 'function') {
const renderProps: SweetAlertRenderProps = {
onEnterKeyDownConfirm: (event: React.KeyboardEvent) => {
if (event.key === 'Enter') {
event.preventDefault();
event.stopPropagation();
this.onConfirm();
}
},
confirm: () => this.onConfirm(),
cancel: () => this.onCancel(),
setAutoFocusInputRef: this.setAutoFocusInputRef.bind(this),
}
return this.props.children(renderProps);
}
return this.props.children;
};
getCloseButton = (): ReactNode => {
if (!this.props.showCloseButton || !this.props.onCancel) {
return null;
}
return (
<span
className='btn'
style={Object.assign({}, styles.closeButton, this.props.closeBtnStyle)}
onClick={() => this.onCancel()}
>x</span>
);
};
getInputField = (): ReactNode => {
if (this.state.type !== 'input') {
return null;
}
return (
<Input
{...this.props}
{...this.state}
type={this.state.type}
onInputKeyDown={this.onInputKeyDown}
onChangeInput={this.onChangeInput}
/>
);
};
getValidationMessage = (): ReactNode => {
if (!this.state.showValidationMessage) {
return null;
}
return <ValidationMessage {...this.props} />;
};
getButtons = (): ReactNode => {
return (
<Buttons
{...this.props}
type={this.state.type}
onConfirm={this.onConfirm}
onCancel={this.onCancel}
focusConfirmBtn={this.state.focusConfirmBtn}
focusCancelBtn={this.state.focusCancelBtn}
disabled={this.isDisabled()}
/>
);
};
getInjectedStyles = (): ReactNode => {
return (
<>
<style type="text/css" dangerouslySetInnerHTML={{
__html: `
body.sweetalert-overflow-hidden {
overflow: hidden;
}
body .sweet-alert button {
outline: none !important;
}
`
}}
/>
<style type="text/css">
{`<Inject>../css/animations.css</Inject>`}
</style>
</>
);
};
render() {
if (!this.state.show) {
return null;
}
return (
<div>
{this.getInjectedStyles()}
<Overlay
show={!this.props.hideOverlay}
onClick={this.onClickOutside}
onKeyDown={this.onKeyDown}
>
<div
style={this.getComposedStyle()}
tabIndex={0}
onKeyDown={this.onKeyDown}
onClick={this.onClickInside}
className={'sweet-alert ' + this.props.customClass}
>
{this.getCloseButton()}
{this.getIcon()}
<Title>{this.props.title}</Title>
<Content>{this.getAlertContent()}</Content>
{this.getInputField()}
{this.getValidationMessage()}
{this.getButtons()}
</div>
</Overlay>
</div>
);
}
} | the_stack |
import type { RegExpVisitor } from "regexpp/visitor"
import type { Assertion, Element, Alternative, Quantifier } from "regexpp/ast"
import type { RegExpContext } from "../utils"
import { quantToString, createRule, defineRegexpVisitor } from "../utils"
import type {
FirstLookChar,
MatchingDirection,
ReadonlyFlags,
} from "regexp-ast-analysis"
import {
isPotentiallyEmpty,
getMatchingDirectionFromAssertionKind,
getFirstCharAfter,
getFirstConsumedChar,
getFirstConsumedCharAfter,
isZeroLength,
FirstConsumedChars,
} from "regexp-ast-analysis"
import { mention } from "../utils/mention"
/**
* Returns whether the given assertions is guaranteed to always trivially
* reject or accept.
*
* @param assertion
*/
function isTrivialAssertion(
assertion: Assertion,
dir: MatchingDirection,
flags: ReadonlyFlags,
): boolean {
if (assertion.kind !== "word") {
if (getMatchingDirectionFromAssertionKind(assertion.kind) !== dir) {
// This assertion doesn't assert anything in that direction, so
// it's the same as trivially accepting
return true
}
}
if (assertion.kind === "lookahead" || assertion.kind === "lookbehind") {
if (isPotentiallyEmpty(assertion.alternatives)) {
// The assertion is guaranteed to trivially accept/reject.
return true
}
}
const look = FirstConsumedChars.toLook(
getFirstConsumedChar(assertion, dir, flags),
)
if (look.char.isEmpty || look.char.isAll) {
// trivially rejecting or accepting (based on the first char)
return true
}
const after = getFirstCharAfter(assertion, dir, flags)
if (!after.edge) {
if (look.exact && look.char.isSupersetOf(after.char)) {
// trivially accepting
return true
}
if (look.char.isDisjointWith(after.char)) {
// trivially rejecting
return true
}
}
return false
}
/**
* Returns the next elements always reachable from the given element without
* consuming characters
*/
function* getNextElements(
start: Element,
dir: MatchingDirection,
): Iterable<Element> {
let element = start
for (;;) {
const parent = element.parent
if (
parent.type === "CharacterClass" ||
parent.type === "CharacterClassRange"
) {
return
}
if (parent.type === "Quantifier") {
if (parent.max === 1) {
element = parent
continue
} else {
return
}
}
const elements = parent.elements
const index = elements.indexOf(element)
const inc = dir === "ltr" ? 1 : -1
for (let i = index + inc; i >= 0 && i < elements.length; i += inc) {
const e = elements[i]
yield e
if (!isZeroLength(e)) {
return
}
}
// we have to check the grand parent
const grandParent = parent.parent
if (
(grandParent.type === "Group" ||
grandParent.type === "CapturingGroup" ||
(grandParent.type === "Assertion" &&
getMatchingDirectionFromAssertionKind(grandParent.kind) !==
dir)) &&
grandParent.alternatives.length === 1
) {
element = grandParent
continue
}
return
}
}
/**
* Goes through the given element and all of its children until a the condition
* returns true or a character is (potentially) consumed.
*/
function tryFindContradictionIn(
element: Element,
dir: MatchingDirection,
condition: (e: Element | Alternative) => boolean,
): boolean {
if (condition(element)) {
return true
}
if (element.type === "CapturingGroup" || element.type === "Group") {
// Go into the alternatives of groups
let some = false
element.alternatives.forEach((a) => {
if (tryFindContradictionInAlternative(a, dir, condition)) {
some = true
}
})
return some
}
if (element.type === "Quantifier" && element.max === 1) {
// Go into the element of quantifiers if their maximum is 1
return tryFindContradictionIn(element.element, dir, condition)
}
if (
element.type === "Assertion" &&
(element.kind === "lookahead" || element.kind === "lookbehind") &&
getMatchingDirectionFromAssertionKind(element.kind) === dir
) {
// Go into the alternatives of lookarounds if they point in the same
// direction. E.g. ltr and (?=a).
// Since we don't consume characters, we want to keep going even if we
// find a contradiction inside the lookaround.
element.alternatives.forEach((a) =>
tryFindContradictionInAlternative(a, dir, condition),
)
}
return false
}
/**
* Goes through all elements of the given alternative until the condition
* returns true or a character is (potentially) consumed.
*/
function tryFindContradictionInAlternative(
alternative: Alternative,
dir: MatchingDirection,
condition: (e: Element | Alternative) => boolean,
): boolean {
if (condition(alternative)) {
return true
}
const { elements } = alternative
const first = dir === "ltr" ? 0 : elements.length
const inc = dir === "ltr" ? 1 : -1
for (let i = first; i >= 0 && i < elements.length; i += inc) {
const e = elements[i]
if (tryFindContradictionIn(e, dir, condition)) {
return true
}
if (!isZeroLength(e)) {
break
}
}
return false
}
/**
* Returns whether the 2 look chars are disjoint (== mutually exclusive).
*/
function disjoint(a: FirstLookChar, b: FirstLookChar): boolean {
if (a.edge && b.edge) {
// both accept the edge
return false
}
return a.char.isDisjointWith(b.char)
}
export default createRule("no-contradiction-with-assertion", {
meta: {
docs: {
description: "disallow elements that contradict assertions",
category: "Possible Errors",
// TODO Switch to recommended in the major version.
// recommended: true,
recommended: false,
},
schema: [],
messages: {
alternative:
"The alternative {{ alt }} can never be entered because it contradicts with the assertion {{ assertion }}. Either change the alternative or assertion to resolve the contradiction.",
cannotEnterQuantifier:
"The quantifier {{ quant }} can never be entered because its element contradicts with the assertion {{ assertion }}. Change or remove the quantifier or change the assertion to resolve the contradiction.",
alwaysEnterQuantifier:
"The quantifier {{ quant }} is always entered despite having a minimum of 0. This is because the assertion {{ assertion }} contradicts with the element(s) after the quantifier. Either set the minimum to 1 ({{ newQuant }}) or change the assertion.",
// suggestions
removeQuantifier: "Remove the quantifier.",
changeQuantifier: "Change the quantifier to {{ newQuant }}.",
},
hasSuggestions: true,
type: "problem",
},
create(context) {
/** Create visitor */
function createVisitor(
regexpContext: RegExpContext,
): RegExpVisitor.Handlers {
const {
node,
flags,
getRegexpLocation,
fixReplaceQuant,
fixReplaceNode,
} = regexpContext
/** Analyses the given assertion. */
function analyseAssertion(
assertion: Assertion,
dir: MatchingDirection,
) {
if (isTrivialAssertion(assertion, dir, flags)) {
return
}
const assertionLook = FirstConsumedChars.toLook(
getFirstConsumedChar(assertion, dir, flags),
)
for (const element of getNextElements(assertion, dir)) {
if (tryFindContradictionIn(element, dir, contradicts)) {
break
}
}
/** Whether the alternative contradicts the current assertion. */
function contradictsAlternative(
alternative: Alternative,
): boolean {
let consumed = getFirstConsumedChar(alternative, dir, flags)
if (consumed.empty) {
// This means that we also have to look at the
// characters after the alternative.
consumed = FirstConsumedChars.concat(
[
consumed,
getFirstConsumedCharAfter(
alternative,
dir,
flags,
),
],
flags,
)
}
const look = FirstConsumedChars.toLook(consumed)
if (disjoint(assertionLook, look)) {
context.report({
node,
loc: getRegexpLocation(alternative),
messageId: "alternative",
data: {
assertion: mention(assertion),
alt: mention(alternative),
},
})
return true
}
return false
}
/** Whether the alternative contradicts the current assertion. */
function contradictsQuantifier(quant: Quantifier): boolean {
if (quant.max === 0) {
return false
}
if (quant.min !== 0) {
// all the below condition assume min=0
return false
}
const consumed = getFirstConsumedChar(
quant.element,
dir,
flags,
)
const look = FirstConsumedChars.toLook(consumed)
if (disjoint(assertionLook, look)) {
// This means that we cannot enter the quantifier
// e.g. /(?!a)a*b/
context.report({
node,
loc: getRegexpLocation(quant),
messageId: "cannotEnterQuantifier",
data: {
assertion: mention(assertion),
quant: mention(quant),
},
suggest: [
{
messageId: "removeQuantifier",
fix: fixReplaceNode(quant, ""),
},
],
})
return true
}
const after = getFirstCharAfter(quant, dir, flags)
if (disjoint(assertionLook, after)) {
// This means that we always have to enter the quantifier
// e.g. /(?!a)b*a/
const newQuant = quantToString({ ...quant, min: 1 })
context.report({
node,
loc: getRegexpLocation(quant),
messageId: "alwaysEnterQuantifier",
data: {
assertion: mention(assertion),
quant: mention(quant),
newQuant,
},
suggest: [
{
messageId: "changeQuantifier",
data: { newQuant },
fix: fixReplaceQuant(quant, {
min: 1,
max: quant.max,
}),
},
],
})
return true
}
return false
}
/** Whether the element contradicts the current assertion. */
function contradicts(element: Element | Alternative): boolean {
if (element.type === "Alternative") {
return contradictsAlternative(element)
} else if (element.type === "Quantifier") {
return contradictsQuantifier(element)
}
return false
}
}
return {
onAssertionEnter(assertion) {
analyseAssertion(assertion, "ltr")
analyseAssertion(assertion, "rtl")
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
}) | the_stack |
import { Color } from 'three'
import { RepresentationRegistry } from '../globals'
import MeasurementRepresentation, { parseNestedAtoms, calcArcPoint, MeasurementRepresentationParameters, LabelDataField } from './measurement-representation'
import { defaults } from '../utils'
import MeshBuffer from '../buffer/mesh-buffer'
import TextBuffer, { TextBufferData, TextBufferParameters } from '../buffer/text-buffer'
import WideLineBuffer, { WideLineBufferData } from '../buffer/wideline-buffer'
import { v3add, v3cross, v3dot, v3fromArray, v3length, v3new,
v3normalize, v3sub, v3toArray } from '../math/vector-utils'
import { copyArray, uniformArray, uniformArray3 } from '../math/array-utils'
import { RAD2DEG } from '../math/math-constants'
import { getFixedLengthWrappedDashData } from '../geometry/dash'
import { Structure } from '../ngl';
import Viewer from '../viewer/viewer';
import StructureView from '../structure/structure-view';
import { BufferData } from '../buffer/buffer';
import { StructureRepresentationData, StructureRepresentationParameters } from './structure-representation';
/**
* @typedef {Object} AngleRepresentationParameters - angle representation parameters
* @mixes RepresentationParameters
* @mixes StructureRepresentationParameters
* @mixes MeasurementRepresentationParameters
*
* @property {String} atomTriple - list of triplets of selection strings
* or atom indices
* @property {Boolean} vectorVisible - Indicate the 3 points for each angle by drawing lines 1-2-3
* @property {Boolean} arcVisible - Show the arc outline for each angle
* @property {Number} lineOpacity - opacity for the line part of the representation
* @property {Number} linewidth - width for line part of representation
* @property {Boolean} sectorVisible - Show the filled arc for each angle
*/
export interface AngleRepresentationParameters extends MeasurementRepresentationParameters {
atomTriple: (number|string)[][]
vectorVisible: boolean
arcVisible: boolean
lineOpacity: number
lineWidth: number
sectorVisible: boolean
}
/**
* Angle representation object
*
* Reperesentation consists of four parts, visibility can be set for each
* label - the text label with the angle size
* vectors - lines joining the three points
* sector - triangles representing the angle
* arc - line bordering the sector
*
* @param {Structure} structure - the structure to measure angles in
* @param {Viewer} viewer - a viewer object
* @param {AngleRepresentationParameters} params - angle representation parameters
*/
class AngleRepresentation extends MeasurementRepresentation {
protected atomTriple: (number|string)[][]
protected vectorVisible: boolean
protected arcVisible: boolean
protected lineOpacity: number
protected lineWidth: number
protected sectorVisible: boolean
protected vectorBuffer: WideLineBuffer
arcLength: number
sectorLength: number
arcBuffer: WideLineBuffer
sectorBuffer: MeshBuffer
constructor (structure: Structure, viewer: Viewer, params: Partial<AngleRepresentationParameters>) {
super(structure, viewer, params)
this.type = 'angle'
this.parameters = Object.assign({
atomTriple: {
type: 'hidden', rebuild: true
},
vectorVisible: {
type: 'boolean', default: true
},
arcVisible: {
type: 'boolean', default: true
},
sectorVisible: {
type: 'boolean', default: true
}
}, this.parameters)
this.init(params)
}
init (params: Partial<AngleRepresentationParameters>) {
const p = params || {}
p.side = defaults(p.side, 'double')
p.opacity = defaults(p.opacity, 0.5)
this.atomTriple = defaults(p.atomTriple, [])
this.arcVisible = defaults(p.arcVisible, true)
this.sectorVisible = defaults(p.sectorVisible, true)
this.vectorVisible = defaults(p.vectorVisible, true)
super.init(p)
}
createData (sview: StructureView) {
if (!sview.atomCount || !this.atomTriple.length) return
const atomPosition = atomTriplePositions(sview, this.atomTriple)
const angleData = getAngleData(atomPosition)
const n = this.n = angleData.labelPosition.length / 3
const labelColor = new Color(this.labelColor)
// Create buffers
this.textBuffer = new TextBuffer({
position: angleData.labelPosition,
size: uniformArray(n, this.labelSize),
color: uniformArray3(n, labelColor.r, labelColor.g, labelColor.b),
text: angleData.labelText
} as TextBufferData, this.getLabelBufferParams() as TextBufferParameters)
const c = new Color(this.colorValue)
this.vectorBuffer = new WideLineBuffer(
getFixedLengthWrappedDashData({
position1: angleData.vectorPosition1,
position2: angleData.vectorPosition2,
color: uniformArray3(2 * n, c.r, c.g, c.b),
color2: uniformArray3(2 * n, c.r, c.g, c.b)
} as WideLineBufferData),
this.getBufferParams({
linewidth: this.linewidth,
visible: this.vectorVisible,
opacity: this.lineOpacity
})
)
this.arcLength = angleData.arcPosition1.length / 3
this.arcBuffer = new WideLineBuffer(
getFixedLengthWrappedDashData({
position1: angleData.arcPosition1,
position2: angleData.arcPosition2,
color: uniformArray3(this.arcLength, c.r, c.g, c.b),
color2: uniformArray3(this.arcLength, c.r, c.g, c.b)
} as WideLineBufferData), this.getBufferParams({
linewidth: this.linewidth,
visible: this.arcVisible,
opacity: this.lineOpacity
}))
this.sectorLength = angleData.sectorPosition.length / 3
this.sectorBuffer = new MeshBuffer({
position: angleData.sectorPosition,
color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
} as BufferData, this.getBufferParams({
visible: this.sectorVisible
}))
return {
bufferList: [
this.textBuffer,
this.vectorBuffer,
this.arcBuffer,
this.sectorBuffer
]
}
}
updateData (what: LabelDataField & {color?: boolean}, data: StructureRepresentationData) {
super.updateData(what, data)
const vectorData = {}
const arcData = {}
const sectorData = {}
if (what.color) {
const c = new Color(this.colorValue)
Object.assign(vectorData, {
color: uniformArray3(this.n * 2, c.r, c.g, c.b),
color2: uniformArray3(this.n * 2, c.r, c.g, c.b)
})
Object.assign(arcData, {
color: uniformArray3(this.arcLength, c.r, c.g, c.b),
color2: uniformArray3(this.arcLength, c.r, c.g, c.b)
})
Object.assign(sectorData, {
color: uniformArray3(this.sectorLength, c.r, c.g, c.b)
})
}
// if (what.sectorOpacity) {
// this.sectorBuffer.opacity = what.sectorOpacity
// }
this.vectorBuffer.setAttributes(vectorData)
this.arcBuffer.setAttributes(arcData)
this.sectorBuffer.setAttributes(sectorData)
}
setParameters (params: Partial<AngleRepresentationParameters>) {
var rebuild = false
var what = {}
super.setParameters(params, what, rebuild)
if (params && (
params.vectorVisible !== undefined ||
params.arcVisible !== undefined ||
params.sectorVisible !== undefined)) {
this.setVisibility(this.visible)
}
if (params && params.lineOpacity) {
this.vectorBuffer.setParameters({ opacity: params.lineOpacity })
this.arcBuffer.setParameters({ opacity: params.lineOpacity })
}
if (params && params.opacity !== undefined) {
this.vectorBuffer.setParameters({ opacity: this.lineOpacity })
this.arcBuffer.setParameters({ opacity: this.lineOpacity })
}
if (params && params.linewidth) {
this.vectorBuffer.setParameters({ linewidth: params.linewidth })
this.arcBuffer.setParameters({ linewidth: params.linewidth })
}
return this
}
setVisibility (value: boolean, noRenderRequest?: boolean) {
super.setVisibility(value, true)
if (this.vectorBuffer) {
this.vectorBuffer.setVisibility(this.vectorVisible && this.visible)
}
if (this.arcBuffer) {
this.arcBuffer.setVisibility(this.arcVisible && this.visible)
}
if (this.sectorBuffer) {
this.sectorBuffer.setVisibility(this.sectorVisible && this.visible)
}
if (!noRenderRequest) this.viewer.requestRender()
return this
}
}
/**
* Ensure mid point does not coincide with first or second
* @param {Float32Array} position 9*nAngle array of coordinates
* @return {Float32Array} Filtered position array, may be shorter
*/
function validatePositions (position: Float32Array) {
const include = []
const n = position.length / 9
for (let i = 0; i < n; i++) {
// Check that first point not same as second and that second not same as third
let okay = true
for (let j = i; j < i + 3; j += 3) {
if (position[j] === position[j + 3] &&
position[j + 1] === position[j + 4] &&
position[j + 2] === position[j + 5]) {
okay = false
}
}
if (okay) include.push(i)
}
const outPosition = new Float32Array(include.length * 9)
let outIdx = 0
include.forEach(function (i) {
copyArray(position, outPosition, i * 9, outIdx * 9, 9)
outIdx++
})
return outPosition
}
function atomTriplePositions (sview: StructureView, atomTriple: (number|string)[][]) {
return validatePositions(parseNestedAtoms(sview, atomTriple))
}
/**
* Converts triple positions into data required to build various buffers.
*/
function getAngleData (position: Float32Array, params: Partial<StructureRepresentationParameters> = {}) {
const angleStep = defaults(params.angleStep, Math.PI / 90)
const n = position.length / 9
const angles = new Float32Array(n)
const labelPosition = new Float32Array(n * 3)
const labelText = new Array(n)
const vectorPosition1 = new Float32Array(n * 6) // Two lines per angle
const vectorPosition2 = new Float32Array(n * 6)
const arcPositionTmp1 = new Array(n) // Start points for arc lines
const arcPositionTmp2 = new Array(n) // End points for arc lines
const sectorPositionTmp = new Array(n) // Triangle points
let totalSegments = 0
// Re-used vectors etc
const p1 = v3new() // Positions of points for each angel
const p2 = v3new()
const p3 = v3new()
const v21 = v3new() // Vectors
const v23 = v3new()
const cross = v3new() // Cross product v21xv23
const cross2 = v3new() // In-plane cross product v21 x (v21 x v23)
const labelTmp = v3new()
const arcPoint = v3new()
for (var i = 0; i < n; i++) {
let p = 9 * i
v3fromArray(p1, position, p)
v3fromArray(p2, position, p + 3)
v3fromArray(p3, position, p + 6)
let v = 6 * i
v3toArray(p1, vectorPosition1, v)
v3toArray(p2, vectorPosition2, v)
v3toArray(p2, vectorPosition1, v + 3)
v3toArray(p3, vectorPosition2, v + 3)
v3sub(v21, p1, p2)
v3sub(v23, p3, p2)
v3normalize(v21, v21) // validatePositions ensures valid
v3normalize(v23, v23)
v3cross(cross, v21, v23)
const crossLength = v3length(cross)
const dot = v3dot(v21, v23)
const angle = angles[i] = Math.atan2(crossLength, dot)
labelText[i] = (RAD2DEG * angle).toFixed(1) + String.fromCharCode(0x00B0)
if (v3length(cross) === 0.0) {
// Angle exactly 0/180, pick an arbitrary direction
cross[ 0 ] = 1.0
cross[ 1 ] = 0.0
cross[ 2 ] = 0.0
}
v3cross(cross2, cross, v21)
v3normalize(cross2, cross2)
calcArcPoint(labelTmp, p2, v21, cross2, angle / 2.0)
// TODO: Scale label position?
v3toArray(labelTmp, labelPosition, 3 * i)
// Build the arc and sector
const nSegments = Math.ceil(angle / angleStep)
const sectorVertices = new Float32Array(nSegments * 9)
sectorPositionTmp[ i ] = sectorVertices
const arcVertices1 = new Float32Array(nSegments * 3)
const arcVertices2 = new Float32Array(nSegments * 3)
arcPositionTmp1[ i ] = arcVertices1
arcPositionTmp2[ i ] = arcVertices2
v3add(arcPoint, p2, v21) // Our initial arc point
const appendArcSection = function (a: number, j: number) {
const si = j * 9
const ai = j * 3
v3toArray(p2, sectorVertices, si)
v3toArray(arcPoint, sectorVertices, si + 3)
v3toArray(arcPoint, arcVertices1, ai)
calcArcPoint(arcPoint, p2, v21, cross2, a)
v3toArray(arcPoint, sectorVertices, si + 6)
v3toArray(arcPoint, arcVertices2, ai)
}
let j = 0
for (let a = angleStep; a < angle; a += angleStep) {
appendArcSection(a, j)
j++
}
appendArcSection(angle, j)
totalSegments += nSegments
}
// Flatten nested arrays of arc/segment points
const arcSize = totalSegments * 3
const sectorSize = totalSegments * 9
const arcPosition1 = new Float32Array(arcSize)
const arcPosition2 = new Float32Array(arcSize)
const sectorPosition = new Float32Array(sectorSize)
let sectorOffset = 0
let arcOffset = 0
for (let i = 0; i < n; i++) {
const ap1 = arcPositionTmp1[ i ]
const ap2 = arcPositionTmp2[ i ]
copyArray(ap1, arcPosition1, 0, arcOffset, ap1.length)
copyArray(ap2, arcPosition2, 0, arcOffset, ap2.length)
arcOffset += ap1.length // === ap2.length
const sp = sectorPositionTmp[ i ]
copyArray(sp, sectorPosition, 0, sectorOffset, sp.length)
sectorOffset += sp.length
}
return {
labelPosition,
labelText,
vectorPosition1,
vectorPosition2,
arcPosition1,
arcPosition2,
sectorPosition
}
}
RepresentationRegistry.add('angle', AngleRepresentation)
export default AngleRepresentation | the_stack |
import 'reflect-metadata';
import {
Repository,
getMetadataArgsStorage,
DeepPartial,
SaveOptions,
FindConditions,
FindManyOptions,
FindOneOptions,
ObjectID,
} from 'typeorm';
import { POLYMORPHIC_KEY_SEPARATOR, POLYMORPHIC_OPTIONS } from './constants';
import {
PolymorphicChildType,
PolymorphicParentType,
PolymorphicChildInterface,
PolymorphicOptionsType,
PolymorphicMetadataInterface,
PolymorphicMetadataOptionsInterface,
} from './polymorphic.interface';
import { EntityRepositoryMetadataArgs } from 'typeorm/metadata-args/EntityRepositoryMetadataArgs';
import { RepositoryNotFoundException } from './repository.token.exception';
type PolymorphicHydrationType = {
key: string;
type: 'children' | 'parent';
values: PolymorphicChildInterface[] | PolymorphicChildInterface;
};
const entityTypeColumn = (options: PolymorphicMetadataInterface): string =>
options.entityTypeColumn || 'entityType';
const entityIdColumn = (options: PolymorphicMetadataInterface): string =>
options.entityTypeId || 'entityId';
const PrimaryColumn = (options: PolymorphicMetadataInterface): string =>
options.primaryColumn || 'id';
export abstract class AbstractPolymorphicRepository<E> extends Repository<E> {
private getPolymorphicMetadata(): Array<PolymorphicMetadataInterface> {
const keys = Reflect.getMetadataKeys(
(this.metadata.target as Function)['prototype'],
);
if (!keys) {
return [];
}
return keys.reduce<Array<PolymorphicMetadataInterface>>(
(keys: PolymorphicMetadataInterface[], key: string) => {
if (key.split(POLYMORPHIC_KEY_SEPARATOR)[0] === POLYMORPHIC_OPTIONS) {
const data: PolymorphicMetadataOptionsInterface & {
propertyKey: string;
} = Reflect.getMetadata(
key,
(this.metadata.target as Function)['prototype'],
);
if (data && typeof data === 'object') {
const classType = data.classType();
keys.push({
...data,
classType,
});
}
}
return keys;
},
[],
);
}
protected isPolymorph(): boolean {
return Reflect.hasOwnMetadata(
POLYMORPHIC_OPTIONS,
(this.metadata.target as Function)['prototype'],
);
}
protected isChildren(
options: PolymorphicChildType | PolymorphicParentType,
): options is PolymorphicChildType {
return options.type === 'children';
}
protected isParent(
options: PolymorphicChildType | PolymorphicParentType,
): options is PolymorphicParentType {
return options.type === 'parent';
}
public async hydrateMany(entities: E[]): Promise<E[]> {
return Promise.all(entities.map((ent) => this.hydrateOne(ent)));
}
public async hydrateOne(entity: E): Promise<E> {
const metadata = this.getPolymorphicMetadata();
return this.hydratePolymorphs(entity, metadata);
}
private async hydratePolymorphs(
entity: E,
options: PolymorphicMetadataInterface[],
): Promise<E> {
const values = await Promise.all(
options.map((option: PolymorphicMetadataInterface) =>
this.hydrateEntities(entity, option),
),
);
return values.reduce<E>((e: E, vals: PolymorphicHydrationType) => {
const values =
vals.type === 'parent' && Array.isArray(vals.values)
? vals.values.filter((v) => typeof v !== 'undefined' && v !== null)
: vals.values;
e[vals.key] =
vals.type === 'parent' && Array.isArray(values) ? values[0] : values; // TODO should be condition for !hasMany
return e;
}, entity);
}
private async hydrateEntities(
entity: E,
options: PolymorphicMetadataInterface,
): Promise<PolymorphicHydrationType> {
const entityTypes: (Function | string)[] =
options.type === 'parent'
? [entity[entityTypeColumn(options)]]
: Array.isArray(options.classType)
? options.classType
: [options.classType];
// TODO if not hasMany, should I return if one is found?
const results = await Promise.all(
entityTypes.map((type: Function) =>
this.findPolymorphs(entity, type, options),
),
);
return {
key: options.propertyKey,
type: options.type,
values: (options.hasMany &&
Array.isArray(results) &&
results.length > 0 &&
Array.isArray(results[0])
? results.reduce<PolymorphicChildInterface[]>(
(
resultEntities: PolymorphicChildInterface[],
entities: PolymorphicChildInterface[],
) => entities.concat(...resultEntities),
results as PolymorphicChildInterface[],
)
: results) as PolymorphicChildInterface | PolymorphicChildInterface[],
};
}
private async findPolymorphs(
parent: E,
entityType: Function,
options: PolymorphicMetadataInterface,
): Promise<PolymorphicChildInterface[] | PolymorphicChildInterface | never> {
const repository = this.findRepository(entityType);
return repository[options.hasMany ? 'find' : 'findOne'](
options.type === 'parent'
? {
where: {
id: parent[entityIdColumn(options)],
},
}
: {
where: {
[entityIdColumn(options)]: parent[PrimaryColumn(options)],
[entityTypeColumn(options)]: entityType,
},
},
);
}
private findRepository(
entityType: Function,
): Repository<PolymorphicChildInterface | never> {
const repositoryToken = this.resolveRepositoryToken(entityType);
const repository: Repository<PolymorphicChildInterface> =
repositoryToken !== entityType
? this.manager.getCustomRepository(repositoryToken)
: this.manager.getRepository(repositoryToken);
if (!repository) {
throw new RepositoryNotFoundException(repositoryToken);
}
return repository;
}
private resolveRepositoryToken(token: Function): Function | never {
const tokens = getMetadataArgsStorage().entityRepositories.filter(
(value: EntityRepositoryMetadataArgs) => value.entity === token,
);
return tokens[0] ? tokens[0].target : token;
}
save<T extends DeepPartial<E>>(
entities: T[],
options: SaveOptions & {
reload: false;
},
): Promise<T[]>;
save<T extends DeepPartial<E>>(
entities: T[],
options?: SaveOptions,
): Promise<(T & E)[]>;
save<T extends DeepPartial<E>>(
entity: T,
options?: SaveOptions & {
reload: false;
},
): Promise<T>;
public async save<T extends DeepPartial<E>>(
entityOrEntities: T | Array<T>,
options?: SaveOptions & { reload: false },
): Promise<(T & E) | Array<T & E> | T | Array<T>> {
if (!this.isPolymorph()) {
return Array.isArray(entityOrEntities)
? super.save(entityOrEntities, options)
: super.save(entityOrEntities, options);
}
const metadata = this.getPolymorphicMetadata();
metadata.map((options: PolymorphicOptionsType) => {
if (this.isParent(options)) {
(Array.isArray(entityOrEntities)
? entityOrEntities
: [entityOrEntities]
).map((entity: E | DeepPartial<E>) => {
const parent = entity[options.propertyKey];
if (!parent || entity[entityIdColumn(options)] !== undefined) {
return entity;
}
/**
* Add parent's id and type to child's id and type field
*/
entity[entityIdColumn(options)] = parent[PrimaryColumn(options)];
entity[entityTypeColumn(options)] = parent.constructor.name;
return entity;
});
}
});
/**
* Check deleteBeforeUpdate
*/
Array.isArray(entityOrEntities)
? await Promise.all(
(entityOrEntities as Array<T>).map((entity) =>
this.deletePolymorphs(entity, metadata),
),
)
: await this.deletePolymorphs(entityOrEntities as T, metadata);
return Array.isArray(entityOrEntities)
? super.save(entityOrEntities, options)
: super.save(entityOrEntities, options);
}
private async deletePolymorphs(
entity: DeepPartial<E>,
options: PolymorphicMetadataInterface[],
): Promise<void | never> {
await Promise.all(
options.map(
(option: PolymorphicMetadataInterface) =>
new Promise((resolve) => {
if (!option.deleteBeforeUpdate) {
resolve(Promise.resolve());
}
const entityTypes = Array.isArray(option.classType)
? option.classType
: [option.classType];
// resolve to singular query?
resolve(
Promise.all(
entityTypes.map((type: () => Function | Function[]) => {
const repository = this.findRepository(type);
repository.delete({
[entityTypeColumn(option)]: type,
[entityIdColumn(option)]: entity[PrimaryColumn(option)],
});
}),
),
);
}),
),
);
}
find(options?: FindManyOptions<E>): Promise<E[]>;
find(conditions?: FindConditions<E>): Promise<E[]>;
public async find(
optionsOrConditions?: FindConditions<E> | FindManyOptions<E>,
): Promise<E[]> {
const results = await super.find(optionsOrConditions);
if (!this.isPolymorph()) {
return results;
}
const metadata = this.getPolymorphicMetadata();
return Promise.all(
results.map((entity) => this.hydratePolymorphs(entity, metadata)),
);
}
findOne(
id?: string | number | Date | ObjectID,
options?: FindOneOptions<E>,
): Promise<E | undefined>;
findOne(options?: FindOneOptions<E>): Promise<E | undefined>;
findOne(
conditions?: FindConditions<E>,
options?: FindOneOptions<E>,
): Promise<E | undefined>;
public async findOne(
idOrOptionsOrConditions?:
| string
| number
| Date
| ObjectID
| FindConditions<E>
| FindOneOptions<E>,
optionsOrConditions?: FindConditions<E> | FindOneOptions<E>,
): Promise<E | undefined> {
const polymorphicMetadata = this.getPolymorphicMetadata();
if (Object.keys(polymorphicMetadata).length === 0) {
return idOrOptionsOrConditions &&
(typeof idOrOptionsOrConditions === 'string' ||
typeof idOrOptionsOrConditions === 'number' ||
typeof idOrOptionsOrConditions === 'object') &&
optionsOrConditions
? super.findOne(
idOrOptionsOrConditions as number | string | ObjectID | Date,
optionsOrConditions as FindConditions<E> | FindOneOptions<E>,
)
: super.findOne(
idOrOptionsOrConditions as FindConditions<E> | FindOneOptions<E>,
);
}
const entity =
idOrOptionsOrConditions &&
(typeof idOrOptionsOrConditions === 'string' ||
typeof idOrOptionsOrConditions === 'number' ||
typeof idOrOptionsOrConditions === 'object') &&
optionsOrConditions
? await super.findOne(
idOrOptionsOrConditions as number | string | ObjectID | Date,
optionsOrConditions as FindConditions<E> | FindOneOptions<E>,
)
: await super.findOne(
idOrOptionsOrConditions as FindConditions<E> | FindOneOptions<E>,
);
if (!entity) {
return entity;
}
return this.hydratePolymorphs(entity, polymorphicMetadata);
}
create(): E;
create(entityLikeArray: DeepPartial<E>[]): E[];
create(entityLike: DeepPartial<E>): E;
create(
plainEntityLikeOrPlainEntityLikes?: DeepPartial<E> | DeepPartial<E>[],
): E | E[] {
const metadata = this.getPolymorphicMetadata();
const entity = super.create(plainEntityLikeOrPlainEntityLikes as any);
if (!metadata) {
return entity;
}
metadata.forEach((value: PolymorphicOptionsType) => {
entity[value.propertyKey] =
plainEntityLikeOrPlainEntityLikes[value.propertyKey];
});
return entity;
}
/// TODO implement remove and have an option to delete children/parent
} | the_stack |
import { IStringDictionary, INumberDictionary } from 'vs/base/common/collections';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { IModelService } from 'vs/editor/common/services/model';
import { ILineMatcher, createLineMatcher, ProblemMatcher, IProblemMatch, ApplyToKind, IWatchingPattern, getResource } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import { IMarkerService, IMarkerData, MarkerSeverity } from 'vs/platform/markers/common/markers';
import { generateUuid } from 'vs/base/common/uuid';
import { IFileService } from 'vs/platform/files/common/files';
import { isWindows } from 'vs/base/common/platform';
export const enum ProblemCollectorEventKind {
BackgroundProcessingBegins = 'backgroundProcessingBegins',
BackgroundProcessingEnds = 'backgroundProcessingEnds'
}
export interface IProblemCollectorEvent {
kind: ProblemCollectorEventKind;
}
namespace IProblemCollectorEvent {
export function create(kind: ProblemCollectorEventKind) {
return Object.freeze({ kind });
}
}
export interface IProblemMatcher {
processLine(line: string): void;
}
export abstract class AbstractProblemCollector implements IDisposable {
private matchers: INumberDictionary<ILineMatcher[]>;
private activeMatcher: ILineMatcher | null;
private _numberOfMatches: number;
private _maxMarkerSeverity?: MarkerSeverity;
private buffer: string[];
private bufferLength: number;
private openModels: IStringDictionary<boolean>;
protected readonly modelListeners = new DisposableStore();
private tail: Promise<void> | undefined;
// [owner] -> ApplyToKind
protected applyToByOwner: Map<string, ApplyToKind>;
// [owner] -> [resource] -> URI
private resourcesToClean: Map<string, Map<string, URI>>;
// [owner] -> [resource] -> [markerkey] -> markerData
private markers: Map<string, Map<string, Map<string, IMarkerData>>>;
// [owner] -> [resource] -> number;
private deliveredMarkers: Map<string, Map<string, number>>;
protected _onDidStateChange: Emitter<IProblemCollectorEvent>;
constructor(public readonly problemMatchers: ProblemMatcher[], protected markerService: IMarkerService, protected modelService: IModelService, fileService?: IFileService) {
this.matchers = Object.create(null);
this.bufferLength = 1;
problemMatchers.map(elem => createLineMatcher(elem, fileService)).forEach((matcher) => {
const length = matcher.matchLength;
if (length > this.bufferLength) {
this.bufferLength = length;
}
let value = this.matchers[length];
if (!value) {
value = [];
this.matchers[length] = value;
}
value.push(matcher);
});
this.buffer = [];
this.activeMatcher = null;
this._numberOfMatches = 0;
this._maxMarkerSeverity = undefined;
this.openModels = Object.create(null);
this.applyToByOwner = new Map<string, ApplyToKind>();
for (const problemMatcher of problemMatchers) {
const current = this.applyToByOwner.get(problemMatcher.owner);
if (current === undefined) {
this.applyToByOwner.set(problemMatcher.owner, problemMatcher.applyTo);
} else {
this.applyToByOwner.set(problemMatcher.owner, this.mergeApplyTo(current, problemMatcher.applyTo));
}
}
this.resourcesToClean = new Map<string, Map<string, URI>>();
this.markers = new Map<string, Map<string, Map<string, IMarkerData>>>();
this.deliveredMarkers = new Map<string, Map<string, number>>();
this.modelService.onModelAdded((model) => {
this.openModels[model.uri.toString()] = true;
}, this, this.modelListeners);
this.modelService.onModelRemoved((model) => {
delete this.openModels[model.uri.toString()];
}, this, this.modelListeners);
this.modelService.getModels().forEach(model => this.openModels[model.uri.toString()] = true);
this._onDidStateChange = new Emitter();
}
public get onDidStateChange(): Event<IProblemCollectorEvent> {
return this._onDidStateChange.event;
}
public processLine(line: string) {
if (this.tail) {
const oldTail = this.tail;
this.tail = oldTail.then(() => {
return this.processLineInternal(line);
});
} else {
this.tail = this.processLineInternal(line);
}
}
protected abstract processLineInternal(line: string): Promise<void>;
public dispose() {
this.modelListeners.dispose();
}
public get numberOfMatches(): number {
return this._numberOfMatches;
}
public get maxMarkerSeverity(): MarkerSeverity | undefined {
return this._maxMarkerSeverity;
}
protected tryFindMarker(line: string): IProblemMatch | null {
let result: IProblemMatch | null = null;
if (this.activeMatcher) {
result = this.activeMatcher.next(line);
if (result) {
this.captureMatch(result);
return result;
}
this.clearBuffer();
this.activeMatcher = null;
}
if (this.buffer.length < this.bufferLength) {
this.buffer.push(line);
} else {
const end = this.buffer.length - 1;
for (let i = 0; i < end; i++) {
this.buffer[i] = this.buffer[i + 1];
}
this.buffer[end] = line;
}
result = this.tryMatchers();
if (result) {
this.clearBuffer();
}
return result;
}
protected async shouldApplyMatch(result: IProblemMatch): Promise<boolean> {
switch (result.description.applyTo) {
case ApplyToKind.allDocuments:
return true;
case ApplyToKind.openDocuments:
return !!this.openModels[(await result.resource).toString()];
case ApplyToKind.closedDocuments:
return !this.openModels[(await result.resource).toString()];
default:
return true;
}
}
private mergeApplyTo(current: ApplyToKind, value: ApplyToKind): ApplyToKind {
if (current === value || current === ApplyToKind.allDocuments) {
return current;
}
return ApplyToKind.allDocuments;
}
private tryMatchers(): IProblemMatch | null {
this.activeMatcher = null;
const length = this.buffer.length;
for (let startIndex = 0; startIndex < length; startIndex++) {
const candidates = this.matchers[length - startIndex];
if (!candidates) {
continue;
}
for (const matcher of candidates) {
const result = matcher.handle(this.buffer, startIndex);
if (result.match) {
this.captureMatch(result.match);
if (result.continue) {
this.activeMatcher = matcher;
}
return result.match;
}
}
}
return null;
}
private captureMatch(match: IProblemMatch): void {
this._numberOfMatches++;
if (this._maxMarkerSeverity === undefined || match.marker.severity > this._maxMarkerSeverity) {
this._maxMarkerSeverity = match.marker.severity;
}
}
private clearBuffer(): void {
if (this.buffer.length > 0) {
this.buffer = [];
}
}
protected recordResourcesToClean(owner: string): void {
const resourceSetToClean = this.getResourceSetToClean(owner);
this.markerService.read({ owner: owner }).forEach(marker => resourceSetToClean.set(marker.resource.toString(), marker.resource));
}
protected recordResourceToClean(owner: string, resource: URI): void {
this.getResourceSetToClean(owner).set(resource.toString(), resource);
}
protected removeResourceToClean(owner: string, resource: string): void {
const resourceSet = this.resourcesToClean.get(owner);
resourceSet?.delete(resource);
}
private getResourceSetToClean(owner: string): Map<string, URI> {
let result = this.resourcesToClean.get(owner);
if (!result) {
result = new Map<string, URI>();
this.resourcesToClean.set(owner, result);
}
return result;
}
protected cleanAllMarkers(): void {
this.resourcesToClean.forEach((value, owner) => {
this._cleanMarkers(owner, value);
});
this.resourcesToClean = new Map<string, Map<string, URI>>();
}
protected cleanMarkers(owner: string): void {
const toClean = this.resourcesToClean.get(owner);
if (toClean) {
this._cleanMarkers(owner, toClean);
this.resourcesToClean.delete(owner);
}
}
private _cleanMarkers(owner: string, toClean: Map<string, URI>): void {
const uris: URI[] = [];
const applyTo = this.applyToByOwner.get(owner);
toClean.forEach((uri, uriAsString) => {
if (
applyTo === ApplyToKind.allDocuments ||
(applyTo === ApplyToKind.openDocuments && this.openModels[uriAsString]) ||
(applyTo === ApplyToKind.closedDocuments && !this.openModels[uriAsString])
) {
uris.push(uri);
}
});
this.markerService.remove(owner, uris);
}
protected recordMarker(marker: IMarkerData, owner: string, resourceAsString: string): void {
let markersPerOwner = this.markers.get(owner);
if (!markersPerOwner) {
markersPerOwner = new Map<string, Map<string, IMarkerData>>();
this.markers.set(owner, markersPerOwner);
}
let markersPerResource = markersPerOwner.get(resourceAsString);
if (!markersPerResource) {
markersPerResource = new Map<string, IMarkerData>();
markersPerOwner.set(resourceAsString, markersPerResource);
}
const key = IMarkerData.makeKeyOptionalMessage(marker, false);
let existingMarker;
if (!markersPerResource.has(key)) {
markersPerResource.set(key, marker);
} else if (((existingMarker = markersPerResource.get(key)) !== undefined) && (existingMarker.message.length < marker.message.length) && isWindows) {
// Most likely https://github.com/microsoft/vscode/issues/77475
// Heuristic dictates that when the key is the same and message is smaller, we have hit this limitation.
markersPerResource.set(key, marker);
}
}
protected reportMarkers(): void {
this.markers.forEach((markersPerOwner, owner) => {
const deliveredMarkersPerOwner = this.getDeliveredMarkersPerOwner(owner);
markersPerOwner.forEach((markers, resource) => {
this.deliverMarkersPerOwnerAndResourceResolved(owner, resource, markers, deliveredMarkersPerOwner);
});
});
}
protected deliverMarkersPerOwnerAndResource(owner: string, resource: string): void {
const markersPerOwner = this.markers.get(owner);
if (!markersPerOwner) {
return;
}
const deliveredMarkersPerOwner = this.getDeliveredMarkersPerOwner(owner);
const markersPerResource = markersPerOwner.get(resource);
if (!markersPerResource) {
return;
}
this.deliverMarkersPerOwnerAndResourceResolved(owner, resource, markersPerResource, deliveredMarkersPerOwner);
}
private deliverMarkersPerOwnerAndResourceResolved(owner: string, resource: string, markers: Map<string, IMarkerData>, reported: Map<string, number>): void {
if (markers.size !== reported.get(resource)) {
const toSet: IMarkerData[] = [];
markers.forEach(value => toSet.push(value));
this.markerService.changeOne(owner, URI.parse(resource), toSet);
reported.set(resource, markers.size);
}
}
private getDeliveredMarkersPerOwner(owner: string): Map<string, number> {
let result = this.deliveredMarkers.get(owner);
if (!result) {
result = new Map<string, number>();
this.deliveredMarkers.set(owner, result);
}
return result;
}
protected cleanMarkerCaches(): void {
this._numberOfMatches = 0;
this._maxMarkerSeverity = undefined;
this.markers.clear();
this.deliveredMarkers.clear();
}
public done(): void {
this.reportMarkers();
this.cleanAllMarkers();
}
}
export const enum ProblemHandlingStrategy {
Clean
}
export class StartStopProblemCollector extends AbstractProblemCollector implements IProblemMatcher {
private owners: string[];
private currentOwner: string | undefined;
private currentResource: string | undefined;
constructor(problemMatchers: ProblemMatcher[], markerService: IMarkerService, modelService: IModelService, _strategy: ProblemHandlingStrategy = ProblemHandlingStrategy.Clean, fileService?: IFileService) {
super(problemMatchers, markerService, modelService, fileService);
const ownerSet: { [key: string]: boolean } = Object.create(null);
problemMatchers.forEach(description => ownerSet[description.owner] = true);
this.owners = Object.keys(ownerSet);
this.owners.forEach((owner) => {
this.recordResourcesToClean(owner);
});
}
protected async processLineInternal(line: string): Promise<void> {
const markerMatch = this.tryFindMarker(line);
if (!markerMatch) {
return;
}
const owner = markerMatch.description.owner;
const resource = await markerMatch.resource;
const resourceAsString = resource.toString();
this.removeResourceToClean(owner, resourceAsString);
const shouldApplyMatch = await this.shouldApplyMatch(markerMatch);
if (shouldApplyMatch) {
this.recordMarker(markerMatch.marker, owner, resourceAsString);
if (this.currentOwner !== owner || this.currentResource !== resourceAsString) {
if (this.currentOwner && this.currentResource) {
this.deliverMarkersPerOwnerAndResource(this.currentOwner, this.currentResource);
}
this.currentOwner = owner;
this.currentResource = resourceAsString;
}
}
}
}
interface IBackgroundPatterns {
key: string;
matcher: ProblemMatcher;
begin: IWatchingPattern;
end: IWatchingPattern;
}
export class WatchingProblemCollector extends AbstractProblemCollector implements IProblemMatcher {
private backgroundPatterns: IBackgroundPatterns[];
// workaround for https://github.com/microsoft/vscode/issues/44018
private _activeBackgroundMatchers: Set<string>;
// Current State
private currentOwner: string | undefined;
private currentResource: string | undefined;
private lines: string[] = [];
constructor(problemMatchers: ProblemMatcher[], markerService: IMarkerService, modelService: IModelService, fileService?: IFileService) {
super(problemMatchers, markerService, modelService, fileService);
this.resetCurrentResource();
this.backgroundPatterns = [];
this._activeBackgroundMatchers = new Set<string>();
this.problemMatchers.forEach(matcher => {
if (matcher.watching) {
const key: string = generateUuid();
this.backgroundPatterns.push({
key,
matcher: matcher,
begin: matcher.watching.beginsPattern,
end: matcher.watching.endsPattern
});
}
});
this.modelListeners.add(this.modelService.onModelRemoved(modelEvent => {
let markerChanged: IDisposable | undefined =
Event.debounce(this.markerService.onMarkerChanged, (last: readonly URI[] | undefined, e: readonly URI[]) => {
return (last ?? []).concat(e);
}, 500)(async (markerEvent) => {
markerChanged?.dispose();
markerChanged = undefined;
if (!markerEvent.includes(modelEvent.uri) || (this.markerService.read({ resource: modelEvent.uri }).length !== 0)) {
return;
}
const oldLines = Array.from(this.lines);
for (const line of oldLines) {
await this.processLineInternal(line);
}
});
setTimeout(async () => {
markerChanged?.dispose();
markerChanged = undefined;
}, 600);
}));
}
public aboutToStart(): void {
for (const background of this.backgroundPatterns) {
if (background.matcher.watching && background.matcher.watching.activeOnStart) {
this._activeBackgroundMatchers.add(background.key);
this._onDidStateChange.fire(IProblemCollectorEvent.create(ProblemCollectorEventKind.BackgroundProcessingBegins));
this.recordResourcesToClean(background.matcher.owner);
}
}
}
protected async processLineInternal(line: string): Promise<void> {
if (await this.tryBegin(line) || this.tryFinish(line)) {
return;
}
this.lines.push(line);
const markerMatch = this.tryFindMarker(line);
if (!markerMatch) {
return;
}
const resource = await markerMatch.resource;
const owner = markerMatch.description.owner;
const resourceAsString = resource.toString();
this.removeResourceToClean(owner, resourceAsString);
const shouldApplyMatch = await this.shouldApplyMatch(markerMatch);
if (shouldApplyMatch) {
this.recordMarker(markerMatch.marker, owner, resourceAsString);
if (this.currentOwner !== owner || this.currentResource !== resourceAsString) {
this.reportMarkersForCurrentResource();
this.currentOwner = owner;
this.currentResource = resourceAsString;
}
}
}
public forceDelivery(): void {
this.reportMarkersForCurrentResource();
}
private async tryBegin(line: string): Promise<boolean> {
let result = false;
for (const background of this.backgroundPatterns) {
const matches = background.begin.regexp.exec(line);
if (matches) {
if (this._activeBackgroundMatchers.has(background.key)) {
continue;
}
this._activeBackgroundMatchers.add(background.key);
result = true;
this.lines = [];
this.lines.push(line);
this._onDidStateChange.fire(IProblemCollectorEvent.create(ProblemCollectorEventKind.BackgroundProcessingBegins));
this.cleanMarkerCaches();
this.resetCurrentResource();
const owner = background.matcher.owner;
const file = matches[background.begin.file!];
if (file) {
const resource = getResource(file, background.matcher);
this.recordResourceToClean(owner, await resource);
} else {
this.recordResourcesToClean(owner);
}
}
}
return result;
}
private tryFinish(line: string): boolean {
let result = false;
for (const background of this.backgroundPatterns) {
const matches = background.end.regexp.exec(line);
if (matches) {
if (this._activeBackgroundMatchers.has(background.key)) {
this._activeBackgroundMatchers.delete(background.key);
this.resetCurrentResource();
this._onDidStateChange.fire(IProblemCollectorEvent.create(ProblemCollectorEventKind.BackgroundProcessingEnds));
result = true;
this.lines.push(line);
const owner = background.matcher.owner;
this.cleanMarkers(owner);
this.cleanMarkerCaches();
}
}
}
return result;
}
private resetCurrentResource(): void {
this.reportMarkersForCurrentResource();
this.currentOwner = undefined;
this.currentResource = undefined;
}
private reportMarkersForCurrentResource(): void {
if (this.currentOwner && this.currentResource) {
this.deliverMarkersPerOwnerAndResource(this.currentOwner, this.currentResource);
}
}
public override done(): void {
[...this.applyToByOwner.keys()].forEach(owner => {
this.recordResourcesToClean(owner);
});
super.done();
}
public isWatching(): boolean {
return this.backgroundPatterns.length > 0;
}
} | the_stack |
import {
Resolver,
Query,
Mutation,
Args,
Subscription,
Context,
ResolveField,
Parent
} from '@nestjs/graphql'
import { getMongoRepository } from 'typeorm'
import {
ApolloError,
AuthenticationError,
ForbiddenError,
UserInputError
} from 'apollo-server-core'
import { uuidv4 } from '@utils'
import { User } from '@entities'
import { comparePassword, hashPassword } from '@utils'
import { EmailResolver } from './email.resolver'
import { FileResolver } from './file.resolver'
import {
CreateUserInput,
UpdateUserInput,
LoginUserInput,
Result,
SearchInput,
UserResult,
LoginResponse,
RefreshTokenResponse,
Type,
UserType
} from '../generator/graphql.schema'
import { generateToken, verifyToken, tradeToken } from '@auth'
import { sendMail, stripe } from '@shared'
import { USER_SUBSCRIPTION, STRIPE_PLAN } from '@environments'
@Resolver('User')
export class UserResolver {
constructor(
private readonly emailResolver: EmailResolver,
private readonly fileResolver: FileResolver
) {}
@Query()
async hello(): Promise<string> {
return uuidv4()
// return await 'world'
}
@Query()
async today(): Promise<Date> {
return new Date()
}
@Query()
async search(@Args('conditions') conditions: SearchInput): Promise<Result[]> {
let result
const { select, where, order, skip, take } = conditions
if (Object.keys(where).length > 1) {
throw new UserInputError('Your where must be 1 collection.')
}
const type = Object.keys(where)[0]
// const createdAt = { $gte: 0, $lte: new Date().getTime() }
result = await getMongoRepository(type).find({
where: where[type] && JSON.parse(JSON.stringify(where[type])),
order: order && JSON.parse(JSON.stringify(order)),
skip,
take
})
// console.log(result)
if (result.length === 0) {
throw new ForbiddenError('Not found.')
}
return result
}
@Query()
async searchUser(@Args('userIds') userIds: string[]): Promise<UserResult> {
let result
if (userIds.length === 0) {
throw new UserInputError('userIds can not be blank.')
}
result = await getMongoRepository(User).find({
where: {
_id: { $in: userIds }
}
})
// tslint:disable-next-line:prefer-conditional-expression
if (result.length > 1) {
result = { users: result }
} else {
result = result[0]
}
return result
}
@Query()
async me(@Context('currentUser') currentUser: User): Promise<User> {
return currentUser
}
@Query()
async users(
@Args('offset') offset: number,
@Args('limit') limit: number
): Promise<User[]> {
const users = await getMongoRepository(User).find({
// where: { email: { $nin: ['trinchinchin@gmail.com'] } },
// order: { createdAt: -1 },
skip: offset,
take: limit,
cache: true // 1000: 60000 / 1 minute
})
return users
}
@Query()
async user(@Args('_id') _id: string): Promise<User> {
try {
const user = await getMongoRepository(User).findOne({ _id })
if (!user) {
throw new ForbiddenError('User not found.')
}
return user
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async createUser(
@Args('input') input: CreateUserInput,
@Context('pubsub') pubsub: any,
@Context('req') req: any
): Promise<User> {
try {
const { email, password } = input
let existedUser
existedUser = await getMongoRepository(User).findOne({
where: {
'local.email': email
}
})
if (existedUser) {
throw new ForbiddenError('User already exists.')
}
// Is there a Google account with the same email?
existedUser = await getMongoRepository(User).findOne({
where: {
$or: [{ 'google.email': email }, { 'facebook.email': email }]
}
})
if (existedUser) {
// Let's merge them?
const updateUser = await getMongoRepository(User).save(
new User({
...input,
local: {
email,
password: await hashPassword(password)
}
})
)
return updateUser
}
const createdUser = await getMongoRepository(User).save(
new User({
...input,
local: {
email,
password: await hashPassword(password)
}
})
)
pubsub.publish(USER_SUBSCRIPTION, { userCreated: createdUser })
// const emailToken = await generateEmailToken(createdUser)
const emailToken = await generateToken(createdUser, 'emailToken')
const existedEmail = await this.emailResolver.createEmail({
userId: createdUser._id,
type: Type.VERIFY_EMAIL
})
await sendMail(
'verifyEmail',
createdUser,
req,
emailToken,
existedEmail._id
)
return createdUser
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async updateUser(
@Args('_id') _id: string,
@Args('input') input: UpdateUserInput
): Promise<boolean> {
try {
const { password } = input
const user = await getMongoRepository(User).findOne({ _id })
if (!user) {
throw new ForbiddenError('User not found.')
}
const updateUser = await await getMongoRepository(User).save(
new User({
...user,
...input,
local: {
email: user.local.email,
password: await hashPassword(password)
}
})
)
return updateUser ? true : false
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async updateAvatar(
@Args('_id') _id: string,
@Args('file') file: any
): Promise<boolean> {
try {
const user = await getMongoRepository(User).findOne({ _id })
if (!user) {
throw new ForbiddenError('User not found.')
}
const newFile = await this.fileResolver.uploadFile(file)
const updateUser = await getMongoRepository(User).save(
new User({
...user,
avatar: newFile.path
})
)
return updateUser ? true : false
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async deleteUser(@Args('_id') _id: string): Promise<boolean> {
try {
const user = await getMongoRepository(User).findOne({ _id })
if (!user) {
throw new ForbiddenError('User not found.')
}
const updateUser = await getMongoRepository(User).save(
new User({
...user,
isActive: false
})
)
return updateUser ? true : false
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async deleteUsers(): Promise<boolean> {
try {
return (await getMongoRepository(User).deleteMany({
email: { $nin: ['trinhchinchin@gmail.com'] }
}))
? true
: false
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async verifyEmail(@Args('emailToken') emailToken: string): Promise<boolean> {
// const user = await verifyEmailToken(emailToken)
const user = await verifyToken(emailToken, 'emailToken')
// console.log(user);
if (!user.isVerified) {
const updateUser = await getMongoRepository(User).save(
new User({
...user,
isVerified: true
})
)
return updateUser ? true : false
} else {
throw new ForbiddenError('Your email has been verified.')
}
}
@Mutation()
async login(@Args('input') input: LoginUserInput): Promise<LoginResponse> {
const { email, password } = input
const user = await getMongoRepository(User).findOne({
where: {
'local.email': email
}
})
if (user && (await comparePassword(password, user.local.password))) {
return await tradeToken(user)
}
throw new AuthenticationError('Login failed.')
}
@Mutation()
async refreshToken(
@Args('refreshToken') refreshToken: string
): Promise<RefreshTokenResponse> {
const user = await verifyToken(refreshToken, 'refreshToken')
const accessToken = await generateToken(user, 'accessToken')
return { accessToken }
}
@Mutation()
async lockAndUnlockUser(
@Args('_id') _id: string,
@Args('reason') reason: string
): Promise<boolean> {
try {
const user = await getMongoRepository(User).findOne({ _id })
if (!user) {
throw new ForbiddenError('User not found.')
}
const updateUser = await getMongoRepository(User).save(
new User({
...user,
reason: !user.isLocked ? reason : '',
isLocked: !user.isLocked
})
)
return updateUser ? true : false
} catch (error) {
throw new ApolloError(error)
}
}
@Mutation()
async changePassword(
@Args('_id') _id: string,
@Args('currentPassword') currentPassword: string,
@Args('password') password: string
): Promise<boolean> {
const user = await getMongoRepository(User).findOne({ _id })
// console.log(currentPassword , password)
if (!user) {
throw new ForbiddenError('User not found.')
}
if (!(await comparePassword(currentPassword, user.local.password))) {
throw new ForbiddenError('Your current password is missing or incorrect.')
}
if (await comparePassword(password, user.local.password)) {
throw new ForbiddenError(
'Your new password must be different from your previous password.'
)
}
const updateUser = await getMongoRepository(User).save(
new User({
...user,
local: {
password: await hashPassword(password)
}
})
)
return updateUser ? true : false
}
@Mutation()
async forgotPassword(
@Args('email') email: string,
@Context('req') req: any
): Promise<boolean> {
const user = await getMongoRepository(User).findOne({
where: {
'local.email': email,
isVerified: true
}
})
if (!user) {
throw new ForbiddenError('User not found.')
}
const resetPassToken = await generateToken(user, 'resetPassToken')
const existedEmail = await this.emailResolver.createEmail({
userId: user._id,
type: Type.FORGOT_PASSWORD
})
// console.log(existedEmail)
await sendMail(
'forgotPassword',
user,
req,
resetPassToken,
existedEmail._id
)
const date = new Date()
const updateUser = await getMongoRepository(User).save(
new User({
...user,
resetPasswordToken: resetPassToken,
resetPasswordExpires: date.setHours(date.getHours() + 1) // 1 hour
})
)
return updateUser ? true : false
}
@Mutation()
async resetPassword(
@Args('resetPasswordToken') resetPasswordToken: string,
@Args('password') password: string
): Promise<boolean> {
const user = await getMongoRepository(User).findOne({
resetPasswordToken
})
if (!user) {
throw new ForbiddenError('User not found.')
}
if (user.resetPasswordExpires < Date.now()) {
throw new AuthenticationError(
'Reset password token is invalid, please try again.'
)
}
const updateUser = await getMongoRepository(User).save(
new User({
...user,
local: {
email: user.local.email,
password: await hashPassword(password)
},
resetPasswordToken: null,
resetPasswordExpires: null
})
)
return updateUser ? true : false
}
@Mutation()
async createSubscription(
@Args('source') source: string,
@Args('ccLast4') ccLast4: string,
@Context('currentUser') currentUser: User
): Promise<User> {
// console.log(source)
if (currentUser.stripeId) {
throw new ForbiddenError('stripeId already existed.')
}
const email = currentUser.local
? currentUser.local.email
: currentUser.google
? currentUser.google.email
: currentUser.facebook.email
const customer = await stripe.customers.create({
email
// source,
// plan: STRIPE_PLAN!,
})
// console.log(customer)
const user = await getMongoRepository(User).save(
new User({
...currentUser,
stripeId: customer.id,
type: UserType.PREMIUM,
ccLast4
})
)
return user
}
@Mutation()
async changeCreditCard(
@Args('source') source: string,
@Args('ccLast4') ccLast4: string,
@Context('currentUser') currentUser: User
): Promise<User> {
// console.log(source)
if (!currentUser.stripeId || currentUser.type !== UserType.PREMIUM) {
throw new ForbiddenError('User not found.')
}
await stripe.customers.update(currentUser.stripeId, {
source
})
const updateUser = await getMongoRepository(User).save(
new User({
...currentUser,
ccLast4
})
)
return updateUser
}
// @Mutation()
// async cancelSubscription(
// @Context('currentUser') currentUser: User
// ): Promise<User> {
// // console.log(source)
// if (!currentUser.stripeId || currentUser.type !== UserType.PREMIUM) {
// throw new ForbiddenError('User not found.')
// }
// // console.log(currentUser.stripeId)
// const stripeCustomer = await stripe.customers.retrieve(currentUser.stripeId)
// // console.log(stripeCustomer.sources)
// const [subscription] = stripeCustomer.subscriptions.data
// // console.log(subscription)
// await stripe.subscriptions.del(subscription.id)
// await stripe.customers.deleteCard(
// currentUser.stripeId,
// stripeCustomer.default_source as string
// )
// currentUser.stripeId = null
// currentUser.type = UserType.BASIC
// const user = await getMongoRepository(User).save(currentUser)
// return user
// }
@Subscription(() => Object, {
filter: (payload: any, variables: any) => {
// console.log('payload', payload)
// console.log('variables', variables)
// return payload.menuPublishByOrder.currentsite === variables.currentsite
return true
}
})
async newUser(@Context('pubsub') pubsub: any): Promise<User> {
return pubsub.asyncIterator(USER_SUBSCRIPTION)
}
@ResolveField()
async fullName(@Parent() user: User): Promise<string> {
const { firstName, lastName } = user
return `${firstName} ${lastName}`
}
// @ResolveField()
// async local(@Parent() user: User): Promise<object> {
// const { local } = user
// local.password = ''
// return local
// }
@Mutation()
async validateUser(
@Args('text') text: string,
@Args('input') input: CreateUserInput
): Promise<boolean> {
return true
}
} | the_stack |
export const bodyLong01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const bodyLong02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const bodyShort01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const bodyShort02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const caption01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const code01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const code02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const display01: {
"@media (min-width: 42rem)": {
fontSize: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const display02: {
"@media (min-width: 42rem)": {
fontSize: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const display03: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const display04: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const expressiveHeading04: {
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const expressiveHeading05: {
"@media (min-width: 42rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const expressiveParagraph01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lg: {
fontSize: string;
lineHeight: string;
};
lineHeight: string;
max: {
fontSize: string;
lineHeight: string;
};
};
export const fontFamilies: {
mono: string;
sans: string;
sansCondensed: string;
sansHebrew: string;
serif: string;
};
export const fontWeights: {
light: number;
regular: number;
semibold: number;
};
export const heading01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const heading02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const heading03: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const helperText01: {
fontFamily: string;
fontSize: string;
fontStyle: string;
letterSpacing: string;
lineHeight: string;
};
export const label01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
export const productiveHeading04: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const productiveHeading05: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const quotation01: {
"@media (min-width: 42rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
};
"@media (min-width: 66rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const quotation02: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
export const reset: {
body: {
"-moz-osx-font-smoothing": string;
"-webkit-font-smoothing": string;
fontFamily: string;
fontWeight: number;
textRendering: string;
};
html: {
fontSize: string;
};
strong: {
fontWeight: number;
};
};
export const scale: number[];
export const spacing: {
layout01: string;
layout02: string;
layout03: string;
margin01: string;
margin02: string;
margin03: string;
};
export const styles: {
bodyLong01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
bodyLong02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
bodyShort01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
bodyShort02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
caption01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
code01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
code02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
display01: {
"@media (min-width: 42rem)": {
fontSize: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
display02: {
"@media (min-width: 42rem)": {
fontSize: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
display03: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
display04: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
letterSpacing: string;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
expressiveHeading04: {
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
expressiveHeading05: {
"@media (min-width: 42rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
expressiveParagraph01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lg: {
fontSize: string;
lineHeight: string;
};
lineHeight: string;
max: {
fontSize: string;
lineHeight: string;
};
};
heading01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
heading02: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
heading03: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
helperText01: {
fontFamily: string;
fontSize: string;
fontStyle: string;
letterSpacing: string;
lineHeight: string;
};
label01: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: string;
lineHeight: string;
};
productiveHeading04: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
productiveHeading05: {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
quotation01: {
"@media (min-width: 42rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
};
"@media (min-width: 66rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
quotation02: {
"@media (min-width: 42rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 66rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 82rem)": {
fontSize: string;
lineHeight: string;
};
"@media (min-width: 99rem)": {
fontSize: string;
};
fontFamily: string;
fontSize: string;
fontWeight: number;
letterSpacing: number;
lineHeight: string;
};
};
export function fontFamily(
name: string
): {
fontFamily: string;
};
export function fontWeight(
weight: string
): {
fontWeight: number;
};
export function getTypeSize(step: number): number;
export function print(block: object): string;
export namespace fontFamily {
const prototype: {};
}
export namespace fontWeight {
const prototype: {};
}
export namespace getTypeSize {
const prototype: {};
}
export namespace print {
const prototype: {};
} | the_stack |
import '../social/monkey/process';
import * as arraybuffers from '../../arraybuffers/arraybuffers';
import * as crypto from 'crypto';
import * as linefeeder from '../../net/linefeeder';
import * as logging from '../../logging/logging';
import * as queue from '../../handler/queue';
import Pinger from '../../net/pinger';
// https://github.com/borisyankov/DefinitelyTyped/blob/master/ssh2/ssh2-tests.ts
import * as ssh2 from 'ssh2';
var Client = require('ssh2').Client;
declare const freedom: freedom.FreedomInModuleEnv;
var log: logging.Log = new logging.Log('cloud social');
const SSH_SERVER_PORT = 5000;
const ZORK_HOST = 'zork';
const ZORK_PORT = 9000;
// Key under which our contacts are saved in storage.
const STORAGE_KEY = 'cloud-social-contacts';
// Timeout for establishing an SSH connection.
const CONNECT_TIMEOUT_MS = 10000;
// Retry timing for SSH connection establishment.
const INITIAL_CONNECTION_INTERVAL_MS = 500;
const MAX_CONNECTION_INTERVAL_MS = 10000;
// Servers prior to MESSAGE_VERSION 6 (which introduced RC4 obfuscation) didn't
// support the message_version command. Assume such servers are running
// MESSAGE_VERSION=4 (caesar obfuscation).
const DEFAULT_MESSAGE_VERSION = 4;
// Credentials for accessing a cloud instance.
// The serialised, base64 form is distributed amongst users.
export interface Invite {
// Hostname or IP of the cloud instance.
// This is the host on which sshd is running, so it should
// be directly accessible from the client.
host: string;
// Username.
user: string;
// Private key, base64-encoded.
key: string;
// True iff uProxy has root access on the server, i.e. uProxy deployed it.
isAdmin?: boolean;
// Host key that should be used to verify the server, base-64 encoded
// (from known_hosts file or public key)
hostKey?: string;
}
// Type of the object placed, in serialised form, in storage
// under STORAGE_KEY.
interface SavedContacts {
// TODO: remove this, invites are now embedded in contacts.
invites?: Invite[];
contacts?: SavedContact[];
}
// A contact as saved to storage, consisting of the invite
// plus any data fetched from the server on login (effectively,
// this on-demand data is cached here).
interface SavedContact {
invite?: Invite;
description?: string;
version?: number;
}
// State of remote user's relationship to local user.
// Defined in github.com/uProxy/uproxy/blob/dev/src/interfaces/social.ts
//
// For cloud instances, only CLOUD_INSTANCE_CREATED_BY_LOCAL or
// CLOUD_INSTANCE_SHARED_WITH_LOCAL are possible statuses.
enum UserStatus {
FRIEND = 0,
LOCAL_INVITED_BY_REMOTE = 1,
REMOTE_INVITED_BY_LOCAL = 2,
CLOUD_INSTANCE_CREATED_BY_LOCAL = 3,
CLOUD_INSTANCE_SHARED_WITH_LOCAL = 4
}
// Returns a VersionedPeerMessage, as defined in interfaces/social.ts
// in the uProxy repo.
//
// type is a PeerMessageType value (also defined in that file) and
// payload is an arbitrary payload, e.g. an instance message.
// TODO: use typings from the uProxy repo
function makeVersionedPeerMessage(
type:number,
payload:Object,
version?:number) : any {
return {
type: type,
data: payload,
version: version || DEFAULT_MESSAGE_VERSION
};
}
// Returns an InstanceHandshake, as defined in interfaces/social.ts
// in the uProxy repo.
//
// publicKey is deliberately omitted so that uProxy will consider us
// an older client without PGP support and will avoid encrypting
// signalling messages (unnecessary because we are forwarding all the
// messages over an SSH tunnel).
// TODO: use typings from the uProxy repo
function makeInstanceMessage(address:string, description?:string): any {
return {
instanceId: address,
// Shown in the contacts list while the user's list item is expanded
description: description,
consent: {
isRequesting: false,
isOffering: true
},
name: address,
userId: address
};
}
// To see how these fields are handled, see
// generic_core/social.ts#handleUserProfile in the uProxy repo. We omit
// the status field since remote-user.ts#update will use FRIEND as a default.
function makeUserProfile(
address: string,
isAdmin ?:boolean): freedom.Social.UserProfile {
var status = isAdmin ? UserStatus.CLOUD_INSTANCE_CREATED_BY_LOCAL :
UserStatus.CLOUD_INSTANCE_SHARED_WITH_LOCAL;
return {
userId: address,
name: address,
status: status
};
}
// Exposes Zork instances as friends.
//
// Intended for use with the run_cloud.sh script in the uproxy-docker
// repo, which will spin up the expected configuration:
// - an SSH server running on port 5000, with an account named "giver"
// - a Zork instance, accessible from the SSH server at the
// hostname "zork"
//
// Note that since there's no actual uProxy instance running on the
// cloud instance, we are forced to re-implement some of uProxy's
// social code here, namely:
// - we must send a "fake" INSTANCE message in order for uProxy
// to consider the cloud instance online
// - we have to inspect, wrap, and unwrap messages coming back and
// forth since Zork has its own protocol
//
// Additionally, contacts are saved to storage so that we can contact
// them on login and emit a fake instance message for them, making
// them appear online.
//
// TODO: key-based authentication
// TODO: move the social message parsing stuff into Zork
export class CloudSocialProvider {
private storage_: freedom.Storage.Storage = freedom['core.storage']();
// Saved contacts, keyed by host.
private savedContacts_: { [host: string]: SavedContact } = {};
// SSH connections, keyed by host.
private clients_: { [host: string]: Promise<Connection> } = {};
// Map from host to whether it is online. Hosts not in the map are assumed
// to be offline.
private onlineHosts_: { [host: string]: boolean } = {};
// Map from host to intervalId used for monitoring online presence.
private onlinePresenceMonitorIds_: { [host: string]: NodeJS.Timer } = {};
private static PING_INTERVAL_ = 60000;
constructor(private dispatchEvent_: (name: string, args: Object) => void) { }
// Emits the messages necessary to make the user appear online
// in the contacts list.
private notifyOfUser_ = (contact: SavedContact) : void => {
this.dispatchEvent_('onUserProfile', makeUserProfile(
contact.invite.host, contact.invite.isAdmin));
var clientState = this.makeClientState_(contact.invite.host);
this.dispatchEvent_('onClientState', clientState);
if (this.isOnline_(contact.invite.host)) {
// Pretend that we received a message from a remote uProxy client.
this.dispatchEvent_('onMessage', {
from: clientState,
// INSTANCE
message: JSON.stringify(makeVersionedPeerMessage(3000, makeInstanceMessage(
contact.invite.host, contact.description), contact.version))
});
}
}
// Establishes an SSH connection to a server, first shutting down
// any that previously exists. Also emits an instance message,
// allowing fields such as the description be updated on every
// reconnect, and saves the contact to storage.
private reconnect_ = (invite: Invite): Promise<Connection> => {
log.debug('reconnecting to %1', invite.host);
if (invite.host in this.clients_) {
log.debug('closing old connection to %1', invite.host);
this.clients_[invite.host].then((connection: Connection) => {
connection.end();
});
}
const connection = new Connection(invite, (message: Object) => {
// Set the server to online, since we are receiving messages from them.
this.setOnlineStatus_(invite.host, true);
this.dispatchEvent_('onMessage', {
from: this.makeClientState_(invite.host),
// SIGNAL_FROM_SERVER_PEER,
message: JSON.stringify(makeVersionedPeerMessage(3002,
message, connection.getVersion()))
});
});
this.clients_[invite.host] = connection.connect().then(() => {
log.info('connected to zork on %1', invite.host);
// Cloud server is online if a connection has succeeded.
this.setOnlineStatus_(invite.host, true);
// Fetch the banner, if available, then emit an instance message.
connection.getBanner().then((banner: string) => {
if (banner.length < 1) {
log.debug('empty banner, leaving blank');
}
return banner;
}, (e: Error) => {
log.warn('failed to fetch banner: %1', e);
return '';
}).then((banner: string) => {
this.savedContacts_[invite.host] = {
invite: invite,
description: banner,
version: connection.getVersion()
};
this.notifyOfUser_(this.savedContacts_[invite.host]);
this.saveContacts_();
});
return connection;
});
return this.clients_[invite.host];
}
// Loads contacts from storage and emits an instance message for each.
// This makes all of the stored contacts appear online.
private loadContacts_ = () => {
log.debug('loadContacts');
this.savedContacts_ = {};
this.storage_.get(STORAGE_KEY).then((storedString: string) => {
if (!storedString) {
log.debug('no saved contacts');
return;
}
log.debug('loaded contacts: %1', storedString);
try {
var savedContacts: SavedContacts = JSON.parse(storedString);
if (savedContacts.contacts) {
for (let contact of savedContacts.contacts) {
this.savedContacts_[contact.invite.host] = contact;
this.startMonitoringPresence_(contact.invite.host);
this.notifyOfUser_(contact);
}
}
} catch (e) {
log.error('could not parse saved contacts: %1', e.message);
}
}, (e: Error) => {
log.error('could not load contacts: %1', e);
});
}
// Saves contacts to storage.
private saveContacts_ = (): Promise<void> => {
log.debug('saveContacts');
return this.storage_.set(STORAGE_KEY, JSON.stringify(<SavedContacts>{
contacts: Object.keys(this.savedContacts_).map(key => this.savedContacts_[key])
})).then((unused: string) => {
log.debug('saved contacts');
}).catch((e) => {
log.error('could not save contacts: %1', e);
Promise.reject({
message: e.message
});
});
}
public login = (options: freedom.Social.LoginRequest):
Promise<freedom.Social.ClientState> => {
log.debug('login: %1', options);
this.loadContacts_();
// TODO: emit an onUserProfile event, which can include an image URL
// TODO: base this on the user's public key?
// (shown in the "connected accounts" page)
return Promise.resolve(this.makeClientState_('me'));
}
public sendMessage = (destinationClientId: string, message: string): Promise<void> => {
log.debug('sendMessage to %1: %2', destinationClientId, message);
try {
// Messages are serialised VersionedPeerMessages. We need to extract
// the signalling message, which is all Zork understands.
var versionedPeerMessage: any = JSON.parse(message);
if (versionedPeerMessage.type &&
versionedPeerMessage.type === 3001 && // social.PeerMessageType.SIGNAL_FROM_CLIENT_PEER
versionedPeerMessage.data) {
// payload is either an instance of social.ts#SignallingMetadata
// or is an opaque object we should forward to Zork.
var payload = versionedPeerMessage.data;
if (payload.proxyingId) {
// Reset the SSH connection because Zork only supports one
// proxyng session per connection.
// TODO: Do not reconnect if we have just invited
// the instance (safe because all we've done is run ping).
log.info('new proxying session %1', payload.proxyingId);
if (!(destinationClientId in this.savedContacts_)) {
return Promise.reject({
message: 'unknown client ' + destinationClientId
});
}
return this.reconnect_(this.savedContacts_[destinationClientId].invite).then(
(connection: Connection) => {
connection.sendMessage('give');
});
} else {
if (destinationClientId in this.clients_) {
return this.clients_[destinationClientId].then(
(connection: Connection) => {
connection.sendMessage(JSON.stringify(payload));
});
} else {
return Promise.reject({
message: 'unknown client ' + destinationClientId
});
}
}
} else {
return Promise.reject({
message: 'message has no or wrong type field'
});
}
} catch (e) {
return Promise.reject({
message: 'could not de-serialise message: ' + e.message
});
}
}
public clearCachedCredentials = (): Promise<void> => {
return Promise.reject({
message: 'clearCachedCredentials unimplemented'
});
}
public getUsers = (): Promise<freedom.Social.Users> => {
return Promise.reject({
message: 'getUsers unimplemented'
});
}
public getClients = (): Promise<freedom.Social.Clients> => {
return Promise.reject({
message: 'getClients unimplemented'
});
}
public logout = (): Promise<void> => {
log.debug('logout');
for (let address in this.clients_) {
this.clients_[address].then((connection: Connection) => {
connection.end();
});
}
return Promise.resolve();
}
////
// social2
////
// Returns the invite code for the specified server.
public inviteUser = (host: string): Promise<Object> => {
log.debug('inviteUser');
if (!(host in this.savedContacts_)) {
return Promise.reject({
message: 'unknown cloud instance ' + host
});
}
const invite = this.savedContacts_[host].invite;
return Promise.resolve(<Invite>{
host: invite.host,
user: invite.user,
key: invite.key
});
}
// Parses the networkData field, serialised to JSON, of invites.
// The contact is immediately saved and added to the contacts list.
public acceptUserInvitation = (inviteJson: string): Promise<void> => {
log.debug('acceptUserInvitation');
try {
const invite = <Invite>JSON.parse(inviteJson);
this.savedContacts_[invite.host] = {
invite: invite
};
this.startMonitoringPresence_(invite.host);
this.notifyOfUser_(this.savedContacts_[invite.host]);
this.saveContacts_();
return Promise.resolve();
} catch (e) {
return Promise.reject(new Error('could not parse invite code: ' + e.message));
}
}
public blockUser = (userId: string): Promise<void> => {
return Promise.reject({
message: 'blockUser unimplemented'
});
}
// Removes a cloud contact from storage
public removeUser = (host: string): Promise<void> => {
log.debug('removeUser %1', host);
if (!(host in this.savedContacts_)) {
// Do not return an error because result is as expected.
log.warn('cloud contact %1 is not in %2 - cannot remove from storage', host, STORAGE_KEY);
return Promise.resolve();
}
this.stopMonitoringPresence_(host);
// Remove host from savedContacts and clients
delete this.savedContacts_[host];
delete this.clients_[host];
// Update storage with this.savedContacts_
return this.saveContacts_();
}
private startMonitoringPresence_ = (host: string) => {
if (this.onlinePresenceMonitorIds_[host]) {
log.error('unexpected call to startMonitoringPresence_ for ' + host);
return;
}
// Ping server every minute to see if it is online. A server is considered
// online if a connection can be established with the SSH port. We stop
// pinging for presence once the host is online, so as to not give away
// that we are pinging uProxy cloud servers with a regular heartbeat.
const ping = () : Promise<boolean> => {
var pinger = new Pinger(host, SSH_SERVER_PORT);
return pinger.pingOnce().then(() => {
return true;
}).catch(() => {
return false;
}).then((newOnlineValue: boolean) => {
var oldOnlineValue = this.isOnline_(host);
this.setOnlineStatus_(host, newOnlineValue);
if (newOnlineValue !== oldOnlineValue) {
// status changed, emit a new onClientState.
this.notifyOfUser_(this.savedContacts_[host]);
if (newOnlineValue) {
// Connect in the background in order to fetch metadata such as
// the banner (description).
const invite = this.savedContacts_[host].invite;
this.reconnect_(invite).catch((e: Error) => {
log.error('failed to log into cloud server once online: %1', e.message);
});
}
}
});
}
this.onlinePresenceMonitorIds_[host] = setInterval(ping, CloudSocialProvider.PING_INTERVAL_);
// Ping server immediately (so we don't have to wait 1 min for 1st result).
ping();
}
private stopMonitoringPresence_ = (host: string) => {
if (!this.onlinePresenceMonitorIds_[host]) {
// We may have already stopped monitoring presence, e.g. because the
// host has come online.
return;
}
clearInterval(this.onlinePresenceMonitorIds_[host]);
delete this.onlinePresenceMonitorIds_[host];
}
private isOnline_ = (host: string) => {
return host === 'me' || this.onlineHosts_[host] === true;
}
private setOnlineStatus_ = (host: string, isOnline: boolean) => {
this.onlineHosts_[host] = isOnline;
if (isOnline) {
// Stop monitoring presence once the client is online.
this.stopMonitoringPresence_(host);
}
}
// To see how these fields are handled, see
// generic_core/social.ts#handleClient in the uProxy repo.
private makeClientState_ = (address: string) : freedom.Social.ClientState => {
return {
userId: address,
clientId: address,
// https://github.com/freedomjs/freedom/blob/master/interface/social.json
status: this.isOnline_(address) ? 'ONLINE' : 'OFFLINE',
timestamp: Date.now()
};
}
}
enum ConnectionState {
NEW,
CONNECTING,
ESTABLISHING_TUNNEL,
WAITING_FOR_PING,
WAITING_FOR_VERSION,
ESTABLISHED,
TERMINATED
}
class Connection {
private static COMMAND_DELIMITER = arraybuffers.decodeByte(
arraybuffers.stringToArrayBuffer('\n'));
// Number of instances created, for logging purposes.
private static id_ = 0;
private state_ = ConnectionState.NEW;
private connection_ = new Client();
// The tunneled connection, i.e. secure link to Zork.
private tunnel_ :ssh2.Channel;
// Server's MESSAGE_VERSION.
private version_ = DEFAULT_MESSAGE_VERSION;
constructor(
private invite_: Invite,
private received_: (message:Object) => void,
private name_: string = 'tunnel' + Connection.id_++) {}
// TODO: timeout
public connect = (): Promise<void> => {
if (this.state_ !== ConnectionState.NEW) {
return Promise.reject({
message: 'can only connect in NEW state'
});
}
this.state_ = ConnectionState.CONNECTING;
let connectConfig: ssh2.ConnectConfig = {
host: this.invite_.host,
port: SSH_SERVER_PORT,
username: this.invite_.user,
readyTimeout: CONNECT_TIMEOUT_MS,
// Remaining fields only for type-correctness.
tryKeyboard: false,
debug: undefined
};
if (this.invite_.key) {
connectConfig['privateKey'] = new Buffer(this.invite_.key, 'base64');
}
if (this.invite_.hostKey) {
connectConfig.hostHash = 'sha1';
let keyBuffer = new Buffer(this.invite_.hostKey, 'base64');
let expectedHash = crypto.createHash('sha1').update(keyBuffer).digest('hex');
connectConfig.hostVerifier = (keyHash :string) => {
return keyHash === expectedHash;
};
}
return new Promise<void>((F, R) => {
this.connection_.on('ready', () => {
// TODO: set a timeout here, too
this.setState_(ConnectionState.ESTABLISHING_TUNNEL);
this.connection_.forwardOut(
// TODO: since we communicate using the stream, what does this mean?
'127.0.0.1', 0,
ZORK_HOST, ZORK_PORT, (e: Error, tunnel: ssh2.Channel) => {
if (e) {
this.end();
R({
message: 'error establishing tunnel: ' + e.message
});
return;
}
this.setState_(ConnectionState.WAITING_FOR_PING);
var bufferQueue = new queue.Queue<ArrayBuffer, void>();
new linefeeder.LineFeeder(bufferQueue).setSyncHandler((reply: string) => {
log.debug('%1: received message: %2', this.name_, reply);
switch (this.state_) {
case ConnectionState.WAITING_FOR_PING:
if (reply === 'ping') {
this.setState_(ConnectionState.WAITING_FOR_VERSION);
tunnel.write('version\n');
} else {
this.end();
R({
message: 'did not receive ping from server on login: ' + reply
});
}
break;
case ConnectionState.WAITING_FOR_VERSION:
const parsedVersion = parseInt(reply, 10);
if (isNaN(parsedVersion)) {
log.debug('%1: server does not support message_version, assuming %2',
this.name_, this.version_);
this.version_ = DEFAULT_MESSAGE_VERSION;
} else {
log.debug('%1: server is running MESSAGE_VERSION %2',
this.name_, this.version_);
this.version_ = parsedVersion;
}
this.setState_(ConnectionState.ESTABLISHED);
F();
break;
case ConnectionState.ESTABLISHED:
try {
this.received_(JSON.parse(reply));
} catch (e) {
log.warn('%1: could not de-serialise signalling message: %2',
this.invite_, reply);
}
break;
default:
log.warn('%1: did not expect message in state %2: %3',
this.name_, ConnectionState[this.state_], reply);
this.end();
}
});
this.tunnel_ = tunnel;
tunnel.on('data', (buffer: Buffer) => {
// Make a copy before passing to the async queue.
bufferQueue.handle(arraybuffers.bufferToArrayBuffer(new Buffer(buffer)));
}).on('end', () => {
log.debug('%1: tunnel end', this.name_);
}).on('close', (hadError: boolean) => {
log.debug('%1: tunnel close, with%2 error', this.name_, (hadError ? '' : 'out'));
});
tunnel.write('ping\n');
});
}).on('error', (e: Error) => {
// This occurs when:
// - user supplies the wrong credentials
// - host cannot be reached, e.g. non-existant hostname
log.warn('%1: connection error: %2', this.name_, e);
this.setState_(ConnectionState.TERMINATED);
R({
message: 'could not login: ' + e.message
});
}).on('end', () => {
log.debug('%1: connection end', this.name_);
this.setState_(ConnectionState.TERMINATED);
R({
message: 'connection end without ping'
});
}).on('close', (hadError: boolean) => {
log.debug('%1: connection close, with%2 error', this.name_, (hadError ? '' : 'out'));
this.setState_(ConnectionState.TERMINATED);
R({
message: 'connection close without ping'
});
}).connect(connectConfig);
});
}
public sendMessage = (s: string): void => {
if (this.state_ !== ConnectionState.ESTABLISHED) {
throw new Error('can only connect in ESTABLISHED state');
}
this.tunnel_.write(s + '\n');
}
public end = (): void => {
log.debug('%1: close', this.name_);
if (this.state_ !== ConnectionState.TERMINATED) {
this.setState_(ConnectionState.TERMINATED);
this.connection_.end();
}
}
// Fetches the server's description, i.e. /banner.
public getBanner = (): Promise<string> => {
return this.exec_('cat /banner');
}
// Executes a command, fulfilling with the first line of the command's
// output on stdout or rejecting if any output is received on stderr.
// TODO: There is a close event with a return code which
// is probably a better indication of success.
private exec_ = (command: string): Promise<string> => {
log.debug('%1: execute command: %2', this.name_, command);
if (this.state_ !== ConnectionState.ESTABLISHED) {
return Promise.reject({
message: 'can only execute commands in ESTABLISHED state'
});
}
return new Promise<string>((F, R) => {
this.connection_.exec(command, (e: Error, stream: ssh2.Channel) => {
if (e) {
R({
message: 'failed to execute command: ' + e.message
});
return;
}
const stdoutRaw = new queue.Queue<ArrayBuffer, void>();
const stdout = new linefeeder.LineFeeder(stdoutRaw);
stdout.setSyncHandler((line: string) => {
F(line);
});
stream.on('data', (data: Buffer) => {
// Make a copy before passing to the async queue.
stdoutRaw.handle(arraybuffers.bufferToArrayBuffer(new Buffer(data)));
}).stderr.on('data', (data: Buffer) => {
R({
message: 'output received on STDERR: ' + data.toString()
});
}).on('end', () => {
log.debug('%1: exec stream end', this.name_);
stdout.flush();
});
});
});
}
private setState_ = (newState: ConnectionState) => {
log.debug('%1: %2 -> %3', this.name_, ConnectionState[this.state_],
ConnectionState[newState]);
this.state_ = newState;
}
public getState = (): ConnectionState => {
return this.state_;
}
public getVersion = (): number => {
return this.version_;
}
} | the_stack |
import { dispose, Id64String, IDisposable } from "@itwin/core-bentley";
import {
ColorInputProps, ComboBox, ComboBoxHandler, convertHexToRgb, createButton, createCheckBox, createColorInput, createComboBox, createNumericInput,
} from "@itwin/frontend-devtools";
import { FeatureAppearance, FeatureAppearanceProps, LinePixels, RgbColor } from "@itwin/core-common";
import { FeatureOverrideProvider, FeatureSymbology, Viewport } from "@itwin/core-frontend";
import { ToolBarDropDown } from "./ToolBar";
export class Provider implements FeatureOverrideProvider {
private readonly _elementOvrs = new Map<Id64String, FeatureAppearance>();
private _defaultOvrs: FeatureAppearance | undefined;
private readonly _vp: Viewport;
private constructor(vp: Viewport) { this._vp = vp; }
public addFeatureOverrides(ovrs: FeatureSymbology.Overrides, _vp: Viewport): void {
this._elementOvrs.forEach((appearance, elementId) => ovrs.override({ elementId, appearance }));
if (undefined !== this._defaultOvrs)
ovrs.setDefaultOverrides(this._defaultOvrs);
}
public overrideElements(app: FeatureAppearance): void {
for (const id of this._vp.iModel.selectionSet.elements)
this._elementOvrs.set(id, app);
this.sync();
}
public overrideElementsByArray(elementOvrs: any[]): void {
elementOvrs.forEach((eo) => {
const fsa = FeatureAppearance.fromJSON(JSON.parse(eo.fsa) as FeatureAppearanceProps);
if (eo.id === "-default-")
this.defaults = fsa;
else
this._elementOvrs.set(eo.id, fsa);
});
this.sync();
}
public toJSON(): any[] | undefined {
if (0 === this._elementOvrs.size && undefined === this._defaultOvrs)
return undefined;
const elementOvrs: any[] = [];
this._elementOvrs.forEach((value, key) => {
const elem = { id: key, fsa: JSON.stringify(value.toJSON()) };
elementOvrs.push(elem);
});
// Put the default override into the array as well, at the end with a special ID that we can find later.
if (undefined !== this._defaultOvrs) {
const elem = { id: "-default-", fsa: JSON.stringify(this._defaultOvrs.toJSON()) };
elementOvrs.push(elem);
}
return elementOvrs;
}
public clear(): void {
this._elementOvrs.clear();
this._defaultOvrs = undefined;
this.sync();
}
public set defaults(value: FeatureAppearance | undefined) {
this._defaultOvrs = value;
this.sync();
}
private sync(): void { this._vp.setFeatureOverrideProviderChanged(); }
public static get(vp: Viewport): Provider | undefined {
return vp.findFeatureOverrideProvider((x) => x instanceof Provider) as Provider | undefined;
}
public static remove(vp: Viewport): void {
const provider = this.get(vp);
if (provider)
vp.dropFeatureOverrideProvider(provider);
}
public static getOrCreate(vp: Viewport): Provider {
let provider = this.get(vp);
if (undefined === provider) {
provider = new Provider(vp);
vp.addFeatureOverrideProvider(provider);
}
return provider;
}
}
export class Settings implements IDisposable {
private _appearance = FeatureAppearance.defaults;
private readonly _vp: Viewport;
private readonly _parent: HTMLElement;
private readonly _element: HTMLElement;
public constructor(vp: Viewport, parent: HTMLElement) {
this._vp = vp;
this._parent = parent;
this._element = document.createElement("div");
this._element.className = "toolMenu";
this._element.style.cssFloat = "left";
this._element.style.display = "block";
this.addColor(this._element);
this.addTransparency(this._element);
this.addWeight(this._element);
Settings.addStyle(this._element, LinePixels.Invalid, (select: HTMLSelectElement) => this.updateStyle(parseInt(select.value, 10)));
createCheckBox({
parent: this._element,
name: "Ignore Material",
id: "ovr_ignoreMaterial",
handler: (cb) => this.updateIgnoreMaterial(cb.checked ? true : undefined),
});
createCheckBox({
parent: this._element,
name: "Non-locatable",
id: "ovr_nonLocatable",
handler: (cb) => this.updateNonLocatable(cb.checked ? true : undefined),
});
createCheckBox({
parent: this._element,
name: "Emphasized",
id: "ovr_emphasized",
handler: (cb) => this.updateAppearance("emphasized", cb.checked ? true : undefined),
});
createCheckBox({
parent: this._element,
name: "View-dependent transparency",
id: "ovr_viewDep",
handler: (cb) => this.updateAppearance("viewDependentTransparency", cb.checked ? true : undefined),
});
const buttonDiv = document.createElement("div");
buttonDiv.style.textAlign = "center";
createButton({
value: "Apply",
handler: () => this._provider.overrideElements(this._appearance),
parent: buttonDiv,
inline: true,
tooltip: "Apply overrides to selection set",
});
createButton({
value: "Default",
handler: () => this._provider.defaults = this._appearance,
parent: buttonDiv,
inline: true,
tooltip: "Set as default overrides",
});
createButton({
value: "Clear",
handler: () => this._provider.clear(),
parent: buttonDiv,
inline: true,
tooltip: "Remove all overrides",
});
this._element.appendChild(document.createElement("hr"));
this._element.appendChild(buttonDiv);
parent.appendChild(this._element);
}
public dispose(): void {
this._parent.removeChild(this._element);
}
private get _provider() { return Provider.getOrCreate(this._vp); }
// private reset() { this._appearance = FeatureSymbology.Appearance.defaults; }
private updateAppearance(field: "rgb" | "transparency" | "linePixels" | "weight" | "ignoresMaterial" | "nonLocatable" | "emphasized" | "viewDependentTransparency", value: any): void {
const props = this._appearance.toJSON();
props[field] = value;
this._appearance = FeatureAppearance.fromJSON(props);
}
private updateColor(rgb: RgbColor | undefined): void { this.updateAppearance("rgb", rgb); }
private updateTransparency(transparency: number | undefined): void { this.updateAppearance("transparency", transparency); }
private updateWeight(weight: number | undefined): void { this.updateAppearance("weight", weight); }
private updateIgnoreMaterial(ignoresMaterial: true | undefined): void { this.updateAppearance("ignoresMaterial", ignoresMaterial); }
private updateNonLocatable(nonLocatable: true | undefined): void { this.updateAppearance("nonLocatable", nonLocatable); }
private updateStyle(style: LinePixels): void {
const linePixels = LinePixels.Invalid !== style ? style : undefined;
this.updateAppearance("linePixels", linePixels);
}
private addTransparency(parent: HTMLElement): void {
const div = document.createElement("div");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.id = "cb_ovrTrans";
div.appendChild(cb);
const label = document.createElement("label");
label.htmlFor = "cb_ovrTrans";
label.innerText = "Transparency ";
div.appendChild(label);
const num = createNumericInput({
parent: div,
value: 0,
disabled: true,
min: 0,
max: 255,
step: 1,
handler: (value) => this.updateTransparency(value / 255),
});
div.appendChild(num);
cb.addEventListener("click", () => {
num.disabled = !cb.checked;
this.updateTransparency(cb.checked ? parseInt(num.value, 10) / 255 : undefined);
});
parent.appendChild(div);
}
private addWeight(parent: HTMLElement): void {
const div = document.createElement("div");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.id = "cb_ovrWeight";
div.appendChild(cb);
const label = document.createElement("label");
label.htmlFor = "cb_ovrWeight";
label.innerText = "Weight ";
div.appendChild(label);
const num = createNumericInput({
parent: div,
value: 1,
disabled: true,
min: 1,
max: 31,
step: 1,
handler: (value) => this.updateWeight(value),
});
div.appendChild(num);
cb.addEventListener("click", () => {
num.disabled = !cb.checked;
this.updateWeight(cb.checked ? parseInt(num.value, 10) : undefined);
});
parent.appendChild(div);
}
public static addStyle(parent: HTMLElement, value: LinePixels, handler: ComboBoxHandler): ComboBox {
const entries = [
{ name: "Not overridden", value: LinePixels.Invalid },
{ name: "Solid", value: LinePixels.Solid },
{ name: "Hidden Line", value: LinePixels.HiddenLine },
{ name: "Invisible", value: LinePixels.Invisible },
{ name: "Code1", value: LinePixels.Code1 },
{ name: "Code2", value: LinePixels.Code2 },
{ name: "Code3", value: LinePixels.Code3 },
{ name: "Code4", value: LinePixels.Code4 },
{ name: "Code5", value: LinePixels.Code5 },
{ name: "Code6", value: LinePixels.Code6 },
{ name: "Code7", value: LinePixels.Code7 },
];
return createComboBox({
parent,
entries,
id: "ovr_Style",
name: "Style ",
value,
handler,
});
}
private addColor(parent: HTMLElement): void {
const div = document.createElement("div");
const cb = document.createElement("input");
cb.type = "checkbox";
cb.id = "cb_ovrColor";
div.appendChild(cb);
const update = () => this.updateColor(convertHexToRgb(input.value));
const props: ColorInputProps = {
parent: div,
id: "color_ovrColor",
label: "Color",
value: "#ffffff",
display: "inline",
disabled: true,
handler: update,
};
const input: HTMLInputElement = createColorInput(props).input;
cb.addEventListener("click", () => {
input.disabled = !cb.checked;
if (cb.checked)
update();
else
this.updateColor(undefined);
});
parent.appendChild(div);
}
}
export class FeatureOverridesPanel extends ToolBarDropDown {
private readonly _vp: Viewport;
private readonly _parent: HTMLElement;
private _settings?: Settings;
public constructor(vp: Viewport, parent: HTMLElement) {
super();
this._vp = vp;
this._parent = parent;
this.open();
}
public override get onViewChanged(): Promise<void> {
Provider.remove(this._vp);
return Promise.resolve();
}
protected _open(): void { this._settings = new Settings(this._vp, this._parent); }
protected _close(): void { this._settings = dispose(this._settings); }
public get isOpen(): boolean { return undefined !== this._settings; }
} | the_stack |
import {Engine} from '../common/engine';
import {
ALLOC_SPACE_MEMORY_ALLOCATED_KEY,
DEFAULT_VIEWING_OPTION,
expandCallsites,
findRootSize,
mergeCallsites,
OBJECTS_ALLOCATED_KEY,
OBJECTS_ALLOCATED_NOT_FREED_KEY,
PERF_SAMPLES_KEY,
SPACE_MEMORY_ALLOCATED_NOT_FREED_KEY
} from '../common/flamegraph_util';
import {NUM, STR} from '../common/query_result';
import {CallsiteInfo, FlamegraphState} from '../common/state';
import {fromNs} from '../common/time';
import {FlamegraphDetails} from '../frontend/globals';
import {publishFlamegraphDetails} from '../frontend/publish';
import {Controller} from './controller';
import {globals} from './globals';
export interface FlamegraphControllerArgs {
engine: Engine;
}
const MIN_PIXEL_DISPLAYED = 1;
class TablesCache {
private engine: Engine;
private cache: Map<string, string>;
private prefix: string;
private tableId: number;
private cacheSizeLimit: number;
constructor(engine: Engine, prefix: string) {
this.engine = engine;
this.cache = new Map<string, string>();
this.prefix = prefix;
this.tableId = 0;
this.cacheSizeLimit = 10;
}
async getTableName(query: string): Promise<string> {
let tableName = this.cache.get(query);
if (tableName === undefined) {
// TODO(hjd): This should be LRU.
if (this.cache.size > this.cacheSizeLimit) {
for (const name of this.cache.values()) {
await this.engine.query(`drop table ${name}`);
}
this.cache.clear();
}
tableName = `${this.prefix}_${this.tableId++}`;
await this.engine.query(
`create temp table if not exists ${tableName} as ${query}`);
this.cache.set(query, tableName);
}
return tableName;
}
}
export class FlamegraphController extends Controller<'main'> {
private flamegraphDatasets: Map<string, CallsiteInfo[]> = new Map();
private lastSelectedFlamegraphState?: FlamegraphState;
private requestingData = false;
private queuedRequest = false;
private flamegraphDetails: FlamegraphDetails = {};
private cache: TablesCache;
constructor(private args: FlamegraphControllerArgs) {
super('main');
this.cache = new TablesCache(args.engine, 'grouped_callsites');
}
run() {
const selection = globals.state.currentFlamegraphState;
if (!selection || !this.shouldRequestData(selection)) {
return;
}
if (this.requestingData) {
this.queuedRequest = true;
return;
}
this.requestingData = true;
this.assembleFlamegraphDetails(selection);
}
private async assembleFlamegraphDetails(selection: FlamegraphState) {
const selectedFlamegraphState = {...selection};
const flamegraphMetadata = await this.getFlamegraphMetadata(
selection.type,
selectedFlamegraphState.ts,
selectedFlamegraphState.upid);
if (flamegraphMetadata !== undefined) {
Object.assign(this.flamegraphDetails, flamegraphMetadata);
}
// TODO(hjd): Clean this up.
if (this.lastSelectedFlamegraphState &&
this.lastSelectedFlamegraphState.focusRegex !== selection.focusRegex) {
this.flamegraphDatasets.clear();
}
this.lastSelectedFlamegraphState = {...selection};
const expandedId = selectedFlamegraphState.expandedCallsite ?
selectedFlamegraphState.expandedCallsite.id :
-1;
const rootSize = selectedFlamegraphState.expandedCallsite === undefined ?
undefined :
selectedFlamegraphState.expandedCallsite.totalSize;
const key = `${selectedFlamegraphState.upid};${selectedFlamegraphState.ts}`;
try {
const flamegraphData = await this.getFlamegraphData(
key,
selectedFlamegraphState.viewingOption ?
selectedFlamegraphState.viewingOption :
DEFAULT_VIEWING_OPTION,
selection.ts,
selectedFlamegraphState.upid,
selectedFlamegraphState.type,
selectedFlamegraphState.focusRegex);
if (flamegraphData !== undefined && selection &&
selection.kind === selectedFlamegraphState.kind &&
selection.id === selectedFlamegraphState.id &&
selection.ts === selectedFlamegraphState.ts) {
const expandedFlamegraphData =
expandCallsites(flamegraphData, expandedId);
this.prepareAndMergeCallsites(
expandedFlamegraphData,
this.lastSelectedFlamegraphState.viewingOption,
rootSize,
this.lastSelectedFlamegraphState.expandedCallsite);
}
} finally {
this.requestingData = false;
if (this.queuedRequest) {
this.queuedRequest = false;
this.run();
}
}
}
private shouldRequestData(selection: FlamegraphState) {
return selection.kind === 'FLAMEGRAPH_STATE' &&
(this.lastSelectedFlamegraphState === undefined ||
(this.lastSelectedFlamegraphState.id !== selection.id ||
this.lastSelectedFlamegraphState.ts !== selection.ts ||
this.lastSelectedFlamegraphState.type !== selection.type ||
this.lastSelectedFlamegraphState.upid !== selection.upid ||
this.lastSelectedFlamegraphState.viewingOption !==
selection.viewingOption ||
this.lastSelectedFlamegraphState.focusRegex !==
selection.focusRegex ||
this.lastSelectedFlamegraphState.expandedCallsite !==
selection.expandedCallsite));
}
private prepareAndMergeCallsites(
flamegraphData: CallsiteInfo[],
viewingOption: string|undefined = DEFAULT_VIEWING_OPTION,
rootSize?: number, expandedCallsite?: CallsiteInfo) {
this.flamegraphDetails.flamegraph = mergeCallsites(
flamegraphData, this.getMinSizeDisplayed(flamegraphData, rootSize));
this.flamegraphDetails.expandedCallsite = expandedCallsite;
this.flamegraphDetails.viewingOption = viewingOption;
publishFlamegraphDetails(this.flamegraphDetails);
}
async getFlamegraphData(
baseKey: string, viewingOption: string, ts: number, upid: number,
type: string, focusRegex: string): Promise<CallsiteInfo[]> {
let currentData: CallsiteInfo[];
const key = `${baseKey}-${viewingOption}`;
if (this.flamegraphDatasets.has(key)) {
currentData = this.flamegraphDatasets.get(key)!;
} else {
// TODO(hjd): Show loading state.
// Collecting data for drawing flamegraph for selected profile.
// Data needs to be in following format:
// id, name, parent_id, depth, total_size
const tableName =
await this.prepareViewsAndTables(ts, upid, type, focusRegex);
currentData = await this.getFlamegraphDataFromTables(
tableName, viewingOption, focusRegex);
this.flamegraphDatasets.set(key, currentData);
}
return currentData;
}
async getFlamegraphDataFromTables(
tableName: string, viewingOption = DEFAULT_VIEWING_OPTION,
focusRegex: string) {
let orderBy = '';
let totalColumnName: 'cumulativeSize'|'cumulativeAllocSize'|
'cumulativeCount'|'cumulativeAllocCount' = 'cumulativeSize';
let selfColumnName: 'size'|'count' = 'size';
// TODO(fmayer): Improve performance so this is no longer necessary.
// Alternatively consider collapsing frames of the same label.
const maxDepth = 100;
switch (viewingOption) {
case ALLOC_SPACE_MEMORY_ALLOCATED_KEY:
orderBy = `where cumulative_alloc_size > 0 and depth < ${
maxDepth} order by depth, parent_id,
cumulative_alloc_size desc, name`;
totalColumnName = 'cumulativeAllocSize';
selfColumnName = 'size';
break;
case OBJECTS_ALLOCATED_NOT_FREED_KEY:
orderBy = `where cumulative_count > 0 and depth < ${
maxDepth} order by depth, parent_id,
cumulative_count desc, name`;
totalColumnName = 'cumulativeCount';
selfColumnName = 'count';
break;
case OBJECTS_ALLOCATED_KEY:
orderBy = `where cumulative_alloc_count > 0 and depth < ${
maxDepth} order by depth, parent_id,
cumulative_alloc_count desc, name`;
totalColumnName = 'cumulativeAllocCount';
selfColumnName = 'count';
break;
case PERF_SAMPLES_KEY:
case SPACE_MEMORY_ALLOCATED_NOT_FREED_KEY:
orderBy = `where cumulative_size > 0 and depth < ${
maxDepth} order by depth, parent_id,
cumulative_size desc, name`;
totalColumnName = 'cumulativeSize';
selfColumnName = 'size';
break;
default:
break;
}
const callsites = await this.args.engine.query(`
SELECT
id as hash,
IFNULL(IFNULL(DEMANGLE(name), name), '[NULL]') as name,
IFNULL(parent_id, -1) as parentHash,
depth,
cumulative_size as cumulativeSize,
cumulative_alloc_size as cumulativeAllocSize,
cumulative_count as cumulativeCount,
cumulative_alloc_count as cumulativeAllocCount,
map_name as mapping,
size,
count,
IFNULL(source_file, '') as sourceFile,
IFNULL(line_number, -1) as lineNumber
from ${tableName} ${orderBy}`);
const flamegraphData: CallsiteInfo[] = [];
const hashToindex: Map<number, number> = new Map();
const it = callsites.iter({
hash: NUM,
name: STR,
parentHash: NUM,
depth: NUM,
cumulativeSize: NUM,
cumulativeAllocSize: NUM,
cumulativeCount: NUM,
cumulativeAllocCount: NUM,
mapping: STR,
sourceFile: STR,
lineNumber: NUM,
size: NUM,
count: NUM,
});
for (let i = 0; it.valid(); ++i, it.next()) {
const hash = it.hash;
let name = it.name;
const parentHash = it.parentHash;
const depth = it.depth;
const totalSize = it[totalColumnName];
const selfSize = it[selfColumnName];
const mapping = it.mapping;
const highlighted = focusRegex !== '' &&
name.toLocaleLowerCase().includes(focusRegex.toLocaleLowerCase());
const parentId =
hashToindex.has(+parentHash) ? hashToindex.get(+parentHash)! : -1;
let location: string|undefined;
if (/[a-zA-Z]/i.test(it.sourceFile)) {
location = it.sourceFile;
if (it.lineNumber !== -1) {
location += `:${it.lineNumber}`;
}
}
if (depth === maxDepth - 1) {
name += ' [tree truncated]';
}
// Instead of hash, we will store index of callsite in this original array
// as an id of callsite. That way, we have quicker access to parent and it
// will stay unique:
hashToindex.set(hash, i);
flamegraphData.push({
id: i,
totalSize,
depth,
parentId,
name,
selfSize,
mapping,
merged: false,
highlighted,
location
});
}
return flamegraphData;
}
private async prepareViewsAndTables(
ts: number, upid: number, type: string,
focusRegex: string): Promise<string> {
// Creating unique names for views so we can reuse and not delete them
// for each marker.
let focusRegexConditional = '';
if (focusRegex !== '') {
const linkingWord = type === 'perf' ? 'and' : 'where';
focusRegexConditional = `${linkingWord} focus_str = '${focusRegex}'`;
}
/*
* TODO(octaviant) this branching should be eliminated for simplicity.
*/
if (type === 'perf') {
return this.cache.getTableName(
`select id, name, map_name, parent_id, depth, cumulative_size,
cumulative_alloc_size, cumulative_count, cumulative_alloc_count,
size, alloc_size, count, alloc_count, source_file, line_number
from experimental_flamegraph
where profile_type = "${type}" and ts <= ${ts} and upid = ${upid}
${focusRegexConditional}`);
}
return this.cache.getTableName(
`select id, name, map_name, parent_id, depth, cumulative_size,
cumulative_alloc_size, cumulative_count, cumulative_alloc_count,
size, alloc_size, count, alloc_count, source_file, line_number
from experimental_flamegraph(${ts}, ${upid}, '${type}') ${
focusRegexConditional}`);
}
getMinSizeDisplayed(flamegraphData: CallsiteInfo[], rootSize?: number):
number {
const timeState = globals.state.frontendLocalState.visibleState;
let width = (timeState.endSec - timeState.startSec) / timeState.resolution;
// TODO(168048193): Remove screen size hack:
width = Math.max(width, 800);
if (rootSize === undefined) {
rootSize = findRootSize(flamegraphData);
}
return MIN_PIXEL_DISPLAYED * rootSize / width;
}
async getFlamegraphMetadata(type: string, ts: number, upid: number) {
// Don't do anything if selection of the marker stayed the same.
if ((this.lastSelectedFlamegraphState !== undefined &&
((this.lastSelectedFlamegraphState.ts === ts &&
this.lastSelectedFlamegraphState.upid === upid)))) {
return undefined;
}
// Collecting data for more information about profile, such as:
// total memory allocated, memory that is allocated and not freed.
const result = await this.args.engine.query(
`select pid from process where upid = ${upid}`);
const pid = result.firstRow({pid: NUM}).pid;
const startTime = fromNs(ts) - globals.state.traceTime.startSec;
return {ts: startTime, tsNs: ts, pid, upid, type};
}
} | the_stack |
import {
AssignmentExpression,
AssignmentPattern,
AstNode,
CallExpression,
FunctionExpression,
Identifier,
MemberExpression,
NodePath,
ObjectMethod,
ObjectProperty,
OptionalCallExpression,
TSQualifiedName,
TSType,
TSTypeAnnotation,
TSTypeReference,
TypeName,
VariableDeclarator,
} from 'ast-types';
import { JsCodeShift } from 'jscodeshift';
/**
* Catch all identifiers that begin with "use" followed by an uppercase Latin
* character to exclude identifiers like "user".
*/
function isHookName(s: string) {
return /^use[A-Z0-9].*$/.test(s);
}
/**
* We consider hooks to be a hook name identifier or a member expression
* containing a hook name.
*/
function isHook(node: AstNode) {
if (node.type === 'Identifier') {
return isHookName((node as Identifier).name);
} else if (
node.type === 'MemberExpression' &&
!(node as MemberExpression).computed &&
isHook((node as MemberExpression).property)
) {
const obj = (node as MemberExpression).object;
const isPascalCaseNameSpace = /^[A-Z].*/;
return obj.type === 'Identifier' && isPascalCaseNameSpace.test((obj as Identifier).name);
} else {
return false;
}
}
/**
* Checks if the node is a React component name. React component names must
* always start with a non-lowercase letter. So `MyComponent` or `_MyComponent`
* are valid component names for instance.
*/
export function isReactComponentName(node: AstNode): node is Identifier {
if (node.type === 'Identifier') {
return !/^[a-z]/.test((node as Identifier).name);
} else {
return false;
}
}
function isReactFunction(node: AstNode, functionName: string) {
return (
(node.type === 'Identifier' && (node as Identifier).name === functionName) ||
(node.type === 'MemberExpression' &&
(node as MemberExpression).object.type === 'Identifier' &&
((node as MemberExpression).object as Identifier).name === 'React' &&
(node as MemberExpression).property.type === 'Identifier' &&
((node as MemberExpression).property as Identifier).name === functionName)
);
}
/**
* Checks if the node is a callback argument of forwardRef. This render function
* should follow the rules of hooks.
*/
function isForwardRefCallback(path: NodePath<AstNode>) {
const isCallExpr =
path.parent &&
(path.parent.node.type === 'CallExpression' ||
path.parent.node.type === 'OptionalCallExpression');
if (!isCallExpr) {
return false;
}
const node = path.parent.node as CallExpression | OptionalCallExpression;
return !!(node.callee && isReactFunction(node.callee, 'forwardRef'));
}
/**
* Checks if the node is a callback argument of React.memo. This anonymous
* functional component should follow the rules of hooks.
*/
function isMemoCallback(path: NodePath<AstNode>) {
const isCallExpr =
path.parent &&
(path.parent.node.type === 'CallExpression' ||
path.parent.node.type === 'OptionalCallExpression');
if (!isCallExpr) {
return false;
}
const node = path.parent.node as CallExpression | OptionalCallExpression;
return !!(node.callee && isReactFunction(node.callee, 'memo'));
}
/**
* Gets the static name of a function AST node. For function declarations it is
* easy. For anonymous function expressions it is much harder. If you search for
* `IsAnonymousFunctionDefinition()` in the ECMAScript spec you'll find places
* where JS gives anonymous function expressions names. We roughly detect the
* same AST nodes with some exceptions to better fit our usecase.
*/
function getFunctionName(path: NodePath<AstNode>) {
if (
path.node.type === 'FunctionDeclaration' ||
(path.node.type === 'FunctionExpression' && (path.node as FunctionExpression).id)
) {
// function useHook() {}
// const whatever = function useHook() {};
//
// Function declaration or function expression names win over any
// assignment statements or other renames.
return (path.node as FunctionExpression).id;
} else if (
path.node.type === 'FunctionExpression' ||
path.node.type === 'ArrowFunctionExpression'
) {
if (
path.parent.node.type === 'VariableDeclarator' &&
(path.parent.node as VariableDeclarator).init === path.node
) {
// const useHook = () => {};
return (path.parent.node as VariableDeclarator).id;
} else if (
path.parent.node.type === 'AssignmentExpression' &&
(path.parent.node as AssignmentExpression).right === path.node &&
(path.parent.node as AssignmentExpression).operator === '='
) {
// useHook = () => {};
return (path.parent.node as AssignmentExpression).left;
} else if (
path.parent.node.type === 'ObjectProperty' &&
(path.parent.node as ObjectProperty).value === path.node &&
!(path.parent.node as ObjectProperty).computed
) {
// {useHook: () => {}}
return (path.parent.node as ObjectProperty).key;
// NOTE: We could also support `ClassProperty` and `MethodDefinition`
// here to be pedantic. However, hooks in a class are an anti-pattern. So
// we don't allow it to error early.
//
// class {useHook = () => {}}
// class {useHook() {}}
} else if (
path.parent.node.type === 'AssignmentPattern' &&
(path.parent.node as AssignmentPattern).right === path.node
) {
// const {useHook = () => {}} = {};
// ({useHook = () => {}} = {});
//
// Kinda clowny, but we'd said we'd follow spec convention for
// `IsAnonymousFunctionDefinition()` usage.
return (path.parent.node as AssignmentPattern).left;
} else {
return undefined;
}
} else if (path.node.type === 'ObjectMethod' && !(path.node as ObjectMethod).computed) {
// {useHook() {}}
return (path.node as ObjectMethod).key;
} else {
return undefined;
}
}
export function isReactFunctionComponentOrHook(path: NodePath<AstNode>) {
const functionName = getFunctionName(path);
if (functionName) {
if (isReactComponentName(functionName) || isHook(functionName)) {
return true;
}
}
if (isForwardRefCallback(path) || isMemoCallback(path)) {
return true;
}
return false;
}
const invalidHookParents: TypeName[] = [
'WhileStatement',
'DoWhileStatement',
'ForAwaitStatement',
'ForInStatement',
'ForOfStatement',
'ForStatement',
'IfStatement',
'SwitchStatement',
];
export function isInvalidHookParent(path: NodePath<AstNode>) {
return invalidHookParents.includes(path.node.type as any);
}
/**
* We node is inside a hook or function component AND not inside a loop or condition statement.
*
* Note: Preliminary returns up the code path or conditional expressions are NOT checked.
*/
export function isValidHookLocation(path: NodePath<AstNode>) {
let insideReactFunctionComponentOrHook = false;
let currentPath = path.parent;
while (currentPath) {
if (isReactFunctionComponentOrHook(currentPath)) {
insideReactFunctionComponentOrHook = true;
break;
}
if (isInvalidHookParent(currentPath)) {
return false;
}
currentPath = currentPath.parent;
}
return insideReactFunctionComponentOrHook;
}
export function isReactFunctionComponent(path: NodePath<AstNode>) {
const functionName = getFunctionName(path);
if (functionName) {
if (isReactComponentName(functionName) || isHook(functionName)) {
return true;
}
}
if (isForwardRefCallback(path) || isMemoCallback(path)) {
return true;
}
return false;
}
export function isInsideReactFunctionComponentOrHook(path: NodePath<AstNode>) {
while (path) {
if (isReactFunctionComponentOrHook(path)) {
return true;
}
path = path.parent;
}
return false;
}
const FUNCTION_COMPONENT_TYPE_NAME = [
'FunctionComponent',
'FC',
/* deprecated */ 'StatelessComponent',
/* deprecated */ 'SFC',
];
/**
* Takes the identifier: `const Identifier: React.FunctionComponent<Props> = () => {}`;
*
* Check two cases: `const Foo: React.FunctionComponent<Props>` and `const Foo: FunctionComponent<Props>`.
*
* Returns `Props` type.
*/
export function getPropsTypeFromVariableDeclaratorId(
j: JsCodeShift,
variableDeclaratorId: Identifier
) {
if (!variableDeclaratorId.typeAnnotation) {
return null;
}
let propsType: TSType | null = null;
const isIdentifierAnnotation = j.match<TSTypeAnnotation>(variableDeclaratorId.typeAnnotation, {
type: j.TSTypeAnnotation.name,
typeAnnotation: {
type: j.TSTypeReference.name,
typeName: {
type: j.Identifier.name,
} as Identifier,
typeParameters: {
type: j.TSTypeParameterInstantiation.name,
params: {
length: 1,
},
},
} as TSTypeReference,
});
const isQualifiedNameAnnotation = j.match<TSTypeAnnotation>(
variableDeclaratorId.typeAnnotation,
{
type: j.TSTypeAnnotation.name,
typeAnnotation: {
type: j.TSTypeReference.name,
typeName: {
type: j.TSQualifiedName.name,
left: {
type: j.Identifier.name,
name: 'React',
},
right: {
type: j.Identifier.name,
},
} as TSQualifiedName,
typeParameters: {
type: j.TSTypeParameterInstantiation.name,
params: {
length: 1,
},
},
} as TSTypeReference,
}
);
if (isIdentifierAnnotation || isQualifiedNameAnnotation) {
// Validate that the name is one of FUNCTION_COMPONENT_TYPE_NAME, if yes, assign the type
const typeRef = variableDeclaratorId.typeAnnotation!.typeAnnotation as TSTypeReference;
let name;
if (typeRef.typeName.type === j.Identifier.name) {
name = (typeRef.typeName as Identifier).name;
} else {
name = ((typeRef.typeName as TSQualifiedName).right as Identifier).name;
}
if (FUNCTION_COMPONENT_TYPE_NAME.includes(name)) {
propsType = typeRef.typeParameters!.params[0];
}
}
return propsType;
} | the_stack |
import * as path from 'path';
import * as fs from 'fs';
import {
AttributeResolutionDirectiveSet,
CdmCorpusDefinition,
CdmEntityDefinition,
CdmFolderDefinition,
cdmStatusLevel,
resolveOptions,
copyOptions
} from '../../../internal';
import { LocalAdapter } from '../../../Storage';
import { testHelper } from '../../testHelper';
import { AttributeContextExpectedValue, AttributeExpectedValue } from '../../Utilities/ObjectValidator';
/**
* Base class for all the new resolution guidance tests.
*/
// tslint:disable:variable-name
export class CommonTest {
/**
* The path of the SchemaDocs project.
*/
protected static schemaDocsPath: string = testHelper.schemaDocumentsPath;
/**
* The test's data path.
*/
protected static testsSubpath: string = 'Cdm/ResolutionGuidance';
/**
* This method runs the tests with a set expected attributes & attribute context values and validated the actual result.
*/
public static async runTestWithValues(
testName: string,
sourceEntityName: string,
expectedContext_default: AttributeContextExpectedValue,
expectedContext_normalized: AttributeContextExpectedValue,
expectedContext_referenceOnly: AttributeContextExpectedValue,
expectedContext_structured: AttributeContextExpectedValue,
expectedContext_normalized_structured: AttributeContextExpectedValue,
expectedContext_referenceOnly_normalized: AttributeContextExpectedValue,
expectedContext_referenceOnly_structured: AttributeContextExpectedValue,
expectedContext_referenceOnly_normalized_structured: AttributeContextExpectedValue,
expected_default: AttributeExpectedValue[],
expected_normalized: AttributeExpectedValue[],
expected_referenceOnly: AttributeExpectedValue[],
expected_structured: AttributeExpectedValue[],
expected_normalized_structured: AttributeExpectedValue[],
expected_referenceOnly_normalized: AttributeExpectedValue[],
expected_referenceOnly_structured: AttributeExpectedValue[],
expected_referenceOnly_normalized_structured: AttributeExpectedValue[],
): Promise<void> {
try {
const testInputPath: string = testHelper.getInputFolderPath(this.testsSubpath, testName);
let testActualPath: string = testHelper.getActualOutputFolderPath(this.testsSubpath, testName);
let testExpectedPath: string = testHelper.getExpectedOutputFolderPath(this.testsSubpath, testName);
const corpusPath: string = testInputPath.substring(0, testInputPath.length - '/Input'.length);
testActualPath = path.resolve(testActualPath);
testExpectedPath = path.resolve(testExpectedPath);
const corpus: CdmCorpusDefinition = new CdmCorpusDefinition();
corpus.setEventCallback(() => { }, cdmStatusLevel.warning);
corpus.storage.mount('local', new LocalAdapter(corpusPath));
corpus.storage.mount('cdm', new LocalAdapter(this.schemaDocsPath));
corpus.storage.defaultNamespace = 'local';
const outFolderPath: string = `${corpus.storage.adapterPathToCorpusPath(testActualPath)}/`; // interesting 'bug'
const outFolder: CdmFolderDefinition = await corpus.fetchObjectAsync<CdmFolderDefinition>(outFolderPath) as CdmFolderDefinition;
const srcEntityDef: CdmEntityDefinition = await corpus.fetchObjectAsync<CdmEntityDefinition>(`local:/Input/${sourceEntityName}.cdm.json/${sourceEntityName}`);
expect(srcEntityDef)
.toBeTruthy();
let resOpt: resolveOptions;
let resolvedEntityDef: CdmEntityDefinition;
let outputEntityName: string = '';
let outputEntityFileName: string = '';
let entityFileName: string = '';
if (expectedContext_default && expected_default) {
entityFileName = 'd';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>()));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_normalized && expected_normalized) {
entityFileName = 'n';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['normalized'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_referenceOnly && expected_referenceOnly) {
entityFileName = 'ro';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['referenceOnly'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_structured && expected_structured) {
entityFileName = 's';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['structured'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_normalized_structured && expected_normalized_structured) {
entityFileName = 'n_s';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['normalized', 'structured'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_referenceOnly_normalized && expected_referenceOnly_normalized) {
entityFileName = 'ro_n';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['referenceOnly', 'normalized'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_referenceOnly_structured && expected_referenceOnly_structured) {
entityFileName = 'ro_s';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['referenceOnly', 'structured'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
if (expectedContext_referenceOnly_normalized_structured && expected_referenceOnly_normalized_structured) {
entityFileName = 'ro_n_s';
resOpt = new resolveOptions(srcEntityDef.inDocument, new AttributeResolutionDirectiveSet(new Set<string>(['referenceOnly', 'normalized', 'structured'])));
outputEntityName = `${sourceEntityName}_R_${entityFileName}`;
outputEntityFileName = `${outputEntityName}.cdm.json`;
resolvedEntityDef = await srcEntityDef.createResolvedEntityAsync(outputEntityName, resOpt, outFolder);
await this.saveActualEntityAndValidateWithExpected(path.join(testExpectedPath, outputEntityFileName), resolvedEntityDef);
}
} catch (err) {
expect(true)
.toEqual(false);
}
}
/**
* Runs validation to test actual output vs expected output for attributes collection vs attribute context.
*/
protected static async saveActualEntityAndValidateWithExpected(expectedPath: string, actualResolvedEntityDef: CdmEntityDefinition): Promise<void> {
const options: copyOptions = new copyOptions();
options.saveConfigFile = false;
await actualResolvedEntityDef.inDocument.saveAsAsync(actualResolvedEntityDef.inDocument.name, false, options);
const actualPath: string = actualResolvedEntityDef.ctx.corpus.storage.corpusPathToAdapterPath(actualResolvedEntityDef.inDocument.atCorpusPath);
const actualCtx = JSON.parse(fs.readFileSync(actualPath, 'utf8'));
const expectedCtx = JSON.parse(fs.readFileSync(expectedPath, 'utf8'));
testHelper.assertObjectContentEquality(expectedCtx, actualCtx);
}
} | the_stack |
namespace is {
// Local references to global functions (better minification)
var ObjProto = Object.prototype;
var ArrayProto = Array.prototype;
var toString = ObjProto.toString;
var hasOwn = ObjProto.hasOwnProperty;
// in case the browser doesn't have it
var index_of = (
ArrayProto.indexOf ?
function(arr, val) { return arr.indexOf(val); } :
function(arr, val) {
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] === val) {
return i;
}
}
return -1;
}
)
// Primitives - test for type exactness
// typeof is faster; see http://jsperf.com/underscore-js-istype-alternatives/7
// typeof does not catch values made with a constructor, but is still faster than to String
// see : http://jsperf.com/is-js
export function string(s): boolean {
return (typeof s === 'string') || s instanceof String;
}
export function number(n) { return (typeof n === 'number') || n instanceof Number; }
export function boolean(b) { return b === !!b || b instanceof Boolean; }
// non-primitive builtin types
export function fn(f) { return (typeof f === 'function'); };
// array - delegates to builtin if available
export var array = Array.isArray || function(a) { return toString.call(a) === '[object Array]'; };
// basically all Javascript types are objects
export function object(o) { return o === Object(o); };
// duck typing, because there isn't really a good way to do this
export function regex(r) { return !!(r && r.test && r.exec && (r.ignoreCase || r.ignoreCase === false)); };
// HTML elements
export var element: (e) => boolean = (
typeof HTMLElement !== 'undefined' ?
function(e) { return (e instanceof HTMLElement); } :
// https://github.com/documentcloud/underscore/blob/master/underscore.js#L836-838
function(e) { return !!(e && e.nodeType === 1); }
);
// non-strict type checking
// http://dl.dropbox.com/u/35146/js/tests/isNumber.html
export function numeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); };
// plain objects - not a specific type, just an object with key/value pairs
// https://github.com/jquery/jquery/blob/c14a6b385fa419ce67f115e853fb4a89d8bd8fad/src/core.js#L425-452
export function hash(o) {
// fail fast for falsy/non-object/HTMLElement/window objects
// also check constructor properties - objects don't have their own constructor,
// and their constructor does not have its own `isPrototypeOf` function
if (!o || typeof o !== 'object' || is.element(o) || (typeof window !== 'undefined' && o === window) ||
(o.constructor && !hasOwn.call(o, 'constructor') && !hasOwn.call(o.constructor.prototype, 'isPrototypeOf'))
) {
return false;
}
// from jQuery source: speed up the test by cycling to the last property,
// since own properties are iterated over first and therefore the last one will
// indicate the presence of any prototype properties
for (var key in o) { }
return (key === undefined || hasOwn.call(o, key));
};
// test for containment, in both arrays and objects
export function inside(container, val) {
if (is.array(container)) {
return index_of(container, val) > -1;
} else if (is.object(container)) {
for (var prop in container) {
if (hasOwn.call(container, prop) && container[prop] === val) {
return true;
}
}
return false;
} else {
return false;
}
};
// test for variable being undefined or null
export function set(v) { return v !== null && v !== (void 0); };
// test for having any elements (if an array), any properties (if an object), or falsy-ness
export function empty(container) {
if (is.array(container)) {
return container.length === 0;
} else if (is.object(container)) {
// when an object has a valueOf function that doesn't return an object,
// object is empty if value is empty
if (is.fn(container.valueOf) && !is.object(container.valueOf())) {
return is.empty(container.valueOf());
}
for (var x in container) {
if (hasOwn.call(container, x)) {
return false;
}
}
return true;
} else {
return !container;
}
}
}
/**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/
function SHA1(msg: string): string {
function rotate_left(n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
function lsb_hex(val) {
var str = "";
var i;
var vh;
var vl;
for (i = 0; i <= 6; i += 2) {
vh = (val >>> (i * 4 + 4)) & 0x0f;
vl = (val >>> (i * 4)) & 0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
};
function cvt_hex(val) {
var str = "";
var i;
var v;
for (i = 7; i >= 0; i--) {
v = (val >>> (i * 4)) & 0x0f;
str += v.toString(16);
}
return str;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
msg = Utf8Encode(msg);
var msg_len = msg.length;
var word_array = new Array();
for (i = 0; i < msg_len - 3; i += 4) {
j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
word_array.push(j);
}
switch (msg_len % 4) {
case 0:
i = 0x080000000;
break;
case 1:
i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
break;
case 2:
i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
break;
case 3:
i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
break;
}
word_array.push(i);
while ((word_array.length % 16) != 14) word_array.push(0);
word_array.push(msg_len >>> 29);
word_array.push((msg_len << 3) & 0x0ffffffff);
for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for (i = 0; i <= 19; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 20; i <= 39; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 40; i <= 59; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 60; i <= 79; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp2 = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp2.toLowerCase();
}
export class Types {
static STRING: string = 'string';
static NUMBER: string = 'number';
static BOOLEAN: string = 'boolean';
static ARRAY: string = '[]';
}
export class Json2dts {
moduleName: string;
classes: any;
classesCache: { [sha: string]: string };
classesInUse: { [name: string]: number };
constructor() { }
public parse(obj: any, objectName: string = "_RootInterface", moduleName: string = ""): any {
this.moduleName = moduleName;
this.classes = {};
this.classesCache = {};
this.classesInUse = {};
this.analyse_object(obj, objectName);
return this.classes;
}
public getCode() {
var output: string;
var classes: { [name: string]: string } = {};
var outputModule: boolean = this.moduleName == "" ? false : true;
var interfaceTab: string = outputModule ? "\t" : "";
var propertyTab: string = interfaceTab + "\t";
Object.keys(this.classes).map((clsName: string) => {
output = interfaceTab + "interface " + clsName + '\n' + interfaceTab + '{\n';
Object.keys(this.classes[clsName]).map((key: string) => {
/** BAS: added a space `:` => `: ` */
output += propertyTab + key + ': ' + this.classes[clsName][key] + ';\n';
})
output += interfaceTab + '}\n\n';
classes[clsName] = output;
})
output = outputModule ? "module " + this.moduleName + "\n{\n" : "";
Object.keys(classes).sort().forEach((key: string) => { output += classes[key] });
return output + (outputModule ? "\n}" : "");
}
public analyse_object(obj: any, objectName: string = "json"): void {
// determine object name
objectName = this.getInterfaceType(objectName, obj);
// initialize named class object
this.classes[objectName] = this.classes[objectName] || {}
// loops over all object properties and
// determines each property type
Object.keys(obj).map((key: string) => {
var type: string = "string";
var sha: string = "";
var value: any = obj[key];
switch (true) {
case is.string(value): type = Types.STRING; break;
case is.number(value): type = Types.NUMBER; break;
case is.boolean(value): type = Types.BOOLEAN; break;
case is.array(value):
// default typed array
type = "any[]";
// if value is consisten over
// all items of the array
if (this.is_value_consistent(value)) {
// is an empty array
if (this.size(value) == 0) {
type = "any[]"; // EMPTY ARRAY
}
else {
// consistent value is an object?
if (is.object(value[0])) {
type = this.getInterfaceType(key, value[0]) + '[]';
this.analyse_object(value[0], key);
}
// conststent value is a basic type
else {
type = this.getBasicType(value[0]) + '[]';
}
}
}
break;
case is.object(value) && !is.array(value):
// default object type
type = "any";
// if object is not empty
// set as current type and process it
if (!is.empty(value)) {
type = this.getInterfaceType(key, value)
this.analyse_object(value, key);
}
break;
}
// if key has any special char, quote it.
if (this.hasSpecialChars((key))) {
key = '\"' + key + '\"';
}
this.classes[objectName][key] = type;
});
}
private objectParser(key: string) {
}
private getBasicType(value: any): string {
var type: string = Types.STRING;
switch (true) {
case is.string(value): type = Types.STRING; break;
case is.number(value): type = Types.NUMBER; break;
case is.boolean(value): type = Types.BOOLEAN; break;
}
return type;
}
private is_value_consistent = function(o: any): boolean {
if (this.size(o) == 0) {
return true;
}
else {
if (!is.array(o)) {
o = this.values(o);
}
var n = o[0];
var nn = (is.object(n) ? this.generate_signature(n) : typeof n);
return Object.keys(o).every((key) => {
return (is.object(o[key]) ? this.generate_signature(o[key]) : typeof o[key]) == nn;
});
}
}
private getInterfaceType(key: string, value: any): string {
// get a valid className
key = key.replace(/_/gi, ' ').replace(/-/gi, ' ').replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1);
}).replace(/ /gi, '');
// check if a definition exist for the current Interface signature
var currentObjectSignature: string = this.generate_signature(value);
var isKnownClass: boolean = Object.keys(this.classesCache).indexOf(currentObjectSignature) != -1;
// its a know type, return it
if (isKnownClass) return this.classesCache[currentObjectSignature];
// current type name is already used by other Interface
if (this.classesInUse[key] != undefined) {
// update key count
this.classesInUse[key]++;
// initialize Interface Name Object
this.classesCache[currentObjectSignature] = key + this.classesInUse[key];
return this.classesCache[currentObjectSignature];
}
// current Interface Name was never used
this.classesCache[currentObjectSignature] = key;
this.classesInUse[key] = 0;
return key;
}
private size(obj: any): number {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : Object.keys(obj).length;
}
private values(obj: any) {
return Object.keys(obj).map((key) => { return obj[key] });
}
private generate_signature(o: any) {
if (is.object(o)) {
return SHA1(Object.keys(o).map((n) => {
return n.toLowerCase();
}).sort().join('|'));
}
else {
return SHA1(Object.keys(o).map((n) => {
return typeof n;
}).sort().join('|'));
}
}
private hasSpecialChars(str: string): boolean {
return /[ ~`!#$%\^&*+=\-\[\]\\';,\/{}|\\":<>\?]/g.test(str);
}
private keysrt(key: string, desc: boolean = false): (a: string, b: string) => number {
return (a, b) => {
return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
}
}
}
function extractLineFeeds(s: string): string {
return s.replace(/[^\n]+/g, '');
}
export function toValidJSON(input: string, keepLineNumbers: boolean = false): string {
var UNESCAPE_MAP = { '\\"': '"', "\\`": "`", "\\'": "'" };
var ML_ESCAPE_MAP = { '\n': '\\n', "\r": '\\r', "\t": '\\t', '"': '\\"' };
function unescapeQuotes(r) { return UNESCAPE_MAP[r] || r; }
return input.replace(/`(?:\\.|[^`])*`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|\/\*[^]*?\*\/|\/\/.*\n?/g, // pass 1: remove comments
(s: string) => {
if (s.charAt(0) == '/') {
return keepLineNumbers ? extractLineFeeds(s) : '';
}
else {
return s;
}
})
.replace(/(?:true|false|null)(?=[^\w_$]|$)|([a-zA-Z_$][\w_$]*)|`((?:\\.|[^`])*)`|'((?:\\.|[^'])*)'|"(?:\\.|[^"])*"|(,)(?=\s*[}\]])/g, // pass 2: requote
(s: string, identifier: string, multilineQuote: string, singleQuote: string, lonelyComma: boolean) => {
if (lonelyComma) {
return '';
}
else if (identifier != null) {
return '"' + identifier + '"';
}
else if (multilineQuote != null) {
return '"' + multilineQuote.replace(/\\./g, unescapeQuotes).replace(/[\n\r\t"]/g, function(r) { return ML_ESCAPE_MAP[r]; }) +
'"' + (keepLineNumbers ? extractLineFeeds(multilineQuote) : '');
}
else if (singleQuote != null) {
return '"' + singleQuote.replace(/\\./g, unescapeQuotes).replace(/"/g, '\\"') + '"';
}
else {
return s;
}
});
} | the_stack |
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Database from '@ioc:Adonis/Lucid/Database'
import { sanitiseHTML } from 'App/Helpers/utils'
import InvoiceQuotation from 'App/Models/InvoiceQuotation'
import UnitOfMeasurement from 'App/Models/UnitOfMeasurement'
import InvoiceQuotationServices from 'App/Services/InvoiceQuotationServices'
import PuppeteerServices from 'App/Services/PuppeteerServices'
import QuotationValidator from 'App/Validators/QuotationValidator'
import isUUID from 'validator/lib/isUUID'
export default class QuotationsController {
public async index({ response, requestedCompany, request, bouncer }: HttpContextContract) {
await bouncer.with('InvoiceQuotationPolicy').authorize('list')
const {
page,
descending,
perPage,
sortBy,
id,
title,
customer,
tax_percentage,
simple_quantities,
date,
show_discounts,
created_at,
updated_at,
type,
} = request.qs()
const searchQuery = {
id: id ? id : null,
title: title ? title : null,
date: date ? date : null,
customer: customer ? customer : null,
tax_percentage: tax_percentage ? tax_percentage : null,
simple_quantities: simple_quantities ? simple_quantities : null,
show_discounts: show_discounts ? show_discounts : null,
created_at: created_at ? created_at : null,
updated_at: updated_at ? updated_at : null,
}
let subquery = InvoiceQuotation.query()
.select(
'invoices_quotations.id',
'invoices_quotations.title',
'invoices_quotations.type',
'invoices_quotations.date',
'invoices_quotations.tax_percentage',
'invoices_quotations.simple_quantities',
'invoices_quotations.show_discounts',
'invoices_quotations.created_at',
'invoices_quotations.updated_at',
'customers.is_corporate',
'customers.first_name',
'customers.last_name',
'customers.corporate_has_rep',
'customers.company_name',
'customers.company_phone'
)
.select(
Database.rawQuery(
"COALESCE(customers.company_name, CONCAT(customers.first_name, ' ', customers.last_name)) AS customer"
)
)
.where('invoices_quotations.company_id', requestedCompany?.id ?? '')
.where({ type })
.leftJoin('customers', (query) =>
query.on('customers.id', '=', 'invoices_quotations.customer_id')
)
if (sortBy) {
subquery = subquery?.orderBy(sortBy, descending === 'true' ? 'desc' : 'asc')
}
if (searchQuery) {
subquery?.where((query) => {
for (const param in searchQuery) {
if (Object.prototype.hasOwnProperty.call(searchQuery, param)) {
let value = searchQuery[param]
if (value) {
if (value === 'true') value = true
if (value === 'false') value = false
if (param === 'customer') {
query
.where('customers.first_name', '=', `%${value}%`)
.orWhere('customers.last_name', '=', `%${value}%`)
.orWhere('customers.company_name', '=', `%${value}%`)
} else {
query.where(`invoices_quotations.${param}`, value)
if (typeof value === 'string') {
query.orWhere(`invoices_quotations.${param}`, 'like', `%${value}%`)
}
}
}
}
}
})
}
const quotations = await await subquery?.paginate(page ? page : 1, perPage ? perPage : 20)
return response.ok({ data: quotations })
}
public async store({ response, request, bouncer, requestedCompany }: HttpContextContract) {
if (requestedCompany) {
await bouncer.with('InvoiceQuotationPolicy').authorize('create')
const {
items,
additionalFees,
date,
code,
customerId,
customerBillingAddressId,
customerShippingAddressId,
introduction,
title,
simpleQuantities,
amountsAreTaxInclusive,
taxPercentage,
roundAmounts,
roundAmountType,
showDiscounts,
discountType,
setDiscountTypePerLine,
calculateTotals,
changeProductPrices,
numberOfDecimals,
useThousandSeparator,
thousandSeparatorType,
notes,
//theme,
showAdditionalSubtotalDiscount,
additionalDiscountType,
additionalDiscountAmount,
showAdditionalFees,
showImages,
useCustomSerialNumbers,
useEditor,
} = await request.validate(QuotationValidator)
const { type: documentType } = request.qs()
const newQuotation = await requestedCompany?.related('quotations').create({
additionalFees,
date,
code,
customerId,
customerBillingAddress: customerBillingAddressId,
customerShippingAddress: customerShippingAddressId,
introduction: sanitiseHTML(introduction),
title,
simpleQuantities,
amountsAreTaxInclusive,
taxPercentage,
roundAmounts,
roundAmountType,
showDiscounts,
discountType,
setDiscountTypePerLine,
calculateTotals,
changeProductPrices,
numberOfDecimals,
useThousandSeparator,
thousandSeparatorType,
notes: sanitiseHTML(notes),
showAdditionalSubtotalDiscount,
additionalDiscountType,
additionalDiscountAmount,
showAdditionalFees,
showImages,
type: documentType,
useCustomSerialNumbers,
useEditor,
})
const preparedItems: Array<Record<string, unknown>> = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
const itemCollector: Record<string, unknown> = {}
// 1. test if product id is a UUID
const isId = isUUID(item?.productId ?? '', 5)
itemCollector.productId = isId ? item.productId : null
itemCollector.productName = isId ? null : sanitiseHTML(item?.productName)
// 2. Get other fields
itemCollector.description = item.description
itemCollector.sortOrder = i + 1
itemCollector.qty = item.qty
itemCollector.groupQty = item.groupQty
itemCollector.unitPrice = item.unitPrice
itemCollector.unitDiscount = item.unitDiscount
itemCollector.discountType = item.discountType
itemCollector.customSerialNumber = item.customSerialNumber
// 3. Get `unitOfMeasurementId`
const uom = await UnitOfMeasurement.findBy('name', item.UOM)
itemCollector.unitOfMeasurementId = uom?.id
// 4. Get `collectionTypeId`
const colType = await UnitOfMeasurement.findBy('name', item.collectionTypeId)
itemCollector.collectionTypeId = colType?.id
preparedItems.push(itemCollector)
}
await newQuotation.related('items').createMany(preparedItems)
await new InvoiceQuotationServices({
invoiceQuotationModel: newQuotation,
}).clearCache()
return response.created({ data: newQuotation?.id })
} else return response.abort({ message: 'Company not found' })
}
public async show({
response,
requestedInvoiceQuotation,
requestedCompany,
bouncer,
}: HttpContextContract) {
// Check authorisation
await bouncer
.with('InvoiceQuotationPolicy')
.authorize('view', requestedInvoiceQuotation!, requestedCompany!)
const invoiceQuotationDetails = await new InvoiceQuotationServices({
invoiceQuotationModel: requestedInvoiceQuotation,
}).getInvoiceQuotationFullDetails()
return response.ok({ data: invoiceQuotationDetails })
}
public async update({
response,
request,
bouncer,
requestedCompany,
requestedInvoiceQuotation,
}: HttpContextContract) {
if (requestedCompany) {
await bouncer
.with('InvoiceQuotationPolicy')
.authorize('edit', requestedInvoiceQuotation, requestedCompany!)
const {
items,
additionalFees,
date,
code,
customerId,
customerBillingAddressId,
customerShippingAddressId,
introduction,
title,
simpleQuantities,
amountsAreTaxInclusive,
taxPercentage,
roundAmounts,
roundAmountType,
showDiscounts,
discountType,
setDiscountTypePerLine,
calculateTotals,
changeProductPrices,
numberOfDecimals,
useThousandSeparator,
thousandSeparatorType,
notes,
//theme,
showAdditionalSubtotalDiscount,
additionalDiscountType,
additionalDiscountAmount,
showAdditionalFees,
showImages,
useCustomSerialNumbers,
useEditor,
} = await request.validate(QuotationValidator)
// 1. Update Quotation/Invoice details
requestedInvoiceQuotation.merge({
// Stringify `additionalFees` since the query is not directly
// done on the InvoiceQuotation model
additionalFees,
date,
code,
customerId,
customerBillingAddress: customerBillingAddressId,
customerShippingAddress: customerShippingAddressId,
introduction: sanitiseHTML(introduction),
title,
simpleQuantities,
amountsAreTaxInclusive,
taxPercentage,
roundAmounts,
roundAmountType,
showDiscounts,
discountType,
setDiscountTypePerLine,
calculateTotals,
changeProductPrices,
numberOfDecimals,
useThousandSeparator,
thousandSeparatorType,
notes: sanitiseHTML(notes),
showAdditionalSubtotalDiscount,
additionalDiscountType,
additionalDiscountAmount,
showAdditionalFees,
showImages,
useCustomSerialNumbers,
useEditor,
})
await requestedInvoiceQuotation.save()
await requestedInvoiceQuotation.refresh()
// 2. Get and drop any previous items owed by the Invoice/Quotation
await requestedInvoiceQuotation.related('items').query().delete()
// 3. Then create new items for the Invoice/Quotation
const preparedItems: Array<Record<string, unknown>> = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
const itemCollector: Record<string, unknown> = {}
// 1. test if product id is a UUID
const isId = isUUID(item?.productId ?? '', 5)
itemCollector.productId = isId ? item.productId : null
itemCollector.productName = isId ? null : sanitiseHTML(item?.productName)
// 2. Get other fields
itemCollector.description = item.description
itemCollector.sortOrder = i + 1
itemCollector.qty = item.qty
itemCollector.groupQty = item.groupQty
itemCollector.unitPrice = item.unitPrice
itemCollector.unitDiscount = item.unitDiscount
itemCollector.discountType = item.discountType
itemCollector.customSerialNumber = item.customSerialNumber
// 3. Get `unitOfMeasurementId`
const uom = await UnitOfMeasurement.findBy('name', item.UOM)
itemCollector.unitOfMeasurementId = uom?.id
// 4. Get `collectionTypeId`
const colType = await UnitOfMeasurement.findBy('name', item.collectionTypeId)
itemCollector.collectionTypeId = colType?.id
preparedItems.push(itemCollector)
}
await requestedInvoiceQuotation.related('items').createMany(preparedItems)
await new InvoiceQuotationServices({
invoiceQuotationModel: requestedInvoiceQuotation,
}).clearCache()
return response.created({ data: requestedInvoiceQuotation?.id })
} else return response.abort({ message: 'Company not found' })
}
public async destroy({
requestedInvoiceQuotation,
response,
requestedCompany,
bouncer,
}: HttpContextContract) {
await bouncer
.with('InvoiceQuotationPolicy')
.authorize('delete', requestedInvoiceQuotation!, requestedCompany!)
const type = requestedInvoiceQuotation.type
await requestedInvoiceQuotation.delete()
return response.created({
message: `${type === 'invoice' ? 'Invoice' : 'Quotation'} was deleted!`,
data: requestedInvoiceQuotation.id,
})
}
public async download({
requestedInvoiceQuotation,
requestedCompany,
bouncer,
}: HttpContextContract) {
// Check authorisation
await bouncer
.with('InvoiceQuotationPolicy')
.authorize('view', requestedInvoiceQuotation!, requestedCompany!)
const requestUrl = `print-pages/invoices-quotations/${requestedInvoiceQuotation.id}/${requestedInvoiceQuotation.type}`
await new PuppeteerServices(requestUrl, {
paperFormat: 'a3',
fileName: `${requestedInvoiceQuotation.type}_${requestedInvoiceQuotation.id}`,
})
.printAsPDF()
.catch((error) => console.error(error))
}
public async print({ params, response }: HttpContextContract) {
// Get invoice/quotation id and type from params
const { invoice_quotation_id, type } = params
const invoiceQuotationDetails = await new InvoiceQuotationServices({
id: invoice_quotation_id,
type,
}).getInvoiceQuotationFullDetails()
return response.ok({ data: invoiceQuotationDetails })
}
} | the_stack |
import { Hub } from "@sentry/hub";
import {
defaultRequestInstrumentationOptions,
IdleTransaction,
registerRequestInstrumentation,
RequestInstrumentationOptions,
startIdleTransaction,
Transaction,
} from "@sentry/tracing";
import {
EventProcessor,
Integration,
Transaction as TransactionType,
TransactionContext,
} from "@sentry/types";
import { logger } from "@sentry/utils";
import { NativeAppStartResponse } from "../definitions";
import { RoutingInstrumentationInstance } from "../tracing/routingInstrumentation";
import { NATIVE } from "../wrapper";
import { NativeFramesInstrumentation } from "./nativeframes";
import { StallTrackingInstrumentation } from "./stalltracking";
import { RouteChangeContextData } from "./types";
import {
adjustTransactionDuration,
getTimeOriginMilliseconds,
isNearToNow,
} from "./utils";
export type BeforeNavigate = (
context: TransactionContext
) => TransactionContext;
export interface ReactNativeTracingOptions
extends RequestInstrumentationOptions {
/**
* The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of
* the last finished span as the endtime for the transaction.
* Time is in ms.
*
* Default: 1000
*/
idleTimeout: number;
/**
* The maximum duration of a transaction before it will be marked as "deadline_exceeded".
* If you never want to mark a transaction set it to 0.
* Time is in seconds.
*
* Default: 600
*/
maxTransactionDuration: number;
/**
* The routing instrumentation to be used with the tracing integration.
* There is no routing instrumentation if nothing is passed.
*/
routingInstrumentation?: RoutingInstrumentationInstance;
/**
* Does not sample transactions that are from routes that have been seen any more and don't have any spans.
* This removes a lot of the clutter as most back navigation transactions are now ignored.
*
* Default: true
*/
ignoreEmptyBackNavigationTransactions: boolean;
/**
* beforeNavigate is called before a navigation transaction is created and allows users to modify transaction
* context data, or drop the transaction entirely (by setting `sampled = false` in the context).
*
* @param context: The context data which will be passed to `startTransaction` by default
*
* @returns A (potentially) modified context object, with `sampled = false` if the transaction should be dropped.
*/
beforeNavigate: BeforeNavigate;
/**
* Track the app start time by adding measurements to the first route transaction. If there is no routing instrumentation
* an app start transaction will be started.
*
* Default: true
*/
enableAppStartTracking: boolean;
/**
* Track slow/frozen frames from the native layer and adds them as measurements to all transactions.
*/
enableNativeFramesTracking: boolean;
/**
* Track when and how long the JS event loop stalls for. Adds stalls as measurements to all transactions.
*/
enableStallTracking: boolean;
}
const defaultReactNativeTracingOptions: ReactNativeTracingOptions = {
...defaultRequestInstrumentationOptions,
idleTimeout: 1000,
maxTransactionDuration: 600,
ignoreEmptyBackNavigationTransactions: true,
beforeNavigate: (context) => context,
enableAppStartTracking: true,
enableNativeFramesTracking: true,
enableStallTracking: true,
};
/**
* Tracing integration for React Native.
*/
export class ReactNativeTracing implements Integration {
/**
* @inheritDoc
*/
public static id: string = "ReactNativeTracing";
/**
* @inheritDoc
*/
public name: string = ReactNativeTracing.id;
/** ReactNativeTracing options */
public options: ReactNativeTracingOptions;
public nativeFramesInstrumentation?: NativeFramesInstrumentation;
public stallTrackingInstrumentation?: StallTrackingInstrumentation;
public useAppStartWithProfiler: boolean = false;
private _getCurrentHub?: () => Hub;
private _awaitingAppStartData?: NativeAppStartResponse;
private _appStartFinishTimestamp?: number;
public constructor(options: Partial<ReactNativeTracingOptions> = {}) {
this.options = {
...defaultReactNativeTracingOptions,
...options,
};
}
/**
* Registers routing and request instrumentation.
*/
public setupOnce(
// @ts-ignore TODO
addGlobalEventProcessor: (callback: EventProcessor) => void,
getCurrentHub: () => Hub
): void {
// eslint-disable-next-line @typescript-eslint/unbound-method
const {
traceFetch,
traceXHR,
tracingOrigins,
// @ts-ignore TODO
shouldCreateSpanForRequest,
routingInstrumentation,
enableAppStartTracking,
enableNativeFramesTracking,
enableStallTracking,
} = this.options;
this._getCurrentHub = getCurrentHub;
if (enableAppStartTracking) {
void this._instrumentAppStart();
}
if (enableNativeFramesTracking) {
this.nativeFramesInstrumentation = new NativeFramesInstrumentation(
addGlobalEventProcessor,
() => {
const self = getCurrentHub().getIntegration(ReactNativeTracing);
if (self) {
return !!self.nativeFramesInstrumentation;
}
return false;
}
);
} else {
NATIVE.disableNativeFramesTracking();
}
if (enableStallTracking) {
this.stallTrackingInstrumentation = new StallTrackingInstrumentation();
}
if (routingInstrumentation) {
routingInstrumentation.registerRoutingInstrumentation(
this._onRouteWillChange.bind(this),
this.options.beforeNavigate,
this._onConfirmRoute.bind(this)
);
} else {
logger.log(
`[ReactNativeTracing] Not instrumenting route changes as routingInstrumentation has not been set.`
);
}
registerRequestInstrumentation({
traceFetch,
traceXHR,
tracingOrigins,
shouldCreateSpanForRequest,
});
}
/**
* To be called on a transaction start. Can have async methods
*/
public onTransactionStart(transaction: Transaction): void {
if (isNearToNow(transaction.startTimestamp)) {
// Only if this method is called at or within margin of error to the start timestamp.
this.nativeFramesInstrumentation?.onTransactionStart(transaction);
this.stallTrackingInstrumentation?.onTransactionStart(transaction);
}
}
/**
* To be called on a transaction finish. Cannot have async methods.
*/
public onTransactionFinish(
transaction: Transaction,
endTimestamp?: number
): void {
this.nativeFramesInstrumentation?.onTransactionFinish(transaction);
this.stallTrackingInstrumentation?.onTransactionFinish(
transaction,
endTimestamp
);
}
/**
* Called by the ReactNativeProfiler component on first component mount.
*/
public onAppStartFinish(endTimestamp: number): void {
this._appStartFinishTimestamp = endTimestamp;
}
/**
* Instruments the app start measurements on the first route transaction.
* Starts a route transaction if there isn't routing instrumentation.
*/
private async _instrumentAppStart(): Promise<void> {
if (!this.options.enableAppStartTracking || !NATIVE.enableNative) {
return;
}
const appStart = await NATIVE.fetchNativeAppStart();
if (!appStart || appStart.didFetchAppStart) {
return;
}
if (!this.useAppStartWithProfiler) {
this._appStartFinishTimestamp = getTimeOriginMilliseconds() / 1000;
}
if (this.options.routingInstrumentation) {
this._awaitingAppStartData = appStart;
} else {
const appStartTimeSeconds = appStart.appStartTime / 1000;
const idleTransaction = this._createRouteTransaction({
name: "App Start",
op: "ui.load",
startTimestamp: appStartTimeSeconds,
});
if (idleTransaction) {
this._addAppStartData(idleTransaction, appStart);
}
}
}
/**
* Adds app start measurements and starts a child span on a transaction.
*/
private _addAppStartData(
transaction: IdleTransaction,
appStart: NativeAppStartResponse
): void {
if (!this._appStartFinishTimestamp) {
logger.warn("App start was never finished.");
return;
}
const appStartTimeSeconds = appStart.appStartTime / 1000;
transaction.startChild({
description: appStart.isColdStart ? "Cold App Start" : "Warm App Start",
op: appStart.isColdStart ? "app.start.cold" : "app.start.warm",
startTimestamp: appStartTimeSeconds,
endTimestamp: this._appStartFinishTimestamp,
});
const appStartDurationMilliseconds =
this._appStartFinishTimestamp * 1000 - appStart.appStartTime;
transaction.setMeasurements(
appStart.isColdStart
? {
app_start_cold: {
value: appStartDurationMilliseconds,
},
}
: {
app_start_warm: {
value: appStartDurationMilliseconds,
},
}
);
}
/** To be called when the route changes, but BEFORE the components of the new route mount. */
private _onRouteWillChange(
context: TransactionContext
): TransactionType | undefined {
return this._createRouteTransaction(context);
}
/**
* Creates a breadcrumb and sets the current route as a tag.
*/
private _onConfirmRoute(context: TransactionContext): void {
this._getCurrentHub?.().configureScope((scope) => {
if (context.data) {
const contextData = context.data as RouteChangeContextData;
scope.addBreadcrumb({
category: "navigation",
type: "navigation",
// We assume that context.name is the name of the route.
message: `Navigation to ${context.name}`,
data: {
from: contextData.previousRoute?.name,
to: contextData.route.name,
},
});
}
scope.setTag("routing.route.name", context.name);
});
}
/** Create routing idle transaction. */
private _createRouteTransaction(
context: TransactionContext
): IdleTransaction | undefined {
if (!this._getCurrentHub) {
logger.warn(
`[ReactNativeTracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`
);
return undefined;
}
// eslint-disable-next-line @typescript-eslint/unbound-method
const { idleTimeout, maxTransactionDuration } = this.options;
const expandedContext = {
...context,
trimEnd: true,
};
const hub = this._getCurrentHub();
const idleTransaction = startIdleTransaction(
hub as Hub,
expandedContext,
idleTimeout,
true
);
this.onTransactionStart(idleTransaction);
logger.log(
`[ReactNativeTracing] Starting ${context.op} transaction "${context.name}" on scope`
);
idleTransaction.registerBeforeFinishCallback(
(transaction, endTimestamp) => {
this.onTransactionFinish(transaction, endTimestamp);
}
);
idleTransaction.registerBeforeFinishCallback((transaction) => {
if (this.options.enableAppStartTracking && this._awaitingAppStartData) {
transaction.startTimestamp =
this._awaitingAppStartData.appStartTime / 1000;
transaction.op = "ui.load";
this._addAppStartData(transaction, this._awaitingAppStartData);
this._awaitingAppStartData = undefined;
}
});
idleTransaction.registerBeforeFinishCallback(
(transaction, endTimestamp) => {
adjustTransactionDuration(
maxTransactionDuration,
transaction,
endTimestamp
);
}
);
if (this.options.ignoreEmptyBackNavigationTransactions) {
idleTransaction.registerBeforeFinishCallback((transaction) => {
if (
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
transaction.data?.route?.hasBeenSeen &&
(!transaction.spanRecorder ||
transaction.spanRecorder.spans.filter(
(span) => span.spanId !== transaction.spanId
).length === 0)
) {
logger.log(
`[ReactNativeTracing] Not sampling transaction as route has been seen before. Pass ignoreEmptyBackNavigationTransactions = false to disable this feature.`
);
// Route has been seen before and has no child spans.
transaction.sampled = false;
}
});
}
return idleTransaction;
}
} | the_stack |
import {TestingModule} from '@nestjs/testing';
import 'reflect-metadata';
import {INote, NoteActions, createNote} from '@wix/quix-shared/entities/note';
import {NoteActionT} from '@wix/quix-shared/entities/note/actions';
import {NotebookActions} from '@wix/quix-shared/entities/notebook';
import {FileActions, FileType} from '@wix/quix-shared/entities/file';
import {QuixEventBus} from './quix-event-bus';
import {QuixEventBusDriver} from './quix-event-bus.driver';
import {range, reject, find} from 'lodash';
import {EntityType} from '../../common/entity-type.enum';
import {MockDataBuilder} from 'test/builder';
import {IAction} from './infrastructure/types';
import {UserActions} from '@wix/quix-shared';
import {emit} from 'process';
jest.setTimeout(300000);
const defaultUser = 'someUser@wix.com';
describe('event sourcing', () => {
let driver: QuixEventBusDriver;
let eventBus: QuixEventBus;
let module: TestingModule;
let mockBuilder: MockDataBuilder;
// let notebookRepo: Repository<DbNotebook>;
// let noteRepo: Repository<DbNote>;
beforeAll(async () => {
driver = await QuixEventBusDriver.create(defaultUser);
({eventBus, module, mockBuilder} = driver);
});
beforeEach(() => driver.clearDb());
afterAll(() => driver.clearDb());
afterAll(() => module.close());
describe('notebooks::', () => {
let id: string;
let createAction: IAction<NotebookActions>;
beforeEach(() => {
[id, createAction] = mockBuilder.createNotebookAction();
});
it('create notebook', async () => {
await driver.emitAsUser(eventBus, [createAction]);
const notebook = await driver.getNotebook(id).and.expectToBeDefined();
expect(notebook.id).toBe(createAction.id);
});
it('set owner correctly', async () => {
await driver.emitAsUser(eventBus, [createAction]);
const notebook = await driver.getNotebook(id).and.expectToBeDefined();
expect(notebook.owner).toBe(defaultUser);
});
it('update name', async () => {
const note = createNote(id);
const addNoteAction = NoteActions.addNote(note.id, note);
await driver.emitAsUser(eventBus, [
createAction,
addNoteAction,
NotebookActions.updateName(id, 'newName'),
]);
const notebook = await driver.getNotebook(id).and.expectToBeDefined();
expect(notebook.name).toBe('newName');
});
it('toggle isLiked', async () => {
await driver.emitAsUser(eventBus, [
createAction,
NotebookActions.toggleIsLiked(id, true),
]);
await driver
.getFavorite(defaultUser, id, EntityType.Notebook)
.and.expectToBeDefined();
await driver.emitAsUser(eventBus, [
NotebookActions.toggleIsLiked(id, false),
]);
await driver
.getFavorite(defaultUser, id, EntityType.Notebook)
.and.expectToBeUndefined();
});
it('delete', async () => {
await eventBus.emit(createAction);
const notebook = await driver.getNotebook(id).and.expectToBeDefined();
expect(notebook.id).toBe(createAction.id);
await driver.emitAsUser(eventBus, [NotebookActions.deleteNotebook(id)]);
await driver.getNotebook(id).and.expectToBeUndefined();
});
it('delete favorite after deleting the notebook', async () => {
await eventBus.emit([createAction]);
await driver.emitAsUser(eventBus, [
NotebookActions.toggleIsLiked(id, true),
]);
await driver
.getFavorite(defaultUser, id, EntityType.Notebook)
.and.expectToBeDefined();
await driver.emitAsUser(eventBus, [NotebookActions.deleteNotebook(id)]);
await driver
.getFavorite(defaultUser, id, EntityType.Notebook)
.and.expectToBeUndefined();
});
it('delete only the favorite of the deleted notebook', async () => {
const [id1, createAction1] = mockBuilder.createNotebookAction();
const [id2, createAction2] = mockBuilder.createNotebookAction();
await eventBus.emit([createAction1, createAction2]);
await driver.emitAsUser(eventBus, [
NotebookActions.toggleIsLiked(id1, true),
NotebookActions.toggleIsLiked(id2, true),
]);
await driver.emitAsUser(eventBus, [NotebookActions.deleteNotebook(id1)]);
await driver
.getFavorite(defaultUser, id1, EntityType.Notebook)
.and.expectToBeUndefined();
await driver
.getFavorite(defaultUser, id2, EntityType.Notebook)
.and.expectToBeDefined();
});
});
describe('notes::', () => {
let notebookId: string;
let createNotebookAction: NotebookActions;
let addNoteAction: NoteActionT<'note.create'>;
let note: INote;
beforeEach(() => {
[notebookId, createNotebookAction] = mockBuilder.createNotebookAction();
note = createNote(notebookId);
addNoteAction = NoteActions.addNote(note.id, note);
});
it('create note', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction]);
await driver.emitAsUser(eventBus, [addNoteAction]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes).toHaveLength(1);
});
it('create note, with content', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction]);
addNoteAction = NoteActions.addNote(
note.id,
createNote(notebookId, {content: 'bla bla bla'}),
);
await driver.emitAsUser(eventBus, [addNoteAction]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes).toHaveLength(1);
expect(notebook.notes![0].textContent).toBe('bla bla bla');
});
it('create note with bulk actions', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction, addNoteAction]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes).toHaveLength(1);
const {id, name, notebookId: parent, type} = note;
expect(notebook.notes![0]).toMatchObject(
expect.objectContaining({
id,
name,
notebookId: parent,
owner: defaultUser,
type,
}),
);
});
it('update name', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction, addNoteAction]);
await driver.emitAsUser(eventBus, [
NoteActions.updateName(note.id, 'changedName'),
]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes![0].name).toBe('changedName');
});
it('delete note', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction, addNoteAction]);
await driver.emitAsUser(eventBus, [NoteActions.deleteNote(note.id)]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes).toHaveLength(0);
});
it('update content', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction, addNoteAction]);
await driver.emitAsUser(eventBus, [
NoteActions.updateContent(note.id, 'select foo from bar'),
]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes![0].textContent).toBe('select foo from bar');
});
it('move note between notebook', async () => {
await driver.emitAsUser(eventBus, [createNotebookAction, addNoteAction]);
const [
secondNotebookId,
createNotebookAction2,
] = mockBuilder.createNotebookAction();
await driver.emitAsUser(eventBus, [createNotebookAction2]);
await driver.emitAsUser(eventBus, [
NoteActions.move(note.id, secondNotebookId),
]);
const notebook = await driver.getNotebookWithNotes(notebookId);
expect(notebook.notes).toHaveLength(0);
const secondNotebook = await driver.getNotebookWithNotes(
secondNotebookId,
);
expect(secondNotebook.notes).toHaveLength(1);
});
describe('note rank/order', () => {
let notes: INote[];
let createNoteActions: NoteActionT<'note.create'>[];
const howManyNotes = 6;
beforeEach(async () => {
const [
notebookId2,
createNotebookAction2,
] = mockBuilder.createNotebookAction();
const notes2 = range(2).map(() => createNote(notebookId2));
notes = range(howManyNotes).map(() => createNote(notebookId));
createNoteActions = notes.map(n => NoteActions.addNote(n.id, n));
const createNoteActions2 = notes2.map(n =>
NoteActions.addNote(n.id, n),
);
/* creating notes in another notebook, just to make sure reorder is local inside a notebook */
await driver.emitAsUser(eventBus, [createNotebookAction2]);
await driver.emitAsUser(eventBus, createNoteActions2);
await driver.emitAsUser(eventBus, [createNotebookAction]);
await driver.emitAsUser(eventBus, createNoteActions);
});
it('should create new notes with correct order', async () => {
const notebook = await driver.getNotebookWithNotes(notebookId);
const doesRankMatchInsertOrder = notes.every(
(note, index) =>
notebook.notes!.find(n => n.id === note.id)!.rank === index,
);
expect(doesRankMatchInsertOrder).toBeTruthy();
});
const deleteCases = [
[0, 'start'],
[howManyNotes - 1, 'end'],
[3, 'middle'],
] as const;
deleteCases.forEach(([noteIndexToDelete, testName]) => {
it(`on delete should set order of remaining notes correctly, when removing from ${testName}`, async () => {
const noteIdToDelete = notes[noteIndexToDelete].id;
const deleteAction = NoteActions.deleteNote(noteIdToDelete);
await driver.emitAsUser(eventBus, [deleteAction]);
const filteredNotes = reject(notes, {id: noteIdToDelete});
const notebook = await driver.getNotebookWithNotes(notebookId);
const doesRankMatchInsertOrder = filteredNotes.every(
(note, index) =>
notebook.notes!.find(n => n.id === note.id)!.rank === index,
);
expect(doesRankMatchInsertOrder).toBeTruthy();
});
});
const reorderCases = [
[4, 2, '"from" greater than "to"'],
[1, 5, '"to" greater than "from"'],
] as const;
reorderCases.forEach(([from, to, testName]) => {
it(`reorder notes correctly, when ${testName}`, async () => {
const noteIdMove = notes[from].id;
const reorderAction = NoteActions.reorderNote(noteIdMove, to);
await driver.emitAsUser(eventBus, [reorderAction]);
const reorderedNotes = reorderPos(notes, from, to);
const notebook = await driver.getNotebookWithNotes(notebookId);
const doesRankMatchInsertOrder = reorderedNotes.every(
(note, index) =>
notebook.notes!.find(n => n.id === note.id)!.rank === index,
);
expect(doesRankMatchInsertOrder).toBeTruthy();
});
});
});
});
describe('folder tree::', () => {
let folderId: string;
let createFolderAction: any;
let notebookId: string;
let createNotebookAction: any;
beforeEach(() => {
[folderId, createFolderAction] = mockBuilder.createFolderAction(
'rootFolder',
[],
);
[notebookId, createNotebookAction] = mockBuilder.createNotebookAction([
{id: folderId},
]);
});
it('a single folder', async () => {
await driver.emitAsUser(eventBus, [createFolderAction]);
const list = await driver.getUserFileTree(defaultUser);
expect(list[0].folder!.name).toBe('rootFolder');
});
it('rename folder', async () => {
await driver.emitAsUser(eventBus, [createFolderAction]);
await driver.emitAsUser(eventBus, [
FileActions.updateName(folderId, 'a changedName'),
]);
const list = await driver.getUserFileTree(defaultUser);
expect(list[0].folder!.name).toBe('a changedName');
});
it('a notebook inside a single folder', async () => {
await driver.emitAsUser(eventBus, [
createFolderAction,
createNotebookAction,
]);
const list = await driver.getUserFileTree(defaultUser);
const notebookTreeItem = list.find(
item => item.id === notebookId && item.parentId === folderId,
);
expect(notebookTreeItem).toBeDefined();
});
it('have multiple notebooks inside a single folder', async () => {
const [
notebookId2,
createNotebookAction2,
] = mockBuilder.createNotebookAction([{id: folderId}]);
await driver.emitAsUser(eventBus, [
createFolderAction,
createNotebookAction,
createNotebookAction2,
]);
const list = await driver.getUserFileTree(defaultUser);
const notebookItems = list.filter(
item => item.type === FileType.notebook,
);
expect(notebookItems).toHaveLength(2);
});
it('notebook move', async () => {
const [
subFolder1,
createSubFolder1,
] = mockBuilder.createFolderAction('subFolder1', [{id: folderId}]);
await driver.emitAsUser(eventBus, [
createFolderAction,
createSubFolder1,
createNotebookAction,
]);
await driver.emitAsUser(eventBus, [
NotebookActions.moveNotebook(notebookId, [{id: subFolder1, name: ''}]),
]);
const list = await driver.getUserFileTree(defaultUser);
const notebook = list.find(item => item.id === notebookId);
expect(notebook!.mpath).toBe(`${folderId}.${subFolder1}.${notebookId}`);
});
it('folder tree move', async () => {
const [
subFolder1,
createSubFolder1,
] = mockBuilder.createFolderAction('subFolder1', [{id: folderId}]);
const [
subFolder2,
createSubFolder2,
] = mockBuilder.createFolderAction('subFolder2', [{id: subFolder1}]);
const [
subFolder3,
createSubFolder3,
] = mockBuilder.createFolderAction('subFolder3', [{id: folderId}]);
const [
notebookId,
createNotebookAction,
] = mockBuilder.createNotebookAction([{id: subFolder2}]);
await driver.emitAsUser(eventBus, [
createFolderAction,
createSubFolder1,
createSubFolder2,
createSubFolder3,
createNotebookAction,
]);
/**
* structure:
* rootFolder ->
* folder1 ->
* folder2->
* notebook
* folder3
*/
await driver.emitAsUser(eventBus, [
FileActions.moveFile(subFolder1, [{id: subFolder3, name: ''}]),
]);
/**
* structure:
* rootFolder ->
* folder3 ->
* folder1 ->
* folder2->
* notebook
*/
const list = await driver.getUserFileTree(defaultUser);
expect(find(list, {id: subFolder1})).toMatchObject({
parentId: subFolder3,
});
expect(find(list, {id: notebookId})).toMatchObject({
mpath: [folderId, subFolder3, subFolder1, subFolder2, notebookId].join(
'.',
),
});
expect(find(list, {id: subFolder2})).toMatchObject({
mpath: [folderId, subFolder3, subFolder1, subFolder2].join('.'),
});
});
it('delete an empty folder', async () => {
const [
subFolder1,
createSubFolder1,
] = mockBuilder.createFolderAction('subFolder1', [{id: folderId}]);
await driver.emitAsUser(eventBus, [createFolderAction, createSubFolder1]);
const beforeList = await driver.getUserFileTree(defaultUser);
expect(beforeList).toHaveLength(2);
await driver.emitAsUser(eventBus, [FileActions.deleteFile(subFolder1)]);
const afterList = await driver.getUserFileTree(defaultUser);
expect(afterList).toMatchObject([
expect.objectContaining({id: folderId}),
]);
});
it('recursively delete a folder', async () => {
const [
subFolder1,
createSubFolder1,
] = mockBuilder.createFolderAction('subFolder1', [{id: folderId}]);
const [
subFolder2,
createSubFolder2,
] = mockBuilder.createFolderAction('subFolder2', [{id: subFolder1}]);
const [
subFolder3,
createSubFolder3,
] = mockBuilder.createFolderAction('subFolder3', [{id: subFolder2}]);
const [
notebookId,
createNotebookAction,
] = mockBuilder.createNotebookAction([{id: subFolder2}]);
await driver.emitAsUser(eventBus, [
createFolderAction,
createSubFolder1,
createSubFolder2,
createSubFolder3,
createNotebookAction,
]);
await driver.emitAsUser(eventBus, [FileActions.deleteFile(subFolder1)]);
const afterList = await driver.getUserFileTree(defaultUser);
expect(afterList).toMatchObject([
expect.objectContaining({id: folderId}),
]);
/* Checking that deletion deletes entities from other tables */
await driver.getNotebook(notebookId).and.expectToBeUndefined();
expect(await driver.folderRepo.find()).toHaveLength(1);
});
it('delete notebook favorite after deleting the parent folder', async () => {
const [
subFolderId,
createSubFolder,
] = mockBuilder.createFolderAction('subFolder', [{id: folderId}]);
const [
notebookId,
createNotebookAction,
] = mockBuilder.createNotebookAction([{id: subFolderId}]);
await driver.emitAsUser(eventBus, [
createFolderAction,
createSubFolder,
createNotebookAction,
]);
await driver.emitAsUser(eventBus, [
NotebookActions.toggleIsLiked(notebookId, true),
]);
await driver.emitAsUser(eventBus, [FileActions.deleteFile(subFolderId)]);
await driver
.getFavorite(defaultUser, notebookId, EntityType.Notebook)
.and.expectToBeUndefined();
});
});
describe('user list::', () => {
it('should add user with dateCreated in the past', async () => {
const createAction = UserActions.createNewUser('foo', {
avatar: '',
dateCreated: 1000,
dateUpdated: 1000,
email: 'foo',
id: 'foo',
name: '',
rootFolder: '',
});
await driver.emitAsUser(eventBus, [createAction], 'foo');
const users = await driver.getUsers();
expect(users[0]).toMatchObject({dateCreated: 1000, dateUpdated: 1000});
});
});
describe('error handling::', () => {
it('should throw an error on invalid action', async () => {
const error = await driver
.emitAsUser(eventBus, [{type: 'foo'}])
.catch(e => e);
await new Promise(resolve => setTimeout(resolve, 1000));
expect(error instanceof Error).toBe(true);
});
});
});
function reorderPos<T>(items: T[], from: number, to: number) {
const clone = items.slice();
const [item] = clone.splice(from, 1);
clone.splice(to, 0, item);
return clone;
} | the_stack |
import { expect, should, use } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import { spawnSync, SpawnSyncOptionsWithBufferEncoding } from 'child_process';
import { join } from 'path';
import { inspect } from 'util';
import { rmdirSync } from 'fs';
import { TestContext } from './context';
import { downloadElectron } from './download';
import { TestServer, TestServerEvent } from './server';
import { getCrashesDirectory, getLastFrame } from './utils';
const SENTRY_KEY = '37f8a2ee37c0409d8970bc7559c7c7e4';
should();
use(chaiAsPromised);
const versions = process.env.ELECTRON_VERSION
? [process.env.ELECTRON_VERSION]
: [
'2.0.18',
'3.1.13',
'4.2.12',
'5.0.13',
'6.1.12',
'7.3.3',
'8.5.5',
'9.4.4',
'10.4.7',
'11.5.0',
'12.1.2',
'13.4.0',
'14.0.1',
'15.0.0',
];
const tests = versions.map((v) => [v, 'x64']);
describe('Bundle Tests', () => {
it('Webpack contextIsolation app', async function () {
// We don't need to compile the isolated app if we're not going to test it
if (process.env.ELECTRON_VERSION && Math.floor(parseFloat(process.env.ELECTRON_VERSION)) < 6) {
this.skip();
}
this.timeout(120000);
const options: SpawnSyncOptionsWithBufferEncoding = {
shell: true,
cwd: join(__dirname, 'test-apps', 'isolated-app'),
};
if (process.env.DEBUG) {
options.stdio = 'inherit';
}
const result = spawnSync('yarn && yarn build', options);
expect(result.status).to.equal(0);
});
});
describe('E2E Tests', () => {
let testServer: TestServer;
function getEvent(): TestServerEvent {
const event = testServer.events.find((e) => e.eventData);
expect(event, 'Could not find event').not.to.be.undefined;
return event as TestServerEvent;
}
function getSession(status: string): TestServerEvent {
const session = testServer.events.find((e) => e.sessionData && e.sessionData.status == status);
expect(session, `Could not find '${status}' session`).not.to.be.undefined;
return session as TestServerEvent;
}
before(() => {
testServer = new TestServer();
testServer.start();
});
after(async () => {
await testServer.stop();
});
tests.forEach(([version, arch]) => {
const majorVersion = Math.floor(parseFloat(version));
if (majorVersion < 3 && process.platform === 'linux') {
// We skip tests on linux for electron version < 3
return;
}
describe(`Electron ${version} ${arch}`, () => {
let context: TestContext;
let crashDir: string;
beforeEach(async () => {
testServer.clearEvents();
const electronPath = await downloadElectron(version, arch);
crashDir = getCrashesDirectory(electronPath);
context = new TestContext(electronPath);
});
afterEach(async function () {
if (this.currentTest?.state === 'failed') {
console.log('App stdout: ');
console.log(context.processStdOut);
if (testServer.events.length) {
console.log('Events received: ', inspect(testServer.events, false, null, true));
} else {
console.log('No Events received');
}
}
if (context.isStarted()) {
await context.stop();
}
try {
rmdirSync(crashDir, { recursive: true });
} catch (_) {}
});
it('JavaScript exception in renderer process', async () => {
await context.start('sentry-basic', 'javascript-renderer');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.dump_file).to.be.false;
expect(event.eventData?.platform).to.equal('javascript');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-renderer.js');
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
it('JavaScript unhandledrejection in renderer process', async () => {
await context.start('sentry-basic', 'javascript-unhandledrejection');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.dump_file).to.be.false;
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-unhandledrejection.js');
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
it('JavaScript exception in main process', async () => {
await context.start('sentry-basic', 'javascript-main');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('browser');
expect(event.dump_file).to.be.false;
expect(event.eventData?.platform).to.equal('node');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-main.js');
});
it('JavaScript exception in main process with spaces and parentheses in path', async () => {
await context.start('sentry-basic', 'javascript main with (parens)');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('browser');
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript main with (parens).js');
expect(event.dump_file).to.be.false;
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
// tslint:disable-next-line
it('Native crash in renderer process', async function () {
await context.start('sentry-basic', 'native-renderer');
// It can take rather a long time to get the event on Mac
await context.waitForEvents(testServer, 1, 20000);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.dump_file).to.be.true;
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
// tslint:disable-next-line
it('Native crash in main process with Electron uploader', async function () {
if (majorVersion < 9) {
this.skip();
}
await context.start('sentry-electron-uploader-main', 'native-main');
// It can take rather a long time to get the event on Mac
await context.waitForEvents(testServer, 1, 20000);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.method).to.equal('minidump');
if (majorVersion >= 15 || process.platform !== 'linux') {
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('browser');
expect(event.eventData?.user?.id).to.equal('ABCDEF1234567890');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.namespaced?.initialScope?.user?.username).to.equal('some_user');
expect(event.namespaced?.initialScope?.release).to.equal('some-release');
}
});
// tslint:disable-next-line
it('Native crash in renderer process with Electron uploader', async function () {
if (majorVersion < 9) {
this.skip();
}
await context.start('sentry-electron-uploader-renderer', 'native-renderer');
// It can take rather a long time to get the event on Mac
await context.waitForEvents(testServer, 1, 20000);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.method).to.equal('minidump');
if (majorVersion >= 15 || process.platform !== 'linux') {
expect(event.namespaced?.initialScope?.user?.username).to.equal('some_user');
expect(event.namespaced?.initialScope?.release).to.equal('some-release');
}
});
it('GPU crash with Electron uploader', async function () {
if (majorVersion < 13 || (process.platform === 'linux' && majorVersion < 15)) {
this.skip();
}
await context.start('sentry-electron-uploader-main', 'native-gpu');
await context.waitForEvents(testServer, 1, 20000);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.method).to.equal('minidump');
expect(event.namespaced?.initialScope?.user?.username).to.equal('some_user');
expect(event.namespaced?.initialScope?.release).to.equal('some-release');
});
it('JavaScript exception in main process with user data', async () => {
await context.start('sentry-scope-user-data', 'javascript-main');
await context.waitForEvents(testServer, 1);
const event = testServer.events[0];
expect(event.eventData?.user?.id).to.equal('johndoe');
});
// tslint:disable-next-line
it('Native crash in main process', async function () {
await context.start('sentry-basic', 'native-main');
// wait for the main process to die
await context.waitForTrue(
async () => (context.mainProcess ? !(await context.mainProcess.isRunning()) : false),
'Timeout: Waiting for app to die',
);
// We have to restart the app to send native crashes from the main process
await context.stop(false);
await context.start('sentry-basic');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('browser');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.true;
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
it('Captures breadcrumbs in renderer process', async () => {
await context.start('sentry-basic', 'breadcrumbs-in-renderer');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.false;
const breadcrumbs = event.eventData?.breadcrumbs?.filter((crumb) => crumb.message === 'Something insightful!');
expect(breadcrumbs?.length, 'filtered breadcrumbs').to.equal(1);
});
it('Captures Scope from renderer', async () => {
await context.start('sentry-basic', 'scope-data-renderer');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.extra?.a).to.equal(2);
expect(event.eventData?.user?.id).to.equal('1');
expect(event.eventData?.tags?.a).to.equal('b');
expect(event.eventData?.contexts?.server).to.include({ id: '2' });
expect(event.eventData?.fingerprint).to.include('abcd');
});
it('Captures Scope from main', async () => {
await context.start('sentry-basic', 'scope-data-main');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('browser');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.extra?.a).to.equal(2);
expect(event.eventData?.user?.id).to.equal('2');
expect(event.eventData?.tags?.a).to.equal('b');
expect(event.eventData?.contexts?.server).to.include({ id: '2' });
expect(event.eventData?.fingerprint).to.include('abcd');
});
it('Main scope not clobbered by scope from renderer', async () => {
await context.start('sentry-basic', 'scope-data-merged');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.extra?.a).to.equal(2);
expect(event.eventData?.user?.id).to.equal('5');
expect(event.eventData?.user?.email).to.equal('none@test.org');
expect(event.eventData?.tags?.a).to.equal('b');
expect(event.eventData?.contexts?.server).to.include({ id: '2' });
expect(event.eventData?.fingerprint).to.include('abcd');
});
it('Custom release string for JavaScript error', async () => {
await context.start('sentry-custom-release', 'javascript-renderer');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.release).to.equal('some-custom-release');
expect(event.dump_file).to.be.false;
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-renderer.js');
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
it('Custom release string for minidump', async function () {
await context.start('sentry-custom-release', 'native-renderer');
// It can take rather a long time to get the event on Mac
await context.waitForEvents(testServer, 1, 20000);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.eventData?.release).to.equal('some-custom-release');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.dump_file).to.be.true;
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
});
it('Custom named renderer process', async () => {
await context.start('sentry-custom-renderer-name', 'javascript-renderer');
await context.waitForEvents(testServer, 1);
const event = testServer.events[0];
expect(testServer.events.length).to.equal(1);
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('SomeWindow');
});
it('JavaScript exception in contextIsolation renderer process', async function () {
// contextIsolation only added >= 6
if (majorVersion < 6) {
this.skip();
}
const electronPath = await downloadElectron(version, arch);
context = new TestContext(electronPath, join(__dirname, 'test-apps', 'isolated-app'));
await context.start();
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.eventData?.contexts?.app?.app_name).to.equal('isolated-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.false;
expect(event.eventData?.user?.id).to.equal('abc-123');
});
it('JavaScript exception in renderer process sent with browser SDK', async () => {
await context.start('sentry-browser', 'javascript-renderer');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('store');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.false;
expect(event.eventData?.platform).to.equal('javascript');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-renderer.js');
expect(event.eventData?.breadcrumbs?.length).to.greaterThanOrEqual(1);
});
it('Tracks sessions with MainProcessSession integration', async () => {
await context.start('sentry-session', 'do-nothing');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const session = testServer.events[0];
expect(session.method).to.equal('envelope');
expect(session.sessionData?.sid).to.exist;
expect(session.sessionData?.started).to.exist;
expect(session.sessionData?.status).to.equal('exited');
expect(session.sessionData?.errors).to.equal(0);
});
it('Tracks sessions with MainProcessSession integration with JavaScript error', async () => {
await context.start('sentry-session', 'javascript-renderer');
await context.waitForEvents(testServer, 3);
expect(testServer.events.length).to.equal(3);
const session = getSession('ok');
expect(session.method).to.equal('envelope');
expect(session.sessionData?.sid).to.exist;
expect(session.sessionData?.started).to.exist;
expect(session.sessionData?.errors).to.equal(1);
const event = getEvent();
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.false;
expect(event.eventData?.platform).to.equal('javascript');
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(getLastFrame(event.eventData)?.filename).to.equal('app:///fixtures/javascript-renderer.js');
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
const session2 = getSession('exited');
expect(session2.method).to.equal('envelope');
expect(session2.sessionData?.sid).to.equal(session.sessionData?.sid);
expect(session2.sessionData?.started).to.exist;
expect(session2.sessionData?.errors).to.equal(1);
});
it('Tracks sessions with MainProcessSession integration with native crash', async () => {
await context.start('sentry-session', 'native-renderer');
await context.waitForEvents(testServer, 2);
expect(testServer.events.length).to.equal(2);
const event = getEvent();
expect(event.method).to.equal('envelope');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.equal('WebContents[1]');
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.dump_file).to.be.true;
expect(event.sentry_key).to.equal(SENTRY_KEY);
expect(event.eventData?.breadcrumbs?.length).to.greaterThan(4);
const session = getSession('crashed');
expect(session.method).to.equal('envelope');
expect(session.sessionData?.started).to.exist;
expect(session.sessionData?.errors).to.equal(1);
});
it('Allows BrowserTracing transactions from renderer', async () => {
await context.start('sentry-browser-tracing', 'do-nothing');
await context.waitForEvents(testServer, 1);
expect(testServer.events.length).to.equal(1);
const event = testServer.events[0];
expect(event.method).to.equal('envelope');
expect(event.eventData?.type).to.equal('transaction');
expect(event.eventData?.release).to.equal('some-release');
expect(event.eventData?.contexts?.app?.app_name).to.equal('test-app');
expect(event.eventData?.contexts?.electron?.crashed_process).to.be.undefined;
expect(event.eventData?.sdk?.name).to.equal('sentry.javascript.electron');
expect(event.eventData?.contexts?.trace?.trace_id).to.not.be.undefined;
expect(event.eventData?.contexts?.trace?.op).to.equal('pageload');
// We don't get spans in Electron v2 (Chrome 61) probably due to missing instrumentation?
if (majorVersion >= 3) {
expect(event.eventData?.spans?.length).to.be.greaterThanOrEqual(7);
}
expect(event.eventData?.transaction).to.equal('app:///index.html');
});
});
});
}); | the_stack |
import { deepAssign } from "../../_util/deep_assign.ts";
// ---------------------------
// Interfaces and base classes
// ---------------------------
interface Success<T> {
ok: true;
body: T;
}
interface Failure {
ok: false;
}
type ParseResult<T> = Success<T> | Failure;
type ParserComponent<T = unknown> = (scanner: Scanner) => ParseResult<T>;
type BlockParseResultBody = {
type: "Block";
value: Record<string, unknown>;
} | {
type: "Table";
key: string[];
value: Record<string, unknown>;
} | {
type: "TableArray";
key: string[];
value: Record<string, unknown>;
};
export class TOMLParseError extends Error {}
export class Scanner {
#whitespace = /[ \t]/;
#position = 0;
constructor(private source: string) {}
/**
* Get current character
* @param index - relative index from current position
*/
char(index = 0) {
return this.source[this.#position + index] ?? "";
}
/**
* Get sliced string
* @param start - start position relative from current position
* @param end - end position relative from current position
*/
slice(start: number, end: number): string {
return this.source.slice(this.#position + start, this.#position + end);
}
/**
* Move position to next
*/
next(count?: number) {
if (typeof count === "number") {
for (let i = 0; i < count; i++) {
this.#position++;
}
} else {
this.#position++;
}
}
/**
* Move position until current char is not a whitespace, EOL, or comment.
* @param options.inline - skip only whitespaces
*/
nextUntilChar(
options: { inline?: boolean; comment?: boolean } = { comment: true },
) {
if (options.inline) {
while (this.#whitespace.test(this.char()) && !this.eof()) {
this.next();
}
} else {
while (!this.eof()) {
const char = this.char();
if (this.#whitespace.test(char) || this.isCurrentCharEOL()) {
this.next();
} else if (options.comment && this.char() === "#") {
// entering comment
while (!this.isCurrentCharEOL() && !this.eof()) {
this.next();
}
} else {
break;
}
}
}
// Invalid if current char is other kinds of whitespace
if (!this.isCurrentCharEOL() && /\s/.test(this.char())) {
const escaped = "\\u" + this.char().charCodeAt(0).toString(16);
throw new TOMLParseError(`Contains invalid whitespaces: \`${escaped}\``);
}
}
/**
* Position reached EOF or not
*/
eof() {
return this.position() >= this.source.length;
}
/**
* Get current position
*/
position() {
return this.#position;
}
isCurrentCharEOL() {
return this.char() === "\n" || this.slice(0, 2) === "\r\n";
}
}
// -----------------------
// Utilities
// -----------------------
function success<T>(body: T): Success<T> {
return {
ok: true,
body,
};
}
function failure(): Failure {
return {
ok: false,
};
}
export const Utils = {
unflat(
keys: string[],
values: unknown = {},
cObj?: unknown,
): Record<string, unknown> {
const out: Record<string, unknown> = {};
if (keys.length === 0) {
return cObj as Record<string, unknown>;
} else {
if (!cObj) {
cObj = values;
}
const key: string | undefined = keys[keys.length - 1];
if (typeof key === "string") {
out[key] = cObj;
}
return this.unflat(keys.slice(0, -1), values, out);
}
},
deepAssignWithTable(target: Record<string, unknown>, table: {
type: "Table" | "TableArray";
key: string[];
value: Record<string, unknown>;
}): void {
if (table.key.length === 0) {
throw new Error("Unexpected key length");
}
const value = target[table.key[0]];
if (typeof value === "undefined") {
Object.assign(
target,
this.unflat(
table.key,
table.type === "Table" ? table.value : [table.value],
),
);
} else if (Array.isArray(value)) {
if (table.type === "TableArray" && table.key.length === 1) {
value.push(table.value);
} else {
const last = value[value.length - 1];
Utils.deepAssignWithTable(last, {
type: table.type,
key: table.key.slice(1),
value: table.value,
});
}
} else if (typeof value === "object" && value !== null) {
Utils.deepAssignWithTable(value as Record<string, unknown>, {
type: table.type,
key: table.key.slice(1),
value: table.value,
});
} else {
throw new Error("Unexpected assign");
}
},
};
// ---------------------------------
// Parser combinators and generators
// ---------------------------------
function or<T>(parsers: ParserComponent<T>[]): ParserComponent<T> {
return function Or(scanner: Scanner): ParseResult<T> {
for (const parse of parsers) {
const result = parse(scanner);
if (result.ok) {
return result;
}
}
return failure();
};
}
function join<T>(
parser: ParserComponent<T>,
separator: string,
): ParserComponent<T[]> {
const Separator = character(separator);
return function Join(scanner: Scanner): ParseResult<T[]> {
const first = parser(scanner);
if (!first.ok) {
return failure();
}
const out: T[] = [first.body];
while (!scanner.eof()) {
if (!Separator(scanner).ok) {
break;
}
const result = parser(scanner);
if (result.ok) {
out.push(result.body);
} else {
throw new TOMLParseError(`Invalid token after "${separator}"`);
}
}
return success(out);
};
}
function kv<T>(
keyParser: ParserComponent<string[]>,
separator: string,
valueParser: ParserComponent<T>,
): ParserComponent<{ [key: string]: unknown }> {
const Separator = character(separator);
return function Kv(
scanner: Scanner,
): ParseResult<{ [key: string]: unknown }> {
const key = keyParser(scanner);
if (!key.ok) {
return failure();
}
const sep = Separator(scanner);
if (!sep.ok) {
throw new TOMLParseError(`key/value pair doesn't have "${separator}"`);
}
const value = valueParser(scanner);
if (!value.ok) {
throw new TOMLParseError(
`Value of key/value pair is invalid data format`,
);
}
return success(Utils.unflat(key.body, value.body));
};
}
function merge(
parser: ParserComponent<unknown[]>,
): ParserComponent<Record<string, unknown>> {
return function Merge(
scanner: Scanner,
): ParseResult<Record<string, unknown>> {
const result = parser(scanner);
if (!result.ok) {
return failure();
}
const body = {};
for (const record of result.body) {
if (typeof body === "object" && body !== null) {
deepAssign(body, record);
}
}
return success(body);
};
}
function repeat<T>(
parser: ParserComponent<T>,
): ParserComponent<T[]> {
return function Repeat(
scanner: Scanner,
) {
const body: T[] = [];
while (!scanner.eof()) {
const result = parser(scanner);
if (result.ok) {
body.push(result.body);
} else {
break;
}
scanner.nextUntilChar();
}
if (body.length === 0) {
return failure();
}
return success(body);
};
}
function surround<T>(
left: string,
parser: ParserComponent<T>,
right: string,
): ParserComponent<T> {
const Left = character(left);
const Right = character(right);
return function Surround(scanner: Scanner) {
if (!Left(scanner).ok) {
return failure();
}
const result = parser(scanner);
if (!result.ok) {
throw new TOMLParseError(`Invalid token after "${left}"`);
}
if (!Right(scanner).ok) {
throw new TOMLParseError(
`Not closed by "${right}" after started with "${left}"`,
);
}
return success(result.body);
};
}
function character(str: string) {
return function character(scanner: Scanner): ParseResult<void> {
scanner.nextUntilChar({ inline: true });
if (scanner.slice(0, str.length) === str) {
scanner.next(str.length);
} else {
return failure();
}
scanner.nextUntilChar({ inline: true });
return success(undefined);
};
}
// -----------------------
// Parser components
// -----------------------
const Patterns = {
BARE_KEY: /[A-Za-z0-9_-]/,
FLOAT: /[0-9_\.e+\-]/i,
END_OF_VALUE: /[ \t\r\n#,}]/,
};
export function BareKey(scanner: Scanner): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
if (!scanner.char() || !Patterns.BARE_KEY.test(scanner.char())) {
return failure();
}
const acc: string[] = [];
while (scanner.char() && Patterns.BARE_KEY.test(scanner.char())) {
acc.push(scanner.char());
scanner.next();
}
const key = acc.join("");
return success(key);
}
function EscapeSequence(scanner: Scanner): ParseResult<string> {
if (scanner.char() === "\\") {
scanner.next();
// See https://toml.io/en/v1.0.0-rc.3#string
switch (scanner.char()) {
case "b":
scanner.next();
return success("\b");
case "t":
scanner.next();
return success("\t");
case "n":
scanner.next();
return success("\n");
case "f":
scanner.next();
return success("\f");
case "r":
scanner.next();
return success("\r");
case "u":
case "U": {
// Unicode character
const codePointLen = scanner.char() === "u" ? 4 : 6;
const codePoint = parseInt(
"0x" + scanner.slice(1, 1 + codePointLen),
16,
);
const str = String.fromCodePoint(codePoint);
scanner.next(codePointLen + 1);
return success(str);
}
case '"':
scanner.next();
return success('"');
case "\\":
scanner.next();
return success("\\");
default:
scanner.next();
return success(scanner.char());
}
} else {
return failure();
}
}
export function BasicString(scanner: Scanner): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
if (scanner.char() === '"') {
scanner.next();
} else {
return failure();
}
const acc = [];
while (scanner.char() !== '"' && !scanner.eof()) {
if (scanner.char() === "\n") {
throw new TOMLParseError("Single-line string cannot contain EOL");
}
const escapedChar = EscapeSequence(scanner);
if (escapedChar.ok) {
acc.push(escapedChar.body);
} else {
acc.push(scanner.char());
scanner.next();
}
}
if (scanner.eof()) {
throw new TOMLParseError(
`Single-line string is not closed:\n${acc.join("")}`,
);
}
scanner.next(); // skip last '""
return success(acc.join(""));
}
export function LiteralString(scanner: Scanner): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
if (scanner.char() === "'") {
scanner.next();
} else {
return failure();
}
const acc: string[] = [];
while (scanner.char() !== "'" && !scanner.eof()) {
if (scanner.char() === "\n") {
throw new TOMLParseError("Single-line string cannot contain EOL");
}
acc.push(scanner.char());
scanner.next();
}
if (scanner.eof()) {
throw new TOMLParseError(
`Single-line string is not closed:\n${acc.join("")}`,
);
}
scanner.next(); // skip last "'"
return success(acc.join(""));
}
export function MultilineBasicString(
scanner: Scanner,
): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
if (scanner.slice(0, 3) === '"""') {
scanner.next(3);
} else {
return failure();
}
if (scanner.char() === "\n") {
// The first newline is trimmed
scanner.next();
}
const acc: string[] = [];
while (scanner.slice(0, 3) !== '"""' && !scanner.eof()) {
// line ending backslash
if (scanner.slice(0, 2) === "\\\n") {
scanner.next();
scanner.nextUntilChar({ comment: false });
continue;
}
const escapedChar = EscapeSequence(scanner);
if (escapedChar.ok) {
acc.push(escapedChar.body);
} else {
acc.push(scanner.char());
scanner.next();
}
}
if (scanner.eof()) {
throw new TOMLParseError(
`Multi-line string is not closed:\n${acc.join("")}`,
);
}
// if ends with 4 `"`, push the fist `"` to string
if (scanner.char(3) === '"') {
acc.push('"');
scanner.next();
}
scanner.next(3); // skip last '""""
return success(acc.join(""));
}
export function MultilineLiteralString(
scanner: Scanner,
): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
if (scanner.slice(0, 3) === "'''") {
scanner.next(3);
} else {
return failure();
}
if (scanner.char() === "\n") {
// The first newline is trimmed
scanner.next();
}
const acc: string[] = [];
while (scanner.slice(0, 3) !== "'''" && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
if (scanner.eof()) {
throw new TOMLParseError(
`Multi-line string is not closed:\n${acc.join("")}`,
);
}
// if ends with 4 `'`, push the fist `'` to string
if (scanner.char(3) === "'") {
acc.push("'");
scanner.next();
}
scanner.next(3); // skip last "'''"
return success(acc.join(""));
}
const symbolPairs: [string, unknown][] = [
["true", true],
["false", false],
["inf", Infinity],
["+inf", Infinity],
["-inf", -Infinity],
["nan", NaN],
["+nan", NaN],
["-nan", NaN],
];
export function Symbols(scanner: Scanner): ParseResult<unknown> {
scanner.nextUntilChar({ inline: true });
const found = symbolPairs.find(([str]) =>
scanner.slice(0, str.length) === str
);
if (!found) {
return failure();
}
const [str, value] = found;
scanner.next(str.length);
return success(value);
}
export const DottedKey = join(
or([BareKey, BasicString, LiteralString]),
".",
);
export function Integer(scanner: Scanner): ParseResult<number | string> {
scanner.nextUntilChar({ inline: true });
// If binary / octal / hex
const first2 = scanner.slice(0, 2);
if (first2.length === 2 && /0(?:x|o|b)/i.test(first2)) {
scanner.next(2);
const acc = [first2];
while (/[0-9a-f_]/i.test(scanner.char()) && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
if (acc.length === 1) {
return failure();
}
return success(acc.join(""));
}
const acc = [];
if (/[+-]/.test(scanner.char())) {
acc.push(scanner.char());
scanner.next();
}
while (/[0-9_]/.test(scanner.char()) && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
if (acc.length === 0 || (acc.length === 1 && /[+-]/.test(acc[0]))) {
return failure();
}
const int = parseInt(acc.filter((char) => char !== "_").join(""));
return success(int);
}
export function Float(scanner: Scanner): ParseResult<number> {
scanner.nextUntilChar({ inline: true });
// lookahead validation is needed for integer value is similar to float
let position = 0;
while (
scanner.char(position) &&
!Patterns.END_OF_VALUE.test(scanner.char(position))
) {
if (!Patterns.FLOAT.test(scanner.char(position))) {
return failure();
}
position++;
}
const acc = [];
if (/[+-]/.test(scanner.char())) {
acc.push(scanner.char());
scanner.next();
}
while (Patterns.FLOAT.test(scanner.char()) && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
if (acc.length === 0) {
return failure();
}
const float = parseFloat(acc.filter((char) => char !== "_").join(""));
if (isNaN(float)) {
return failure();
}
return success(float);
}
export function DateTime(scanner: Scanner): ParseResult<Date> {
scanner.nextUntilChar({ inline: true });
let dateStr = scanner.slice(0, 10);
// example: 1979-05-27
if (/^\d{4}-\d{2}-\d{2}/.test(dateStr)) {
scanner.next(10);
} else {
return failure();
}
const acc = [];
// example: 1979-05-27T00:32:00Z
while (/[ 0-9TZ.:-]/.test(scanner.char()) && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
dateStr += acc.join("");
const date = new Date(dateStr.trim());
// invalid date
if (isNaN(date.getTime())) {
throw new TOMLParseError(`Invalid date string "${dateStr}"`);
}
return success(date);
}
export function LocalTime(scanner: Scanner): ParseResult<string> {
scanner.nextUntilChar({ inline: true });
let timeStr = scanner.slice(0, 8);
if (/^(\d{2}):(\d{2}):(\d{2})/.test(timeStr)) {
scanner.next(8);
} else {
return failure();
}
const acc = [];
if (scanner.char() === ".") {
acc.push(scanner.char());
scanner.next();
} else {
return success(timeStr);
}
while (/[0-9]/.test(scanner.char()) && !scanner.eof()) {
acc.push(scanner.char());
scanner.next();
}
timeStr += acc.join("");
return success(timeStr);
}
export function ArrayValue(scanner: Scanner): ParseResult<unknown[]> {
scanner.nextUntilChar({ inline: true });
if (scanner.char() === "[") {
scanner.next();
} else {
return failure();
}
const array: unknown[] = [];
while (!scanner.eof()) {
scanner.nextUntilChar();
const result = Value(scanner);
if (result.ok) {
array.push(result.body);
} else {
break;
}
scanner.nextUntilChar({ inline: true });
// may have a next item, but trailing comma is allowed at array
if (scanner.char() === ",") {
scanner.next();
} else {
break;
}
}
scanner.nextUntilChar();
if (scanner.char() === "]") {
scanner.next();
} else {
throw new TOMLParseError("Array is not closed");
}
return success(array);
}
export function InlineTable(
scanner: Scanner,
): ParseResult<Record<string, unknown>> {
scanner.nextUntilChar();
const pairs = surround(
"{",
join(Pair, ","),
"}",
)(scanner);
if (!pairs.ok) {
return failure();
}
const table = {};
for (const pair of pairs.body) {
deepAssign(table, pair);
}
return success(table);
}
export const Value = or([
MultilineBasicString,
MultilineLiteralString,
BasicString,
LiteralString,
Symbols,
DateTime,
LocalTime,
Float,
Integer,
ArrayValue,
InlineTable,
]);
export const Pair = kv(DottedKey, "=", Value);
export function Block(
scanner: Scanner,
): ParseResult<BlockParseResultBody> {
scanner.nextUntilChar();
const result = merge(repeat(Pair))(scanner);
if (result.ok) {
return success({
type: "Block",
value: result.body,
});
} else {
return failure();
}
}
export const TableHeader = surround("[", DottedKey, "]");
export function Table(
scanner: Scanner,
): ParseResult<BlockParseResultBody> {
scanner.nextUntilChar();
const header = TableHeader(scanner);
if (!header.ok) {
return failure();
}
scanner.nextUntilChar();
const block = Block(scanner);
return success({
type: "Table",
key: header.body,
value: block.ok ? block.body.value : {},
});
}
export const TableArrayHeader = surround(
"[[",
DottedKey,
"]]",
);
export function TableArray(
scanner: Scanner,
): ParseResult<BlockParseResultBody> {
scanner.nextUntilChar();
const header = TableArrayHeader(scanner);
if (!header.ok) {
return failure();
}
scanner.nextUntilChar();
const block = Block(scanner);
return success({
type: "TableArray",
key: header.body,
value: block.ok ? block.body.value : {},
});
}
export function Toml(
scanner: Scanner,
): ParseResult<Record<string, unknown>> {
const blocks = repeat(or([Block, TableArray, Table]))(scanner);
if (!blocks.ok) {
return failure();
}
const body = {};
for (const block of blocks.body) {
switch (block.type) {
case "Block": {
deepAssign(body, block.value);
break;
}
case "Table": {
Utils.deepAssignWithTable(body, block);
break;
}
case "TableArray": {
Utils.deepAssignWithTable(body, block);
break;
}
}
}
return success(body);
}
export function ParserFactory<T>(parser: ParserComponent<T>) {
return function parse(tomlString: string): T {
const scanner = new Scanner(tomlString);
let parsed: ParseResult<T> | null = null;
let err: Error | null = null;
try {
parsed = parser(scanner);
} catch (e) {
err = e instanceof Error ? e : new Error("[non-error thrown]");
}
if (err || !parsed || !parsed.ok || !scanner.eof()) {
const position = scanner.position();
const subStr = tomlString.slice(0, position);
const lines = subStr.split("\n");
const row = lines.length;
const column = (() => {
let count = subStr.length;
for (const line of lines) {
if (count > line.length) {
count -= line.length + 1;
} else {
return count;
}
}
return count;
})();
const message = `Parse error on line ${row}, column ${column}: ${
err ? err.message : `Unexpected character: "${scanner.char()}"`
}`;
throw new TOMLParseError(message);
}
return parsed.body;
};
}
/**
* Parse parses TOML string into an object.
* @param tomlString
*/
export const parse = ParserFactory(Toml); | the_stack |
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import moment from 'moment';
import { useNavigation } from '@react-navigation/native';
import { useTranslation } from 'react-i18next';
import { DEVICE_LARGE } from '@/utils/deviceConstants';
import { BLACK, DARKER_GREY, ORANGE, RED, WHITE } from '@/theme/colors';
import { fontSize } from '@/theme/fonts';
import TrustlevelSlider from '@/components/Connections/TrustlevelSlider';
import { retrieveImage } from '@/utils/filesystem';
import {
connection_levels,
RECOVERY_COOLDOWN_DURATION,
} from '@/utils/constants';
import { calculateCooldownPeriod } from '@/utils/recovery';
import { recoveryConnectionsSelector } from '@/reducer/connectionsSlice';
import { useSelector } from '@/store';
import { ConnectionStats } from './ConnectionStats';
import { ProfileCard } from './ProfileCard';
// percentage determines reported warning
const REPORTED_PERCENTAGE = 0.1;
// Reported is currently not displayed inside of the reconnect view
type ReconnectViewProps = {
pendingConnection: PendingConnection;
existingConnection: Connection;
setLevelHandler: (level: ConnectionLevel) => any;
abuseHandler: () => any;
};
export const ReconnectView = ({
pendingConnection,
existingConnection,
setLevelHandler,
abuseHandler,
}: ReconnectViewProps) => {
const navigation = useNavigation();
const recoveryConnections = useSelector(recoveryConnectionsSelector);
const [identicalProfile, setIdenticalProfile] = useState(true);
const [connectionLevel, setConnectionLevel] = useState(
existingConnection.level,
);
const { t } = useTranslation();
const id = useSelector((state) => state.user.id);
const userReported = pendingConnection.reports.find(
(report) => report.id === id,
);
const reported =
!userReported &&
pendingConnection.reports.length /
(pendingConnection.connectionsNum || 1) >=
REPORTED_PERCENTAGE;
const brightIdVerified = pendingConnection.verifications
.map((v) => v.name)
.includes('BrightID');
useEffect(() => {
const compareProfiles = async () => {
if (pendingConnection.name !== existingConnection.name) {
setIdenticalProfile(false);
return;
}
const existingPhoto = await retrieveImage(
existingConnection.photo.filename,
);
if (existingPhoto !== pendingConnection.photo) {
setIdenticalProfile(false);
return;
}
// name and photo are equal
setIdenticalProfile(true);
};
compareProfiles();
}, [pendingConnection, existingConnection]);
const photoTouchHandler = (photo: string, type: 'base64' | 'file') => {
navigation.navigate('FullScreenPhoto', {
photo,
base64: type === 'base64',
});
};
const updateLevel = () => {
let cooldownPeriod = 0;
if (existingConnection.level !== connectionLevel) {
// user changed level. Check if recovery level was added or removed.
if (connectionLevel === connection_levels.RECOVERY) {
// adding recovery connection. check if cooldown period applies
cooldownPeriod = calculateCooldownPeriod({
recoveryConnections,
connection: existingConnection,
});
} else if (existingConnection.level === connection_levels.RECOVERY) {
// removing recovery connection. Cooldown period always applies.
cooldownPeriod = RECOVERY_COOLDOWN_DURATION;
}
}
if (cooldownPeriod > 0) {
// show info about cooldown period
navigation.navigate('RecoveryCooldownInfo', {
connectionId: existingConnection.id,
cooldownPeriod,
successCallback: () => {
setLevelHandler(connectionLevel);
},
});
} else {
setLevelHandler(connectionLevel);
}
};
if (identicalProfile) {
return (
<>
<View style={styles.header} testID="ReconnectScreen">
<Text style={styles.subheaderText}>
{t('connections.text.alreadyConnectedWith', {
name: pendingConnection.name,
})}
</Text>
<Text style={styles.lastConnectedText}>
{t('connections.tag.lastConnected', {
date: moment(
parseInt(String(pendingConnection.connectedAt), 10),
).fromNow(),
})}
</Text>
</View>
<View style={styles.profiles}>
<View testID="identicalProfileView" style={styles.profile}>
<ProfileCard
name={pendingConnection.name}
photo={pendingConnection.photo}
photoSize="large"
photoType="base64"
verified={brightIdVerified}
photoTouchHandler={photoTouchHandler}
reported={reported}
userReported={userReported}
/>
</View>
</View>
<View style={styles.countsContainer}>
<ConnectionStats
connectionsNum={pendingConnection.connectionsNum}
groupsNum={pendingConnection.groupsNum}
mutualConnectionsNum={pendingConnection.mutualConnections.length}
/>
</View>
<View style={styles.connectionLevel}>
<View style={styles.connectionLevelLabel}>
<Text style={styles.connectionLevelLabelText}>
{t('connections.label.currentConnectionLevel')}
</Text>
</View>
<View style={styles.connectionLevel} testID="ReconnectSliderView">
<TrustlevelSlider
currentLevel={connectionLevel}
changeLevelHandler={setConnectionLevel}
incomingLevel={existingConnection.incomingLevel}
verbose={false}
/>
</View>
</View>
<View style={styles.actionButtons}>
<TouchableOpacity
style={styles.updateButton}
onPress={updateLevel}
testID="updateBtn"
>
<Text style={styles.updateButtonLabel}>
{t('connections.button.reconnect')}
</Text>
</TouchableOpacity>
</View>
</>
);
} else {
return (
<>
<View style={styles.header} testID="ReconnectScreen">
<Text style={styles.subheaderText}>
{t('connections.text.alreadyConnectedWith')}
</Text>
<Text style={styles.lastConnectedText}>
{t('connections.tag.lastConnected', {
date: moment(
parseInt(String(existingConnection.createdAt), 10),
).fromNow(),
})}
</Text>
</View>
<View style={styles.profiles}>
<View
testID="oldProfileView"
style={[styles.profile, styles.verticalDivider]}
>
<View style={styles.profileHeader}>
<Text style={styles.profileHeaderText}>
{t('connections.label.oldProfile')}
</Text>
</View>
<ProfileCard
name={existingConnection.name}
photo={existingConnection.photo.filename}
photoSize="small"
photoType="file"
verified={brightIdVerified}
photoTouchHandler={photoTouchHandler}
reported={reported}
userReported={userReported}
/>
</View>
<View testID="newProfileView" style={styles.profile}>
<View style={styles.profileHeader}>
<Text style={styles.profileHeaderText}>
{t('connections.label.newProfile')}
</Text>
</View>
<ProfileCard
name={pendingConnection.name}
photo={pendingConnection.photo}
photoSize="small"
photoType="base64"
verified={brightIdVerified}
photoTouchHandler={photoTouchHandler}
reported={reported}
userReported={userReported}
/>
</View>
</View>
<View style={styles.countsContainer}>
<ConnectionStats
connectionsNum={pendingConnection.connectionsNum}
groupsNum={pendingConnection.groupsNum}
mutualConnectionsNum={pendingConnection.mutualConnections.length}
/>
</View>
<View style={styles.connectionLevel}>
<View style={styles.connectionLevelLabel}>
<Text style={styles.connectionLevelLabelText}>
{t('connections.label.currentConnectionLevel')}
</Text>
</View>
<View style={styles.connectionLevel} testID="ReconnectSliderView">
<TrustlevelSlider
currentLevel={connectionLevel}
changeLevelHandler={setConnectionLevel}
incomingLevel={existingConnection.incomingLevel}
verbose={false}
/>
</View>
</View>
<View style={styles.actionButtons}>
<TouchableOpacity
style={styles.abuseButton}
onPress={abuseHandler}
testID="reportAbuseBtn"
>
<Text style={styles.abuseButtonLabel}>
{t('connections.button.reportConnection')}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.updateButton}
onPress={updateLevel}
testID="updateBtn"
>
<Text style={styles.updateButtonLabel}>
{t('connections.button.updateConnection')}
</Text>
</TouchableOpacity>
</View>
</>
);
}
};
const styles = StyleSheet.create({
header: {
marginTop: DEVICE_LARGE ? 10 : 4,
justifyContent: 'center',
alignItems: 'center',
marginBottom: 5,
},
subheaderText: {
fontFamily: 'Poppins-Medium',
fontSize: fontSize[15],
textAlign: 'center',
color: DARKER_GREY,
},
lastConnectedText: {
fontFamily: 'Poppins-Bold',
fontSize: fontSize[15],
textAlign: 'center',
color: DARKER_GREY,
},
profiles: {
flexDirection: 'row',
marginTop: 8,
marginBottom: 0,
},
profileHeader: {
marginTop: 8,
marginBottom: 10,
},
profileHeaderText: {
fontFamily: 'Poppins-Bold',
fontSize: fontSize[15],
color: BLACK,
},
profile: {
flex: 1,
alignItems: 'center',
},
verticalDivider: {
borderRightWidth: StyleSheet.hairlineWidth,
borderColor: ORANGE,
height: '100%',
},
countsContainer: {
width: '88%',
paddingTop: 6,
paddingBottom: 6,
marginTop: 8,
marginBottom: 16,
borderTopWidth: StyleSheet.hairlineWidth,
borderBottomWidth: StyleSheet.hairlineWidth,
borderColor: ORANGE,
justifyContent: 'space-evenly',
flexDirection: 'row',
},
connectionLevel: {
alignItems: 'center',
},
connectionLevelLabel: {
marginBottom: 10,
},
connectionLevelLabelText: {
fontFamily: 'Poppins-Bold',
fontSize: fontSize[15],
color: BLACK,
},
connectionLevelText: {
fontFamily: 'Poppins-Medium',
fontSize: fontSize[15],
marginBottom: 5,
},
actionButtons: {
flexDirection: 'row',
width: '88%',
},
abuseButton: {
backgroundColor: RED,
flex: 1,
marginRight: 5,
borderRadius: 60,
alignItems: 'center',
paddingTop: 8,
paddingBottom: 9,
},
abuseButtonLabel: {
fontFamily: 'Poppins-Bold',
fontSize: fontSize[14],
color: WHITE,
},
updateButton: {
backgroundColor: WHITE,
borderColor: ORANGE,
borderWidth: 1,
borderRadius: 60,
flex: 1,
marginLeft: 5,
alignItems: 'center',
paddingTop: 8,
paddingBottom: 9,
},
updateButtonLabel: {
fontFamily: 'Poppins-Bold',
fontSize: fontSize[14],
color: ORANGE,
},
}); | the_stack |
export const transformedOriginalTokens = {
/**
* size
*/
size: {
name: 'size token 16px (height: 24px)',
comment: 'a size description',
category: 'size',
exportKey: 'size',
type: 'number',
unit: 'pixel',
value: 16
},
/**
* breakpoint
*/
breakpoint: {
name: 'breakpoint token 1024px (height: 20px)',
comment: 'a breakpoint description',
category: 'breakpoint',
exportKey: 'breakpoint',
type: 'number',
unit: 'pixel',
value: 1024
},
/**
* spacing
*/
spacing: {
name: 'spacing 24, 20,16, 8',
comment: 'a spacing token',
category: 'spacing',
exportKey: 'spacing',
top: {
value: 24,
unit: 'pixel',
type: 'number'
},
right: {
value: 20,
unit: 'pixel',
type: 'number'
},
bottom: {
value: 16,
unit: 'pixel',
type: 'number'
},
left: {
value: 8,
unit: 'pixel',
type: 'number'
}
},
/**
* radiusMixed
*/
radiusMixed: {
name: 'radius 1,2,3,4',
comment: 'a mixed radius token',
category: 'radius',
exportKey: 'radius',
radiusType: {
value: 'mixed',
type: 'string'
},
radii: {
topLeft: {
value: 1,
unit: 'pixel',
type: 'number'
},
topRight: {
value: 2,
unit: 'pixel',
type: 'number'
},
bottomRight: {
value: 3,
unit: 'pixel',
type: 'number'
},
bottomLeft: {
value: 4,
unit: 'pixel',
type: 'number'
}
},
smoothing: {
value: 0.5,
type: 'number'
}
},
/**
* radiusSingle
*/
radiusSingle: {
name: 'radius 5',
comment: 'a single radius token',
category: 'radius',
exportKey: 'radius',
radius: {
value: 5,
unit: 'pixel',
type: 'number'
},
radiusType: {
value: 'single',
type: 'string'
},
radii: {
topLeft: {
value: 5,
unit: 'pixel',
type: 'number'
},
topRight: {
value: 5,
unit: 'pixel',
type: 'number'
},
bottomRight: {
value: 5,
unit: 'pixel',
type: 'number'
},
bottomLeft: {
value: 5,
unit: 'pixel',
type: 'number'
}
},
smoothing: {
value: 0.0,
type: 'number'
}
},
/**
* grid
*/
grid: {
name: 'grid',
comment: 'a grid token',
category: 'grid',
exportKey: 'grid',
pattern: {
value: 'columns',
type: 'string'
},
sectionSize: {
value: 8,
unit: 'pixel',
type: 'number'
},
gutterSize: {
value: 8,
type: 'number',
unit: 'pixel'
},
alignment: {
value: 'center',
type: 'string'
},
count: {
value: 6,
type: 'number'
},
offset: {
value: 16,
type: 'number',
unit: 'pixel'
}
},
multiGrid: {
name: 'multiGrid',
comment: 'a multiGrid token',
category: 'grid',
exportKey: 'grid',
0: {
pattern: {
value: 'columns',
type: 'string'
},
sectionSize: {
value: 8,
unit: 'pixel',
type: 'number'
},
gutterSize: {
value: 8,
type: 'number',
unit: 'pixel'
},
alignment: {
value: 'center',
type: 'string'
},
count: {
value: 6,
type: 'number'
},
offset: {
value: 16,
type: 'number',
unit: 'pixel'
}
},
1: {
pattern: {
value: 'columns',
type: 'string'
},
sectionSize: {
value: 8,
unit: 'pixel',
type: 'number'
},
gutterSize: {
value: 8,
type: 'number',
unit: 'pixel'
},
alignment: {
value: 'center',
type: 'string'
},
count: {
value: 6,
type: 'number'
},
offset: {
value: 16,
type: 'number',
unit: 'pixel'
}
}
},
/**
* font
*/
font: {
name: 'font 16',
category: 'font',
exportKey: 'font',
comment: 'a font token',
fontSize: {
value: 16,
type: 'number',
unit: 'pixel'
},
textDecoration: {
value: 'underline',
type: 'string'
},
fontFamily: {
value: 'Helvetica',
type: 'string'
},
fontWeight: {
value: 700,
type: 'number'
},
fontStyle: {
value: 'italic',
type: 'string'
},
fontStretch: {
value: 'normal',
type: 'string'
},
_fontStyleOld: {
value: 'bold italic',
type: 'string'
},
letterSpacing: {
value: 120,
type: 'number',
unit: 'percent'
},
lineHeight: {
value: 'normal',
type: 'string',
unit: 'auto'
},
paragraphIndent: {
value: 0,
type: 'number',
unit: 'pixel'
},
paragraphSpacing: {
value: 12,
type: 'number',
unit: 'pixel'
},
textCase: {
value: 'none',
type: 'string'
}
},
/**
* border
*/
border: {
name: 'border',
category: 'border',
exportKey: 'border',
comment: 'a border token',
stroke: {
value: 'rgba(255, 230, 0, 1)',
type: 'color'
},
strokeWeight: {
value: 4,
unit: 'pixel',
type: 'number'
},
strokeMiterLimit: {
value: 0,
unit: 'degree',
type: 'number'
},
strokeJoin: {
value: 'round',
type: 'string'
},
strokeCap: {
value: 'none',
type: 'string'
},
dashPattern: {
value: '5, 5',
type: 'string'
},
strokeAlign: {
value: 'center',
type: 'string'
}
},
/**
* color
*/
color: {
name: 'background',
comment: 'a color token',
category: 'color',
exportKey: 'color',
type: 'color',
value: 'rgba(255, 230, 0, 1)'
},
multiColor: {
name: 'multiColor',
comment: 'a multi color token',
category: 'color',
exportKey: 'color',
0: {
type: 'color',
value: 'rgba(255, 230, 0, 1)'
},
1: {
type: 'color',
value: 'rgba(0, 100, 255, 0.5)'
}
},
/**
* gradient
*/
gradient: {
name: 'gradient',
category: 'gradient',
exportKey: 'gradient',
comment: 'a gradient token',
gradientType: {
value: 'linear',
type: 'string'
},
rotation: {
type: 'number',
unit: 'degree',
value: 45
},
stops: {
0: {
position: {
value: 0,
type: 'number'
},
color: {
value: 'rgba(255, 230, 0, 0.5)',
type: 'color'
}
},
1: {
position: {
value: 1,
type: 'number'
},
color: {
value: 'rgba(0, 100, 250, 1)',
type: 'color'
}
}
},
opacity: {
value: 0.5,
type: 'number'
}
},
/**
* gradient and colors
*/
gradientAndColor: {
name: 'gradientAndColor',
category: 'gradient',
exportKey: 'gradient',
comment: 'a gradient and color token',
0: {
gradientType: {
value: 'linear',
type: 'string'
},
rotation: {
type: 'number',
unit: 'degree',
value: 45
},
stops: {
0: {
position: {
value: 0,
type: 'number'
},
color: {
value: 'rgba(255, 230, 0, 1)',
type: 'color'
}
},
1: {
position: {
value: 1,
type: 'number'
},
color: {
value: 'rgba(0, 100, 250, 1)',
type: 'color'
}
}
},
opacity: {
value: 1,
type: 'number'
}
},
1: {
type: 'color',
value: 'rgba(0, 100, 255, 0.5)'
}
},
colorAndGradient: {
name: 'colorAndGradient',
category: 'color',
exportKey: 'color',
comment: 'a color and gradient token',
0: {
type: 'color',
value: 'rgba(255, 230, 0, 1)'
},
1: {
gradientType: {
value: 'linear',
type: 'string'
},
rotation: {
type: 'number',
unit: 'degree',
value: 45
},
stops: {
0: {
position: {
value: 0,
type: 'number'
},
color: {
value: 'rgba(255, 230, 0, 1)',
type: 'color'
}
},
1: {
position: {
value: 1,
type: 'number'
},
color: {
value: 'rgba(0, 100, 250, 1)',
type: 'color'
}
}
},
opacity: {
value: 1,
type: 'number'
}
}
},
/**
* effect
*/
effect: {
name: 'effect',
comment: 'an effect token',
category: 'effect',
exportKey: 'effect',
type: {
value: 'dropShadow',
type: 'string'
},
radius: {
value: 0,
type: 'number',
unit: 'pixel'
},
color: {
value: 'rgba(10, 12, 14, 0.1)',
type: 'color'
},
offset: {
x: {
value: 2,
type: 'number',
unit: 'pixel'
},
y: {
value: 4,
type: 'number',
unit: 'pixel'
}
},
spread: {
value: 0,
type: 'number',
unit: 'pixel'
}
},
multiEffect: {
name: 'multiEffect',
comment: 'a multi effect token',
category: 'effect',
exportKey: 'effect',
0: {
type: {
value: 'dropShadow',
type: 'string'
},
radius: {
value: 0,
type: 'number',
unit: 'pixel'
},
color: {
value: 'rgba(10, 12, 14, 0.1)',
type: 'color'
},
offset: {
x: {
value: 2,
type: 'number',
unit: 'pixel'
},
y: {
value: 4,
type: 'number',
unit: 'pixel'
}
},
spread: {
value: 0,
type: 'number',
unit: 'pixel'
}
},
1: {
type: {
value: 'dropShadow',
type: 'string'
},
radius: {
value: 0,
type: 'number',
unit: 'pixel'
},
color: {
value: 'rgba(10, 12, 14, 0.2)',
type: 'color'
},
offset: {
x: {
value: 2,
type: 'number',
unit: 'pixel'
},
y: {
value: 4,
type: 'number',
unit: 'pixel'
}
},
spread: {
value: 0,
type: 'number',
unit: 'pixel'
}
}
},
/**
* motion
*/
motion: {
name: 'motion',
category: 'motion',
exportKey: 'motion',
comment: 'a motion token',
type: {
value: 'slide_in',
type: 'string'
},
duration: {
value: 0.2,
unit: 's',
type: 'number'
},
direction: {
value: 'top',
type: 'string'
},
easing: {
value: 'ease-in',
type: 'string'
},
easingFunction: {
x1: {
value: 0.41999998688697815,
type: 'number'
},
x2: {
value: 0,
type: 'number'
},
y1: {
value: 1,
type: 'number'
},
y2: {
value: 1,
type: 'number'
}
}
}
// END of object
} | the_stack |
import {Position, Range} from 'vscode-languageserver';
import * as vscode from 'vscode-languageserver';
import * as coqProto from './../coqtop/coq-proto';
import * as parser from './../parsing/coq-parser';
import * as textUtil from './../util/text-util';
import {Sentence} from './../sentence-model/Sentence';
import {ProofView,Goal,UnfocusedGoalStack} from '../protocol';
import {AnnotatedText} from '../util/AnnotatedText';
import * as diff from './DiffProofView';
import {GoalId, ProofViewReference, GoalsCache} from './GoalsCache'
export type StateId = number;
export interface StatusErrorInternal {
/** Error message */
message: AnnotatedText,
/** Range of error within this sentence w.r.t. document positions. Is `undefined` if the error applies to the whole sentence */
range?: Range,
}
export interface StatusError extends StatusErrorInternal {
/** Error message */
message: AnnotatedText,
/** Range of error within this sentence w.r.t. document positions. Is `undefined` if the error applies to the whole sentence */
range?: Range,
/** Range of the sentence containing the error */
sentence: Range,
}
export enum StateStatus {
Parsing, Processing, Processed, Error, Axiom, Incomplete,
}
enum StateStatusFlags {
Parsing = 0,
Processing = 1 << 0,
Incomplete = 1 << 1,
Unsafe = 1 << 2,
Error = 1 << 3,
Warning = 1 << 4,
}
export class State {
private status: StateStatusFlags;
// private proofView: CoqTopGoalResult;
private computeTimeMS: number;
private error?: StatusErrorInternal = undefined;
// set to true when a document change has invalidated the meaning of the associated sentence; this state needs to be cancelled
private markedInvalidated = false;
private goal : ProofViewReference | null = null;
private constructor
( private commandText: string
, private stateId: StateId
, private textRange: Range
, private prev: State | null
, private next: State | null
, private computeStart: [number,number] = [0,0]
) {
this.status = StateStatusFlags.Parsing;
// this.proofView = {};
this.computeTimeMS = 0;
}
public static newRoot(stateId: StateId) : State {
return new State("",stateId,Range.create(0,0,0,0),null,null,[0,0]);
}
public static add(parent: State, command: string, stateId: number, range: Range, computeStart : [number,number]) : State {
// This implies a strict order of descendents by document position
// To support comments that are not added as sentences,
// this could be loosened to if(textUtil.isBefore(range.start,parent.textRange.end)).
if(!textUtil.positionIsEqual(range.start, parent.textRange.end))
throw "New sentence is expected to be adjacent to its parent";
const result = new State(command,stateId,range,parent,parent.next,computeStart);
parent.next = result;
return result;
}
public toString() : string {
return this.commandText;
}
public getText() : string {
return this.commandText;
}
public getStateId() : StateId {
return this.stateId;
}
/** Iterates all parent states */
public *ancestors() : Iterable<State> {
let state = this.prev;
while(state != null) {
yield state;
state = state.prev;
}
}
/** Iterates all decendent states */
public *descendants() : Iterable<State> {
let state = this.next;
while(state != null) {
yield state;
state = state.next;
}
}
/** Iterates all decendent states until, and not including, end */
public *descendantsUntil(end: StateId|State) : Iterable<State> {
let state = this.next;
while(state != null && state.stateId !== end && state !== end) {
yield state;
state = state.next;
}
}
/** Iterates this and all ancestor states in the order they appear in the document */
public *backwards() : Iterable<State> {
yield this;
yield *this.ancestors();
}
/** Iterates this and all decentant states in the order they appear in the document */
public *forwards() : Iterable<State> {
yield this;
yield *this.descendants();
}
public getParent() : State {
return this.prev;
}
public getNext() : State {
return this.next;
}
public truncate() {
if(this.next)
this.next.prev = null;
this.next = null;
}
public unlink() {
if(this.prev)
this.prev.next = this.next;
if(this.next)
this.next.prev = this.prev;
}
public updateWorkerStatus(workerId: string, status: string) {
}
/** Handle sentence-status updates as they come from coqtop */
public updateStatus(status: coqProto.SentenceStatus) {
switch(status) {
case coqProto.SentenceStatus.Parsing:
this.status = StateStatusFlags.Parsing;
this.computeStart = process.hrtime();
this.computeTimeMS = 0;
break;
case coqProto.SentenceStatus.AddedAxiom:
this.status &= ~(StateStatusFlags.Processing | StateStatusFlags.Error);
this.status |= StateStatusFlags.Unsafe;
break;
case coqProto.SentenceStatus.Processed:
if(this.status & StateStatusFlags.Processing) {
const duration = process.hrtime(this.computeStart);
this.computeTimeMS = duration[0] * 1000.0 + (duration[1] / 1000000.0);
this.status &= ~StateStatusFlags.Processing;
}
break;
case coqProto.SentenceStatus.ProcessingInWorker:
if(!(this.status & StateStatusFlags.Processing)) {
this.computeStart = process.hrtime();
this.status |= StateStatusFlags.Processing;
}
break;
case coqProto.SentenceStatus.Incomplete:
this.status |= StateStatusFlags.Incomplete;
break;
case coqProto.SentenceStatus.Complete:
this.status &= ~StateStatusFlags.Incomplete;
break;
case coqProto.SentenceStatus.InProgress:
break;
}
}
public getRange() : Range {
return this.textRange;
}
public hasGoal() : boolean {
return this.goal !== null;
}
public setGoal(goal: ProofViewReference) {
this.goal = goal;
}
public getGoal(goalsCache: GoalsCache) : ProofView|null {
if(!this.goal)
return null;
const newGoals = {...goalsCache.getProofView(this.goal), focus: this.textRange.end};
if(this.prev && this.prev.goal) {
const oldGoals = goalsCache.getProofView(this.prev.goal);
return diff.diffProofView(oldGoals, newGoals);
}
return newGoals;
}
/** Adjust's this sentence by the change
* @returns true if the delta intersects this sentence
*/
private shift(delta: textUtil.RangeDelta) : boolean {
this.textRange = textUtil.rangeDeltaTranslate(this.textRange, delta);
// invalidate if there is an intersection
return textUtil.rangeIntersects(this.textRange, Range.create(delta.start,delta.end));
}
/**
* Applies the textual changes to the sentence
* @return false if the change has invalidated the sentence; true if preserved
*/
public applyTextChanges(changes: vscode.TextDocumentContentChangeEvent[], deltas: textUtil.RangeDelta[], updatedDocumentText: string) : boolean {
if(this.isRoot())
return true;
let newText = this.commandText;
let newRange = this.textRange;
let newErrorRange = undefined;
if(this.error && this.error.range)
newErrorRange = this.error.range;
let touchesEnd = false; // indicates whether a change has touched the end of this sentence
change: for(let idx = 0; idx < changes.length; ++ idx) {
const change = changes[idx];
const delta = deltas[idx];
switch(parser.sentenceRangeContainment(newRange,change.range)) {
case parser.SentenceRangeContainment.Before:
newRange = textUtil.rangeDeltaTranslate(newRange,delta);
if(newErrorRange)
newErrorRange = textUtil.rangeDeltaTranslate(newErrorRange,delta);
continue change;
case parser.SentenceRangeContainment.After:
if(textUtil.positionIsEqual(this.textRange.end, change.range.start))
touchesEnd = true;
continue change; // ignore this change
case parser.SentenceRangeContainment.Crosses:
return false; // give up; this sentence is toast (invalidated; needs to be cancelled)
case parser.SentenceRangeContainment.Contains:
// the change falls within this sentence
const beginOffset = textUtil.relativeOffsetAtAbsolutePosition(newText, newRange.start, change.range.start);
if(beginOffset == -1)
continue change;
newText =
newText.substring(0,beginOffset)
+ change.text
+ newText.substring(beginOffset+change.rangeLength);
// newRange = Range.create(newRange.start,textUtil.positionRangeDeltaTranslateEnd(newRange.end,delta));
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
newRange.end = textUtil.positionRangeDeltaTranslateEnd(newRange.end,delta);
if(newErrorRange)
newErrorRange = textUtil.rangeDeltaTranslate(newErrorRange,delta);
} // switch
} // change: for
if(touchesEnd) {
// We need to reparse the sentence to make sure the end of the sentence has not changed
const endOffset = textUtil.offsetAt(updatedDocumentText, newRange.end);
// The problem is if a non-blank [ \r\n] is now contacting the end-period of this sentence; we need only check one more character
const newEnd = parser.parseSentenceLength(newText + updatedDocumentText.substr(endOffset, 1));
if(newEnd === -1 || newEnd !== newText.length)
return false; // invalidate: bad or changed syntax
}
if(parser.isPassiveDifference(this.commandText, newText)) {
this.commandText = newText;
this.textRange = newRange;
if(newErrorRange)
this.error.range = newErrorRange;
return true;
} else
return false;
}
public isRoot() : boolean {
return this.prev === null;
}
public markInvalid() : void {
this.markedInvalidated = true;
}
public isInvalidated() : boolean {
return this.markedInvalidated;
}
/** Removes descendents until (and not including) state end */
public *removeDescendentsUntil(end: State) : Iterable<State> {
for(let state of this.descendantsUntil(end.stateId))
yield state;
// unlink the traversed sentences
this.next = end;
end.prev = this;
}
public getStatus() : StateStatus {
if (this.status & StateStatusFlags.Error)
return StateStatus.Error;
else if (this.status & StateStatusFlags.Processing)
return StateStatus.Processing;
else if (this.status & StateStatusFlags.Unsafe)
return StateStatus.Axiom;
else if (this.status & StateStatusFlags.Incomplete)
return StateStatus.Incomplete;
else if (this.status & StateStatusFlags.Parsing)
return StateStatus.Parsing;
else
return StateStatus.Processed;
}
/** @returns `true` if this sentence appears strictly before `position` */
public isBefore(position: Position) : boolean {
return textUtil.positionIsBeforeOrEqual(this.textRange.end, position);
}
/** @returns `true` if this sentence appears before or contains `position` */
public isBeforeOrAt(position: Position) : boolean {
return textUtil.positionIsBeforeOrEqual(this.textRange.end, position) || textUtil.positionIsBeforeOrEqual(this.textRange.start, position);
}
/** @returns `true` if this sentence appears strictly after `position`. */
public isAfter(position: Position) : boolean {
return textUtil.positionIsAfter(this.textRange.start, position);
}
/** @returns `true` if this sentence appears after or contains `position`. */
public isAfterOrAt(position: Position) : boolean {
return textUtil.positionIsAfterOrEqual(this.textRange.start, position) ||
textUtil.positionIsAfter(this.textRange.end, position);
}
/** @returns `true` if this sentence contains `position`. */
public contains(position: Position) : boolean {
return textUtil.positionIsBeforeOrEqual(this.textRange.start, position) &&
textUtil.positionIsAfter(this.textRange.end, position);
}
/** This sentence has reached an error state
* @param location: optional offset range within the sentence where the error occurred
*/
public setError(message: AnnotatedText, location?: coqProto.Location) : void {
this.error = {message: message};
if(location && location.start !== location.stop) {
this.status |= StateStatusFlags.Error;
this.status &= ~StateStatusFlags.Processing;
const sentRange = this.getRange();
const sentText = this.getText();
this.error.range =
Range.create(
textUtil.positionAtRelativeCNL(sentRange.start, sentText, location.start),
textUtil.positionAtRelativeCNL(sentRange.start, sentText, location.stop))
}
}
public getError() : StatusError|null {
if(this.error) {
const range = this.getRange();
return Object.assign(this.error, {sentence: range});
} else
return null;
}
} | the_stack |
import { HttpClientModule } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { AngularTokenModule } from './angular-token.module';
import { AngularTokenService } from './angular-token.service';
import {
SignInData,
RegisterData,
UpdatePasswordData,
ResetPasswordData,
AuthData,
UserData,
AngularTokenOptions
} from './angular-token.model';
describe('AngularTokenService', () => {
// Init common test data
const tokenType = 'Bearer';
const uid = 'test@test.com';
const accessToken = 'fJypB1ugmWHJfW6CELNfug';
const client = '5dayGs4hWTi4eKwSifu_mg';
const expiry = '1472108318';
const tokenHeaders = {
'content-Type': 'application/json',
'token-type': tokenType,
'uid': uid,
'access-token': accessToken,
'client': client,
'expiry': expiry
};
const authData: AuthData = {
tokenType: tokenType,
uid: uid,
accessToken: accessToken,
client: client,
expiry: expiry
};
const userData: UserData = {
id: 1,
provider: 'provider',
uid: 'uid',
name: 'name',
nickname: 'nickname',
image: null,
login: 'test@test.de'
};
// SignIn test data
const signInData: SignInData = {
login: 'test@test.de',
password: 'password'
};
const signInDataOutput = {
email: 'test@test.de',
password: 'password'
};
const signInDataCustomOutput = {
username: 'test@test.de',
password: 'password'
};
// Register test data
const registerData: RegisterData = {
login: 'test@test.de',
password: 'password',
passwordConfirmation: 'password'
};
// Register test data
const registerCustomFieldsData: RegisterData = {
login: 'test@test.de',
first_name: 'John',
last_name: 'Doe',
password: 'password',
passwordConfirmation: 'password'
};
const registerCustomFieldsDataOutput = {
email: 'test@test.de',
first_name: 'John',
last_name: 'Doe',
password: 'password',
password_confirmation: 'password',
confirm_success_url: window.location.href
};
const registerDataOutput = {
email: 'test@test.de',
password: 'password',
password_confirmation: 'password',
confirm_success_url: window.location.href
};
const registerCustomDataOutput = {
username: 'test@test.de',
password: 'password',
password_confirmation: 'password',
confirm_success_url: window.location.href
};
// Update password data
const updatePasswordData: UpdatePasswordData = {
password: 'newpassword',
passwordConfirmation: 'newpassword',
passwordCurrent: 'oldpassword'
};
const updatePasswordDataOutput = {
current_password: 'oldpassword',
password: 'newpassword',
password_confirmation: 'newpassword'
};
// Reset password data
const resetPasswordData: ResetPasswordData = {
login: 'test@test.de',
};
const resetPasswordDataOutput = {
email: 'test@test.de',
redirect_url: 'http://localhost:9876/context.html'
};
const resetCustomPasswordDataOutput = {
username: 'test@test.de',
redirect_url: 'http://localhost:9876/context.html'
};
let service: AngularTokenService;
let backend: HttpTestingController;
function initService(serviceConfig: AngularTokenOptions) {
// Inject HTTP and AngularTokenService
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule,
AngularTokenModule.forRoot(serviceConfig)
],
providers: [
AngularTokenService
]
});
service = TestBed.inject(AngularTokenService);
backend = TestBed.inject(HttpTestingController);
}
beforeEach(() => {
// Fake Local Storage
let store: { [key: string]: string; } = {};
const fakeSessionStorage = {
setItem: (key: string, value: string) => store[key] = `${value}`,
getItem: (key: string): string => key in store ? store[key] : null,
removeItem: (key: string) => delete store[key],
clear: () => store = {}
};
spyOn(Storage.prototype, 'setItem').and.callFake(fakeSessionStorage.setItem);
spyOn(Storage.prototype, 'getItem').and.callFake(fakeSessionStorage.getItem);
spyOn(Storage.prototype, 'removeItem').and.callFake(fakeSessionStorage.removeItem);
spyOn(Storage.prototype, 'clear').and.callFake(fakeSessionStorage.clear);
});
afterEach(() => {
backend.verify();
});
/**
*
* Test default configuration
*
*/
describe('default configuration', () => {
beforeEach(() => {
initService({});
});
it('signIn should POST data', () => {
service.signIn(signInData);
const req = backend.expectOne({
url: 'auth/sign_in',
method: 'POST'
});
expect(req.request.body).toEqual(signInDataOutput);
});
it('signIn method should set local storage', () => {
service.signIn(signInData).subscribe(data => {
expect(localStorage.getItem('accessToken')).toEqual(accessToken);
expect(localStorage.getItem('client')).toEqual(client);
expect(localStorage.getItem('expiry')).toEqual(expiry);
expect(localStorage.getItem('tokenType')).toEqual(tokenType);
expect(localStorage.getItem('uid')).toEqual(uid);
});
const req = backend.expectOne({
url: 'auth/sign_in',
method: 'POST'
});
req.flush(
{ login: 'test@email.com' },
{ headers: tokenHeaders }
);
});
it('signOut should DELETE', () => {
service.signOut().subscribe();
backend.expectOne({
url: 'auth/sign_out',
method: 'DELETE'
});
expect(localStorage.getItem('accessToken')).toBeNull();
expect(localStorage.getItem('client')).toBeNull();
expect(localStorage.getItem('expiry')).toBeNull();
expect(localStorage.getItem('tokenType')).toBeNull();
expect(localStorage.getItem('uid')).toBeNull();
});
it('signOut should clear local storage', () => {
localStorage.setItem('token-type', tokenType);
localStorage.setItem('uid', uid);
localStorage.setItem('access-token', accessToken);
localStorage.setItem('client', client);
localStorage.setItem('expiry', expiry);
service.signOut().subscribe( data => {
expect(localStorage.getItem('accessToken')).toBe(null);
expect(localStorage.getItem('client')).toBe(null);
expect(localStorage.getItem('expiry')).toBe(null);
expect(localStorage.getItem('tokenType')).toBe(null);
expect(localStorage.getItem('uid')).toBe(null);
});
backend.expectOne({
url: 'auth/sign_out',
method: 'DELETE'
});
});
describe('registerAccount should POST data', () => {
it('with standard fields', () => {
service.registerAccount(registerData).subscribe();
const req = backend.expectOne({
url: 'auth',
method: 'POST'
});
expect(req.request.body).toEqual(registerDataOutput);
});
it('with custom fields', () => {
service.registerAccount(registerCustomFieldsData).subscribe();
const req = backend.expectOne({
url: 'auth',
method: 'POST'
});
expect(req.request.body).toEqual(registerCustomFieldsDataOutput);
});
});
it('validateToken should GET', () => {
service.validateToken();
backend.expectOne({
url: 'auth/validate_token',
method: 'GET'
});
});
it('validateToken should not call signOut when it returns status 401', () => {
const signOutSpy = spyOn(service, 'signOut');
service.validateToken().subscribe(() => {}, () => expect(signOutSpy).not.toHaveBeenCalled());
const req = backend.expectOne({
url: 'auth/validate_token',
method: 'GET'
});
req.flush('',
{
status: 401,
statusText: 'Not authorized'
}
);
});
it('updatePassword should PUT', () => {
service.updatePassword(updatePasswordData).subscribe();
const req = backend.expectOne({
url: 'auth',
method: 'PUT'
});
expect(req.request.body).toEqual(updatePasswordDataOutput);
});
it('resetPassword should POST', () => {
service.resetPassword(resetPasswordData).subscribe();
const req = backend.expectOne({
url: 'auth/password',
method: 'POST'
});
expect(req.request.body).toEqual(resetPasswordDataOutput);
});
});
/**
*
* Testing custom configuration
*
*/
describe('custom configuration', () => {
beforeEach(() => {
initService({
apiBase: 'https://localhost',
apiPath: 'myapi',
signInPath: 'myauth/mysignin',
signOutPath: 'myauth/mysignout',
registerAccountPath: 'myauth/myregister',
deleteAccountPath: 'myauth/mydelete',
validateTokenPath: 'myauth/myvalidate',
updatePasswordPath: 'myauth/myupdate',
resetPasswordPath: 'myauth/myreset',
loginField: 'username'
});
});
it('signIn should POST data', () => {
service.signIn(signInData);
const req = backend.expectOne({
url: 'https://localhost/myapi/myauth/mysignin',
method: 'POST'
});
expect(req.request.body).toEqual(signInDataCustomOutput);
});
it('signOut should DELETE', () => {
service.signOut().subscribe();
backend.expectOne({
url: 'https://localhost/myapi/myauth/mysignout',
method: 'DELETE'
});
});
it('registerAccount should POST data', () => {
service.registerAccount(registerData).subscribe();
const req = backend.expectOne({
url: 'https://localhost/myapi/myauth/myregister',
method: 'POST'
});
expect(req.request.body).toEqual(registerCustomDataOutput);
});
it('validateToken should GET', () => {
service.validateToken();
backend.expectOne({
url: 'https://localhost/myapi/myauth/myvalidate',
method: 'GET'
});
});
it('updatePassword should PUT', () => {
service.updatePassword(updatePasswordData).subscribe();
const req = backend.expectOne({
url: 'https://localhost/myapi/myauth/myupdate',
method: 'PUT'
});
expect(req.request.body).toEqual(updatePasswordDataOutput);
});
it('resetPassword should POST', () => {
service.resetPassword(resetPasswordData).subscribe();
const req = backend.expectOne({
url: 'https://localhost/myapi/myauth/myreset',
method: 'POST'
});
expect(req.request.body).toEqual(resetCustomPasswordDataOutput);
});
});
describe('signoutValidate', () => {
beforeEach(() => {
initService({
signOutFailedValidate: true
});
});
it('validateToken should call signOut when it returns status 401', () => {
const signOutSpy = spyOn(service, 'signOut');
service.validateToken().subscribe(() => {}, () => expect(signOutSpy).toHaveBeenCalled() );
const req = backend.expectOne({
url: 'auth/validate_token',
method: 'GET'
});
req.flush('',
{
status: 401,
statusText: 'Not authorized'
}
);
});
});
describe('user signed out', () => {
beforeEach(() => {
initService({});
});
it('currentAuthData should return undefined', () => {
expect(service.currentAuthData).toEqual(null);
});
it('currentUserData should return undefined', () => {
expect(service.currentUserData).toEqual(null);
});
it('currentUserType should return undefined', () => {
expect(service.currentUserType).toEqual(undefined);
});
it('userSignedIn should return false', () => {
expect(service.userSignedIn()).toEqual(false);
});
});
describe('user signed in', () => {
beforeEach(() => {
initService({});
});
it('currentAuthData should return current auth data', () => {
service.signIn(signInData).subscribe(
data => expect(service.currentAuthData).toEqual(authData)
);
const req = backend.expectOne({
url: 'auth/sign_in',
method: 'POST'
});
req.flush( userData, { headers: tokenHeaders } );
});
/*it('currentUserData should return current user data', () => {
service.signIn(signInData).subscribe(
data => expect(service.currentUserData).toEqual(userData)
);
const req = backend.expectOne({
url: 'auth/sign_in',
method: 'POST'
});
req.flush( userData, { headers: tokenHeaders } );
});*/
it('userSignedIn should true', () => {
service.signIn(signInData).subscribe(
data => expect(service.userSignedIn()).toEqual(true)
);
const req = backend.expectOne({
url: 'auth/sign_in',
method: 'POST'
});
req.flush( userData, { headers: tokenHeaders } );
});
});
}); | the_stack |
import i18next from "i18next";
import { computed } from "mobx";
import filterOutUndefined from "../../../Core/filterOutUndefined";
import isDefined from "../../../Core/isDefined";
import TerriaError, { networkRequestError } from "../../../Core/TerriaError";
import {
ShortReportTraits,
MetadataUrlTraits
} from "../../../Traits/TraitsClasses/CatalogMemberTraits";
import { DimensionOptionTraits } from "../../../Traits/TraitsClasses/DimensionTraits";
import { FeatureInfoTemplateTraits } from "../../../Traits/TraitsClasses/FeatureInfoTraits";
import LegendTraits from "../../../Traits/TraitsClasses/LegendTraits";
import SdmxCatalogItemTraits, {
SdmxDimensionTraits
} from "../../../Traits/TraitsClasses/SdmxCatalogItemTraits";
import {
ModelOverrideTraits,
ModelOverrideType
} from "../../../Traits/TraitsClasses/SdmxCommonTraits";
import TableChartStyleTraits, {
TableChartLineStyleTraits
} from "../../../Traits/TraitsClasses/TableChartStyleTraits";
import TableColorStyleTraits from "../../../Traits/TraitsClasses/TableColorStyleTraits";
import TableColumnTraits, {
ColumnTransformationTraits
} from "../../../Traits/TraitsClasses/TableColumnTraits";
import TableStyleTraits from "../../../Traits/TraitsClasses/TableStyleTraits";
import TableTimeStyleTraits from "../../../Traits/TraitsClasses/TableTimeStyleTraits";
import createCombinedModel from "../../Definition/createCombinedModel";
import createStratumInstance from "../../Definition/createStratumInstance";
import LoadableStratum from "../../Definition/LoadableStratum";
import Model, { BaseModel } from "../../Definition/Model";
import StratumFromTraits from "../../Definition/StratumFromTraits";
import StratumOrder from "../../Definition/StratumOrder";
import proxyCatalogItemUrl from "../proxyCatalogItemUrl";
import { MAX_SELECTABLE_DIMENSION_OPTIONS } from "../../SelectableDimensions";
import SdmxJsonCatalogItem from "./SdmxJsonCatalogItem";
import { loadSdmxJsonStructure, parseSdmxUrn } from "./SdmxJsonServerStratum";
import {
Attribute,
CodeLists,
ConceptSchemes,
ContentConstraints,
Dataflow,
DataStructure,
Dimension,
SdmxJsonStructureMessage
} from "./SdmxJsonStructureMessage";
export interface SdmxJsonDataflow {
/** metadata for dataflow (eg description) */
dataflow: Dataflow;
/** lists this dataflow's dimensions (including time), attributes, primary measure, ... */
dataStructure: DataStructure;
/** codelists describe dimension/attribute values (usually to make them human-readable) */
codelists?: CodeLists;
/** concept schemes: used to describe dimensions and attributes */
conceptSchemes?: ConceptSchemes;
/** contentConstraints: describe allowed values for enumeratted dimensions/attributes */
contentConstraints?: ContentConstraints;
}
export class SdmxJsonDataflowStratum extends LoadableStratum(
SdmxCatalogItemTraits
) {
static stratumName = "sdmxJsonDataflow";
duplicateLoadableStratum(model: BaseModel): this {
return new SdmxJsonDataflowStratum(
model as SdmxJsonCatalogItem,
this.sdmxJsonDataflow
) as this;
}
/**
* Load SDMX-JSON dataflow - will also load references (dataStructure, codelists, conceptSchemes, contentConstraints)
*/
static async load(
catalogItem: SdmxJsonCatalogItem
): Promise<SdmxJsonDataflowStratum> {
// Load dataflow (+ all related references)
let dataflowStructure: SdmxJsonStructureMessage = await loadSdmxJsonStructure(
proxyCatalogItemUrl(
catalogItem,
`${catalogItem.baseUrl}/dataflow/${catalogItem.agencyId}/${catalogItem.dataflowId}?references=all`
),
false
);
// Check response
if (!isDefined(dataflowStructure.data)) {
throw networkRequestError({
title: i18next.t("models.sdmxJsonDataflowStratum.loadDataErrorTitle"),
message: i18next.t(
"models.sdmxJsonDataflowStratum.loadDataErrorMessage.invalidResponse"
)
});
}
if (
!Array.isArray(dataflowStructure.data.dataflows) ||
dataflowStructure.data.dataflows.length === 0
) {
throw networkRequestError({
title: i18next.t("models.sdmxJsonDataflowStratum.loadDataErrorTitle"),
message: i18next.t(
"models.sdmxJsonDataflowStratum.loadDataErrorMessage.noDataflow",
this
)
});
}
if (
!Array.isArray(dataflowStructure.data.dataStructures) ||
dataflowStructure.data.dataStructures.length === 0
) {
throw networkRequestError({
title: i18next.t("models.sdmxJsonDataflowStratum.loadDataErrorTitle"),
message: i18next.t(
"models.sdmxJsonDataflowStratum.loadDataErrorMessage.noDatastructure",
this
)
});
}
return new SdmxJsonDataflowStratum(catalogItem, {
dataflow: dataflowStructure.data.dataflows[0],
dataStructure: dataflowStructure.data.dataStructures[0],
codelists: dataflowStructure.data.codelists,
conceptSchemes: dataflowStructure.data.conceptSchemes,
contentConstraints: dataflowStructure.data.contentConstraints
});
}
constructor(
private readonly catalogItem: SdmxJsonCatalogItem,
private readonly sdmxJsonDataflow: SdmxJsonDataflow
) {
super();
}
@computed
get description() {
return this.sdmxJsonDataflow.dataflow.description;
}
/** Transform dataflow annotations with type "EXT_RESOURCE"
* These can be of format:
* - ${title}|${url}|${imageUrl}
* - EG "Metadata|http://purl.org/spc/digilib/doc/7thdz|https://sdd.spc.int/themes/custom/sdd/images/icons/metadata.png"
*/
@computed get metadataUrls() {
return filterOutUndefined(
this.sdmxJsonDataflow?.dataflow.annotations
?.filter(a => a.type === "EXT_RESOURCE" && a.text)
.map(annotation => {
let text = annotation.texts?.[i18next.language] ?? annotation.text!;
const title = text.includes("|") ? text.split("|")[0] : undefined;
const url = text.includes("|") ? text.split("|")[1] : text;
return createStratumInstance(MetadataUrlTraits, { title, url });
}) ?? []
);
}
get sdmxAttributes() {
return (
this.sdmxJsonDataflow.dataStructure.dataStructureComponents?.attributeList
?.attributes ?? []
);
}
get sdmxDimensions() {
return (
this.sdmxJsonDataflow.dataStructure.dataStructureComponents?.dimensionList
?.dimensions ?? []
);
}
get sdmxTimeDimensions() {
return (
this.sdmxJsonDataflow.dataStructure.dataStructureComponents?.dimensionList
.timeDimensions ?? []
);
}
get sdmxPrimaryMeasure() {
return this.sdmxJsonDataflow.dataStructure.dataStructureComponents
?.measureList.primaryMeasure;
}
/**
* If we get a dataflow with a single value (and not region-mapped), show the exact value in a short report
*/
@computed
get shortReportSections() {
if (this.catalogItem.mapItems.length !== 0 || this.catalogItem.isLoading)
return;
const primaryCol = this.catalogItem.tableColumns.find(
col => col.name === this.primaryMeasureColumn?.name
);
if (
primaryCol?.valuesAsNumbers.values.length === 1 &&
typeof primaryCol?.valuesAsNumbers.values[0] === "number"
) {
return [
createStratumInstance(ShortReportTraits, {
name: this.chartTitle,
content: primaryCol?.valuesAsNumbers.values[0].toLocaleString(
undefined,
primaryCol.traits.format
)
})
];
}
}
// ------------- START SDMX TRAITS STRATUM -------------
/** Merge codelist and concept model overrides (codelist takes priority) */
getMergedModelOverride(
dim: Attribute | Dimension
): Model<ModelOverrideTraits> | undefined {
const conceptOverride = this.catalogItem.modelOverrides.find(
concept => concept.id === dim.conceptIdentity
);
const codelistOverride = this.catalogItem.modelOverrides.find(
codelist => codelist.id === dim.localRepresentation?.enumeration
);
let modelOverride = conceptOverride;
if (!modelOverride) {
modelOverride = codelistOverride;
// If there is a codelist and concept override, merge them
} else if (codelistOverride) {
modelOverride = createCombinedModel(codelistOverride, modelOverride);
}
return modelOverride;
}
/**
* This maps SDMX-JSON dataflow structure to `SdmxDimensionTraits` (which gets turned into `SelectableDimensions`) - it uses:
* - Data structure's dimensions (filtered to only include "enumerated" dimensions)
* - Content constraints to find dimension options
* - Codelists to add human readable labels to dimension options
*
* It will also apply ModelOverrides - which are used to override dimension values based on concept/codelist ID.
* - @see ModelOverrideTraits
*/
@computed
get dimensions(): StratumFromTraits<SdmxDimensionTraits>[] | undefined {
// Contraint contains allowed dimension values for a given dataflow
// Get 'actual' constraints (rather than 'allowed' constraints)
const constraints = this.sdmxJsonDataflow.contentConstraints?.filter(
c => c.type === "Actual"
);
return (
this.sdmxDimensions
// Filter normal enum dimensions
.filter(
dim =>
dim.id &&
dim.type === "Dimension" &&
dim.localRepresentation?.enumeration
)
.map(dim => {
const modelOverride = this.getMergedModelOverride(dim);
// Concept maps dimension's ID to a human-readable name
const concept = this.getConceptByUrn(dim.conceptIdentity);
// Codelist maps dimension enum values to human-readable labels
const codelist = this.getCodelistByUrn(
dim.localRepresentation?.enumeration
);
// Get allowed options from constraints.cubeRegions (there may be multiple - take union of all values)
const allowedOptionIds = Array.isArray(constraints)
? constraints.reduce<Set<string>>((keys, constraint) => {
constraint.cubeRegions?.forEach(cubeRegion =>
cubeRegion.keyValues
?.filter(kv => kv.id === dim.id)
?.forEach(regionKey =>
regionKey.values?.forEach(value => keys.add(value))
)
);
return keys;
}, new Set())
: new Set();
let options: StratumFromTraits<DimensionOptionTraits>[] = [];
// Only create options if less then MAX_SELECTABLE_DIMENSION_OPTIONS (1000) values
if (allowedOptionIds.size < MAX_SELECTABLE_DIMENSION_OPTIONS) {
// Get codes by merging allowedOptionIds with codelist
let filteredCodesList =
(allowedOptionIds.size > 0
? codelist?.codes?.filter(code =>
allowedOptionIds.has(code.id!)
)
: // If no allowedOptions were found -> return all codes
codelist?.codes) ?? [];
// Create options object
// If modelOverride `options` has been defined -> use it
// Other wise use filteredCodesList
const overrideOptions = modelOverride?.options;
options =
isDefined(overrideOptions) && overrideOptions.length > 0
? overrideOptions.map(option => {
return {
id: option.id,
name: option.name,
value: undefined
};
})
: filteredCodesList.map(code => {
return { id: code.id!, name: code.name, value: undefined };
});
}
// Use first option as default if no other default is provided
let selectedId: string | undefined =
modelOverride?.allowUndefined ||
allowedOptionIds.size >= MAX_SELECTABLE_DIMENSION_OPTIONS
? undefined
: options[0]?.id;
// Override selectedId if it a valid option
const selectedIdOverride = modelOverride?.selectedId;
if (
isDefined(selectedIdOverride) &&
options.find(option => option.id === selectedIdOverride)
) {
selectedId = selectedIdOverride;
}
return {
id: dim.id!,
name: modelOverride?.name ?? concept?.name,
options: options,
position: dim.position,
disable: modelOverride?.disable,
allowUndefined: modelOverride?.allowUndefined,
selectedId: selectedId
};
})
.filter(isDefined)
);
}
/**
* Adds SDMX Common concepts as model overrides:
* - `UNIT_MEASURE` (see `this.unitMeasure`)
* - `UNIT_MULT` (see `this.primaryMeasureColumn`)
* - `FREQ` (see `this.unitMeasure`)
*/
@computed
get modelOverrides() {
return filterOutUndefined(
// Map through all dimensions and attributes to find ones which use common concepts
[...this.sdmxDimensions, ...this.sdmxAttributes].map(dimAttr => {
const conceptUrn = parseSdmxUrn(dimAttr.conceptIdentity);
// Add UNIT_MEASURE common concept override for unit-measure
if (conceptUrn?.descendantIds?.[0] === "UNIT_MEASURE") {
return createStratumInstance(ModelOverrideTraits, {
id: dimAttr.conceptIdentity,
type: "unit-measure"
});
// Add UNIT_MULT common concept override for unit-multiplier
} else if (conceptUrn?.descendantIds?.[0] === "UNIT_MULT") {
return createStratumInstance(ModelOverrideTraits, {
id: dimAttr.conceptIdentity,
type: "unit-multiplier"
});
// Add FREQUENCY common concept override for frequency
} else if (conceptUrn?.descendantIds?.[0] === "FREQ") {
return createStratumInstance(ModelOverrideTraits, {
id: dimAttr.conceptIdentity,
type: "frequency"
});
}
})
);
}
/**
* Get unitMeasure string using modelOverrides.
* - Search for columns linked to dimensions/attributes which have modelOverrides of type "unit-measure"
* - We will only use a column if it has a single unique value - as this unitMeasure it used effectively as "units" for the dataset
* - Also search for dimensions which have modelOverrides of type "frequency".
* - These will be used to add the frequency to the end of the unitMeasure string
* For example: "Value (Yearly)" or "AUD (Quaterly)"
*
*/
@computed
get unitMeasure(): string | undefined {
// Find tableColumns which have corresponding modelOverride with type `unit-measure`
// We will only use columns if they have a single unique value
const unitMeasure = filterOutUndefined(
this.catalogItem.modelOverrides
?.filter(override => override.type === "unit-measure" && override.id)
.map(override => {
// Find dimension/attribute id with concept or codelist override
let dimOrAttr =
this.getAttributionWithConceptOrCodelist(override.id!) ??
this.getDimensionWithConceptOrCodelist(override.id!);
const column = dimOrAttr?.id
? this.catalogItem.findColumnByName(dimOrAttr.id)
: undefined;
if (column?.uniqueValues.values.length === 1) {
// If this column has a codelist, use it to format the value
const codelist = this.getCodelistByUrn(
dimOrAttr?.localRepresentation?.enumeration
);
const value = column?.uniqueValues.values[0];
return codelist?.codes?.find(c => c.id === value)?.name ?? value;
}
})
).join(", ");
// Find frequency from dimensions with modelOverrides of type "frequency".
const frequencyDim = this.getDimensionsWithOverrideType(
"frequency"
).find(dim => isDefined(dim.selectedId));
// Try to get option label if it exists
let frequency =
frequencyDim?.options.find(o => o.id === frequencyDim.selectedId)?.name ??
frequencyDim?.id;
return `${unitMeasure ||
i18next.t("models.sdmxJsonDataflowStratum.defaultUnitMeasure")}${
frequency ? ` (${frequency})` : ""
}`;
}
// ------------- START TABLE TRAITS STRATUM -------------
/**
* Add TableColumnTraits for primary measure column - this column contains observational values to be visualised on chart or map:
* - `name` to dimension id
* - `title` to concept name
* - `transformation` if unit multiplier attribute has been found (which will apply `x*(10^unitMultiplier)` to all observation vlues)
*/
@computed
get primaryMeasureColumn(): StratumFromTraits<TableColumnTraits> | undefined {
if (!this.sdmxPrimaryMeasure) return;
const primaryMeasureConcept = this.getConceptByUrn(
this.sdmxPrimaryMeasure?.conceptIdentity
);
// Find unit multipler columns by searching for attributes/dimensions which have modelOverrides of type "unit-multiplier".
// Use the first column found
const unitMultiplier = filterOutUndefined(
this.catalogItem.modelOverrides
?.filter(override => override.type === "unit-multiplier" && override.id)
.map(override => {
// Find dimension/attribute id with concept or codelist
let dimOrAttr =
this.getAttributionWithConceptOrCodelist(override.id!) ??
this.getDimensionWithConceptOrCodelist(override.id!);
return dimOrAttr?.id;
})
)[0];
return createStratumInstance(TableColumnTraits, {
name: this.sdmxPrimaryMeasure?.id,
title: primaryMeasureConcept?.name,
type: "scalar",
// If a unitMultiplier was found, we add `x*(10^unitMultiplier)` transformation
transformation: unitMultiplier
? createStratumInstance(ColumnTransformationTraits, {
expression: `x*(10^${unitMultiplier})`,
dependencies: [unitMultiplier]
})
: undefined
});
}
/**
* Add TableColumnTraits for dimensions
* The main purpose of this is to try to find the region type for columns.
* It also adds:
* - `name` as dimension id
* - `title` as concept name (more human-readable than dimension id)
* - `type` to `region` if a valid region-type is found, or `hidden` if the dimension is disabled
*/
@computed
get dimensionColumns(): StratumFromTraits<TableColumnTraits>[] {
// Get columns for all dimensions (excluding time dimensions)
return (
this.sdmxDimensions
.filter(dim => isDefined(dim.id))
.map(dim => {
// Hide dimension columns if they are disabled
if (this.dimensions?.find(d => d.id === dim.id)?.disable) {
return createStratumInstance(TableColumnTraits, {
name: dim.id,
type: "hidden"
});
}
// Get concept for the current dimension
const concept = this.getConceptByUrn(dim.conceptIdentity);
// Get codelist for current dimension
const codelist = this.getCodelistByUrn(
dim.localRepresentation?.enumeration
);
const modelOverride = this.getMergedModelOverride(dim);
// Try to find region type
let regionType: string | undefined;
// Are any regionTypes present in modelOverride
regionType = this.catalogItem.matchRegionType(
modelOverride?.regionType
);
// Next try fetching reigon type from another dimension (only if this modelOverride type 'region')
// It will look through dimensions which have modelOverrides of type `region-type` and have a selectedId, if one is found - it will be used as the regionType of this column
// Note this will override previous regionType
if (modelOverride?.type === "region") {
// Use selectedId of first dimension with one
regionType = this.catalogItem.matchRegionType(
this.getDimensionsWithOverrideType("region-type").find(d =>
isDefined(d.selectedId)
)?.selectedId ?? regionType
);
}
// Try to find valid region type from:
// - dimension ID
// - codelist name
// - codelist ID
// - concept name?
// - concept id (the string, not the full URN)
if (!isDefined(regionType))
regionType =
this.catalogItem.matchRegionType(dim.id) ??
this.catalogItem.matchRegionType(codelist?.name) ??
this.catalogItem.matchRegionType(codelist?.id) ??
this.catalogItem.matchRegionType(concept?.name) ??
this.catalogItem.matchRegionType(concept?.id);
// Apply regionTypeReplacements (which can replace regionType with a different regionType - using [{find:string, replace:string}] pattern)
if (modelOverride?.type === "region") {
const replacement = modelOverride?.regionTypeReplacements?.find(
r => r.find === regionType
)?.replace;
if (isDefined(replacement)) {
regionType = replacement;
}
}
return createStratumInstance(TableColumnTraits, {
name: dim.id,
title: concept?.name,
// We set columnType to hidden for all columns except for region columns - as we are never interested in visualising them
// For "time" columns see `get timeColumns()`
// For primary measure ("scalar") column - see `get primaryMeasureColumn()`
type: isDefined(regionType) ? "region" : "hidden",
regionType
});
}) ?? []
);
}
/**
* Add traits for time columns:
* - `name` to dimension id
* - `type = time`
* - `title` to concept name (if it exists)
*/
@computed
get timeColumns(): StratumFromTraits<TableColumnTraits>[] {
return (
this.sdmxTimeDimensions.map(dim => {
const concept = this.getConceptByUrn(dim.conceptIdentity);
return createStratumInstance(TableColumnTraits, {
name: dim.id,
title: concept?.name ?? dim.id,
type: "time"
});
}) ?? []
);
}
/**
* Add traits for attribute columns - all attribute columns are hidden, they are used to describe the primary measure (in feature info, unit measure, unit multiplier...):
* - `name` to attribute id
* - `type = hidden`
*/
@computed
get attributeColumns(): StratumFromTraits<TableColumnTraits>[] {
return (
this.sdmxAttributes.map(attr => {
return createStratumInstance(TableColumnTraits, {
name: attr.id,
type: "hidden"
});
}) ?? []
);
}
/**
* Munge all columns together
*/
@computed
get columns() {
return filterOutUndefined([
this.primaryMeasureColumn,
...this.dimensionColumns,
...this.timeColumns,
...this.attributeColumns
]);
}
/** Get region TableColumn by searching catalogItem.tableColumns for region dimension
* NOTE: this is searching through catalogItem.tableColumns to find the completely resolved regionColumn
* This can only be used in computeds/fns outside of ColumnTraits - or you will get infinite recursion
*/
@computed get resolvedRegionColumn() {
return this.catalogItem.tableColumns.find(
tableCol =>
tableCol.name ===
this.dimensionColumns.find(dimCol => dimCol.type === "region")?.name
);
}
/** If we only have a single region (or no regions)
* We want to:
* - disable the region column so we get a chart instead - see `get styles()`
* - get region name for chart title (if single region) - see `get chartTitle()`
**/
@computed get disableRegion() {
return (
!this.catalogItem.isLoading &&
this.resolvedRegionColumn?.ready &&
(this.resolvedRegionColumn?.valuesAsRegions.uniqueRegionIds.length ??
0) <= 1
);
}
/** Get nice title to use for chart
* If we have a region column with a single region, it will append the region name to the title
*/
@computed get chartTitle() {
if (this.disableRegion) {
const regionValues = this.resolvedRegionColumn?.uniqueValues.values;
if (regionValues && regionValues.length === 1) {
// Get region dimension ID
const regionDimensionId = this.getDimensionsWithOverrideType(
"region"
)[0]?.id;
// Lookup in sdmxDimensions to get codelist (this is needed because region dimensions which have more options than MAX_SELECTABLE_DIMENSION_OPTIONS will not return any dimension.options)
const regionDimension = this.sdmxDimensions.find(
dim => dim.id === regionDimensionId
);
if (regionDimension) {
// Try to get human readable region name from codelist
const codelist = this.getCodelistByUrn(
regionDimension.localRepresentation?.enumeration
);
const regionName =
codelist?.codes?.find(c => c.id === regionValues[0])?.name ??
regionValues[0];
return `${regionName} - ${this.unitMeasure}`;
}
}
}
return this.unitMeasure;
}
/**
* Set TableStyleTraits for primary measure column:
* - Legend title is set to `unitMeasure` to add context - eg "AUD (Quaterly)"
* - Chart traits are set if this dataflow is time-series with no region-mapping:
* - `xAxisColumn` to time column name
* - `lines.name` set to `unitMeasure`
* - `lines.yAxisColumn` set to primary measure column
* - `regionColumn` set to region dimension name (if one exists)
*/
@computed
get styles() {
if (this.primaryMeasureColumn) {
return [
createStratumInstance(TableStyleTraits, {
id: this.primaryMeasureColumn.name,
color: createStratumInstance(TableColorStyleTraits, {
legend: createStratumInstance(LegendTraits, {
title: this.unitMeasure
}),
/** Enable z-score filtering (see TableColorStyleTraits.zScoreFilter) */
zScoreFilter: 4
}),
time: createStratumInstance(TableTimeStyleTraits, {
timeColumn: this.timeColumns[0].name,
spreadStartTime: true,
spreadFinishTime: true
}),
// Add chart if there is a time column but no region column
chart:
this.timeColumns.length > 0 &&
(this.disableRegion || !this.resolvedRegionColumn)
? createStratumInstance(TableChartStyleTraits, {
xAxisColumn: this.timeColumns[0].name,
lines: [
createStratumInstance(TableChartLineStyleTraits, {
name: this.chartTitle,
yAxisColumn: this.primaryMeasureColumn.name
})
]
})
: undefined,
regionColumn: this.disableRegion
? null
: this.resolvedRegionColumn?.name
})
];
}
return [];
}
/**
* Set active table style to primary measure column
*/
@computed
get activeStyle() {
return this.primaryMeasureColumn?.name;
}
/**
* Set default time to last time of dataset
*/
@computed
get initialTimeSource() {
return "stop";
}
/**
* Formats feature info table to add:
* - Current time (if time-series)
* - Selected region (if region-mapped)
* - All dimension values
* - Formatted primary measure (the actual value)
* - Time-series chart
*/
@computed
get featureInfoTemplate() {
const regionType = this.resolvedRegionColumn?.regionType;
if (!regionType) return;
let template = '<table class="cesium-infoBox-defaultTable">';
// Function to format row with title and value
const row = (title: string, value: string) =>
`<tr><td style="vertical-align: middle">${title}</td><td>${value}</td></tr>`;
// Get time dimension values
template += this.timeColumns
?.map(col => row(col.title ?? "Time", `{{${col.name}}}`))
.join(", ");
// Get region dimension values
template += row(regionType?.description, `{{${regionType?.nameProp}}}`);
// Get other dimension values
template += this.catalogItem.sdmxSelectableDimensions
?.filter(d => (d.name || d.id) && !d.disable && d.selectedId)
.map(d => {
const selectedOption = d.options?.find(o => o.id === d.selectedId);
return row((d.name || d.id)!, selectedOption?.name ?? d.selectedId!);
})
.join("");
const primaryMeasureName =
this.unitMeasure ??
this.primaryMeasureColumn?.title ??
this.primaryMeasureColumn?.name ??
"Value";
template +=
row("", "") +
row(
primaryMeasureName,
`{{#terria.formatNumber}}{useGrouping: true}{{${this.primaryMeasureColumn?.name}}}{{/terria.formatNumber}}`
);
// Add timeSeries chart if more than one time observation
if (
this.catalogItem.discreteTimes &&
this.catalogItem.discreteTimes.length > 1
) {
const chartName = `${this.catalogItem.name}: {{${regionType.nameProp}}}`;
template += `</table>{{#terria.timeSeries.data}}<chart title="${chartName}" x-column="{{terria.timeSeries.xName}}" y-column="${this.unitMeasure}" >{{terria.timeSeries.data}}</chart>{{/terria.timeSeries.data}}`;
}
return createStratumInstance(FeatureInfoTemplateTraits, { template });
}
// ------------- START SDMX STRUCTURE HELPER FUNCTIONS -------------
getConceptScheme(id: string) {
if (!isDefined(id)) return;
return this.sdmxJsonDataflow.conceptSchemes?.find(c => c.id === id);
}
getConceptByUrn(urn?: string) {
if (!urn) return;
const conceptUrn = parseSdmxUrn(urn);
const conceptSchemeId = conceptUrn?.resourceId;
const conceptId = conceptUrn?.descendantIds?.[0];
if (!isDefined(conceptId)) return;
let resolvedConceptScheme =
typeof conceptSchemeId === "string"
? this.getConceptScheme(conceptSchemeId)
: conceptSchemeId;
return resolvedConceptScheme?.concepts?.find(d => d.id === conceptId);
}
getCodelistByUrn(urn?: string) {
if (!urn) return;
const codelistUrn = parseSdmxUrn(urn);
const id = codelistUrn?.resourceId;
if (!isDefined(id)) return;
return this.sdmxJsonDataflow.codelists?.find(c => c.id === id);
}
/**
* Find modelOverrides with type 'region-type' to try to extract regionType from another dimension
* For example, ABS have a regionType dimension which may have values (SA1, SA2, ...), which could be used to determine regionType
*/
getDimensionsWithOverrideType(type: ModelOverrideType) {
return filterOutUndefined(
this.catalogItem.modelOverrides
?.filter(override => override.type === type && override.id)
.map(override => {
// Find dimension id with concept or codelist
return this.catalogItem.dimensions?.find(
d =>
d.id === this.getDimensionWithConceptOrCodelist(override.id!)?.id
);
})
);
}
getDimensionWithConceptOrCodelist(id: string) {
return this.sdmxDimensions.find(
dim =>
dim.conceptIdentity === id ||
dim.localRepresentation?.enumeration === id
);
}
getAttributionWithConceptOrCodelist(id: string) {
return this.sdmxAttributes.find(
attr =>
attr.conceptIdentity === id ||
attr.localRepresentation?.enumeration === id
);
}
}
StratumOrder.addLoadStratum(SdmxJsonDataflowStratum.stratumName); | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as NetworkForward from '../../panels/network/forward/forward.js';
import * as UI from '../../ui/legacy/legacy.js';
import * as NetworkComponents from './components/components.js';
import {EventSourceMessagesView} from './EventSourceMessagesView.js';
import type {NetworkTimeCalculator} from './NetworkTimeCalculator.js';
import {RequestCookiesView} from './RequestCookiesView.js';
import {RequestHeadersView} from './RequestHeadersView.js';
import {RequestPayloadView} from './RequestPayloadView.js';
import {RequestInitiatorView} from './RequestInitiatorView.js';
import {RequestPreviewView} from './RequestPreviewView.js';
import {RequestResponseView} from './RequestResponseView.js';
import {RequestTimingView} from './RequestTimingView.js';
import {ResourceWebSocketFrameView} from './ResourceWebSocketFrameView.js';
const UIStrings = {
/**
*@description Text for network request headers
*/
headers: 'Headers',
/**
*@description Text in Network Item View of the Network panel
*/
payload: 'Payload',
/**
*@description Text in Network Item View of the Network panel
*/
messages: 'Messages',
/**
*@description Text in Network Item View of the Network panel
*/
websocketMessages: 'WebSocket messages',
/**
*@description Text in Network Item View of the Network panel
*/
eventstream: 'EventStream',
/**
*@description Text for previewing items
*/
preview: 'Preview',
/**
*@description Text in Network Item View of the Network panel
*/
responsePreview: 'Response preview',
/**
*@description Icon title in Network Item View of the Network panel
*/
signedexchangeError: 'SignedExchange error',
/**
*@description Title of a tab in the Network panel. A Network response refers to the act of acknowledging a
network request. Should not be confused with answer.
*/
response: 'Response',
/**
*@description Text in Network Item View of the Network panel
*/
rawResponseData: 'Raw response data',
/**
*@description Text for the initiator of something
*/
initiator: 'Initiator',
/**
* @description Tooltip for initiator view in Network panel. An initiator is a piece of code/entity
* in the code that initiated/started the network request, i.e. caused the network request. The 'call
* stack' is the location in the code where the initiation happened.
*/
requestInitiatorCallStack: 'Request initiator call stack',
/**
*@description Title of a tab in Network Item View of the Network panel.
*The tab displays the duration breakdown of a network request.
*/
timing: 'Timing',
/**
*@description Text in Network Item View of the Network panel
*/
requestAndResponseTimeline: 'Request and response timeline',
/**
*@description Label of a tab in the network panel
*/
trustTokens: 'Trust Tokens',
/**
*@description Title of the Trust token tab in the Network panel
*/
trustTokenOperationDetails: 'Trust Token operation details',
/**
*@description Text for web cookies
*/
cookies: 'Cookies',
/**
*@description Text in Network Item View of the Network panel
*/
requestAndResponseCookies: 'Request and response cookies',
};
const str_ = i18n.i18n.registerUIStrings('panels/network/NetworkItemView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class NetworkItemView extends UI.TabbedPane.TabbedPane {
private requestInternal: SDK.NetworkRequest.NetworkRequest;
private readonly resourceViewTabSetting: Common.Settings.Setting<NetworkForward.UIRequestLocation.UIRequestTabs>;
private readonly headersView: RequestHeadersView;
private payloadView: RequestPayloadView|null;
private readonly responseView: RequestResponseView|undefined;
private cookiesView: RequestCookiesView|null;
private initialTab?: NetworkForward.UIRequestLocation.UIRequestTabs;
constructor(
request: SDK.NetworkRequest.NetworkRequest, calculator: NetworkTimeCalculator,
initialTab?: NetworkForward.UIRequestLocation.UIRequestTabs) {
super();
this.requestInternal = request;
this.element.classList.add('network-item-view');
this.resourceViewTabSetting = Common.Settings.Settings.instance().createSetting(
'resourceViewTab', NetworkForward.UIRequestLocation.UIRequestTabs.Preview);
this.headersView = new RequestHeadersView(request);
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Headers, i18nString(UIStrings.headers), this.headersView,
i18nString(UIStrings.headers));
this.payloadView = null;
this.maybeAppendPayloadPanel();
this.addEventListener(UI.TabbedPane.Events.TabSelected, this.tabSelected, this);
if (request.resourceType() === Common.ResourceType.resourceTypes.WebSocket) {
const frameView = new ResourceWebSocketFrameView(request);
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.WsFrames, i18nString(UIStrings.messages), frameView,
i18nString(UIStrings.websocketMessages));
} else if (request.mimeType === SDK.NetworkRequest.MIME_TYPE.EVENTSTREAM) {
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.EventSource, i18nString(UIStrings.eventstream),
new EventSourceMessagesView(request));
} else {
this.responseView = new RequestResponseView(request);
const previewView = new RequestPreviewView(request);
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Preview, i18nString(UIStrings.preview), previewView,
i18nString(UIStrings.responsePreview));
const signedExchangeInfo = request.signedExchangeInfo();
if (signedExchangeInfo && signedExchangeInfo.errors && signedExchangeInfo.errors.length) {
const icon = UI.Icon.Icon.create('smallicon-error');
UI.Tooltip.Tooltip.install(icon, i18nString(UIStrings.signedexchangeError));
this.setTabIcon(NetworkForward.UIRequestLocation.UIRequestTabs.Preview, icon);
}
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Response, i18nString(UIStrings.response), this.responseView,
i18nString(UIStrings.rawResponseData));
}
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Initiator, i18nString(UIStrings.initiator),
new RequestInitiatorView(request), i18nString(UIStrings.requestInitiatorCallStack));
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Timing, i18nString(UIStrings.timing),
new RequestTimingView(request, calculator), i18nString(UIStrings.requestAndResponseTimeline));
if (request.trustTokenParams()) {
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.TrustTokens, i18nString(UIStrings.trustTokens),
new NetworkComponents.RequestTrustTokensView.RequestTrustTokensView(request),
i18nString(UIStrings.trustTokenOperationDetails));
}
this.cookiesView = null;
this.initialTab = initialTab || this.resourceViewTabSetting.get();
// Selecting tabs should not be handled by the super class.
this.setAutoSelectFirstItemOnShow(false);
}
wasShown(): void {
super.wasShown();
this.requestInternal.addEventListener(
SDK.NetworkRequest.Events.RequestHeadersChanged, this.requestHeadersChanged, this);
this.requestInternal.addEventListener(
SDK.NetworkRequest.Events.ResponseHeadersChanged, this.maybeAppendCookiesPanel, this);
this.requestInternal.addEventListener(
SDK.NetworkRequest.Events.TrustTokenResultAdded, this.maybeShowErrorIconInTrustTokenTabHeader, this);
this.maybeAppendCookiesPanel();
this.maybeShowErrorIconInTrustTokenTabHeader();
// Only select the initial tab the first time the view is shown after construction.
// When the view is re-shown (without re-constructing) users or revealers might have changed
// the selected tab in the mean time. Show the previously selected tab in that
// case instead, by simply doing nohting.
if (this.initialTab) {
this.selectTabInternal(this.initialTab);
this.initialTab = undefined;
}
}
willHide(): void {
this.requestInternal.removeEventListener(
SDK.NetworkRequest.Events.RequestHeadersChanged, this.requestHeadersChanged, this);
this.requestInternal.removeEventListener(
SDK.NetworkRequest.Events.ResponseHeadersChanged, this.maybeAppendCookiesPanel, this);
this.requestInternal.removeEventListener(
SDK.NetworkRequest.Events.TrustTokenResultAdded, this.maybeShowErrorIconInTrustTokenTabHeader, this);
}
private async requestHeadersChanged(): Promise<void> {
this.maybeAppendCookiesPanel();
this.maybeAppendPayloadPanel();
}
private maybeAppendCookiesPanel(): void {
const cookiesPresent = this.requestInternal.hasRequestCookies() || this.requestInternal.responseCookies.length > 0;
console.assert(cookiesPresent || !this.cookiesView, 'Cookies were introduced in headers and then removed!');
if (cookiesPresent && !this.cookiesView) {
this.cookiesView = new RequestCookiesView(this.requestInternal);
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Cookies, i18nString(UIStrings.cookies), this.cookiesView,
i18nString(UIStrings.requestAndResponseCookies));
}
}
private async maybeAppendPayloadPanel(): Promise<void> {
if (this.requestInternal.queryParameters || await this.requestInternal.requestFormData()) {
this.payloadView = new RequestPayloadView(this.requestInternal);
this.appendTab(
NetworkForward.UIRequestLocation.UIRequestTabs.Payload, i18nString(UIStrings.payload), this.payloadView,
i18nString(UIStrings.payload), /* userGesture=*/ void 0,
/* isCloseable=*/ void 0, /* isPreviewFeature=*/ void 0, /* index=*/ 1);
}
}
private maybeShowErrorIconInTrustTokenTabHeader(): void {
const trustTokenResult = this.requestInternal.trustTokenOperationDoneEvent();
if (trustTokenResult &&
!NetworkComponents.RequestTrustTokensView.statusConsideredSuccess(trustTokenResult.status)) {
this.setTabIcon(
NetworkForward.UIRequestLocation.UIRequestTabs.TrustTokens, UI.Icon.Icon.create('smallicon-error'));
}
}
private selectTabInternal(tabId: string): void {
if (!this.selectTab(tabId)) {
this.selectTab('headers');
}
}
private tabSelected(event: Common.EventTarget.EventTargetEvent<UI.TabbedPane.EventData>): void {
if (!event.data.isUserGesture) {
return;
}
this.resourceViewTabSetting.set(event.data.tabId as NetworkForward.UIRequestLocation.UIRequestTabs);
}
request(): SDK.NetworkRequest.NetworkRequest {
return this.requestInternal;
}
async revealResponseBody(line?: number): Promise<void> {
this.selectTabInternal(NetworkForward.UIRequestLocation.UIRequestTabs.Response);
if (this.responseView && typeof line === 'number') {
await this.responseView.revealLine((line as number));
}
}
revealHeader(section: NetworkForward.UIRequestLocation.UIHeaderSection, header: string|undefined): void {
this.selectTabInternal(NetworkForward.UIRequestLocation.UIRequestTabs.Headers);
this.headersView.revealHeader(section, header);
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/virtualMachineImagesMappers";
import * as Parameters from "../models/parameters";
import { ComputeManagementClientContext } from "../computeManagementClientContext";
/** Class representing a VirtualMachineImages. */
export class VirtualMachineImages {
private readonly client: ComputeManagementClientContext;
/**
* Create a VirtualMachineImages.
* @param {ComputeManagementClientContext} client Reference to the service client.
*/
constructor(client: ComputeManagementClientContext) {
this.client = client;
}
/**
* Gets a virtual machine image.
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param version A valid image SKU version.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachineImagesGetResponse>
*/
get(location: string, publisherName: string, offer: string, skus: string, version: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachineImagesGetResponse>;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param version A valid image SKU version.
* @param callback The callback
*/
get(location: string, publisherName: string, offer: string, skus: string, version: string, callback: msRest.ServiceCallback<Models.VirtualMachineImage>): void;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param version A valid image SKU version.
* @param options The optional parameters
* @param callback The callback
*/
get(location: string, publisherName: string, offer: string, skus: string, version: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineImage>): void;
get(location: string, publisherName: string, offer: string, skus: string, version: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineImage>, callback?: msRest.ServiceCallback<Models.VirtualMachineImage>): Promise<Models.VirtualMachineImagesGetResponse> {
return this.client.sendOperationRequest(
{
location,
publisherName,
offer,
skus,
version,
options
},
getOperationSpec,
callback) as Promise<Models.VirtualMachineImagesGetResponse>;
}
/**
* Gets a list of all virtual machine image versions for the specified location, publisher, offer,
* and SKU.
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachineImagesListResponse>
*/
list(location: string, publisherName: string, offer: string, skus: string, options?: Models.VirtualMachineImagesListOptionalParams): Promise<Models.VirtualMachineImagesListResponse>;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param callback The callback
*/
list(location: string, publisherName: string, offer: string, skus: string, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param skus A valid image SKU.
* @param options The optional parameters
* @param callback The callback
*/
list(location: string, publisherName: string, offer: string, skus: string, options: Models.VirtualMachineImagesListOptionalParams, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
list(location: string, publisherName: string, offer: string, skus: string, options?: Models.VirtualMachineImagesListOptionalParams | msRest.ServiceCallback<Models.VirtualMachineImageResource[]>, callback?: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): Promise<Models.VirtualMachineImagesListResponse> {
return this.client.sendOperationRequest(
{
location,
publisherName,
offer,
skus,
options
},
listOperationSpec,
callback) as Promise<Models.VirtualMachineImagesListResponse>;
}
/**
* Gets a list of virtual machine image offers for the specified location and publisher.
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachineImagesListOffersResponse>
*/
listOffers(location: string, publisherName: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachineImagesListOffersResponse>;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param callback The callback
*/
listOffers(location: string, publisherName: string, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param options The optional parameters
* @param callback The callback
*/
listOffers(location: string, publisherName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
listOffers(location: string, publisherName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineImageResource[]>, callback?: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): Promise<Models.VirtualMachineImagesListOffersResponse> {
return this.client.sendOperationRequest(
{
location,
publisherName,
options
},
listOffersOperationSpec,
callback) as Promise<Models.VirtualMachineImagesListOffersResponse>;
}
/**
* Gets a list of virtual machine image publishers for the specified Azure location.
* @param location The name of a supported Azure region.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachineImagesListPublishersResponse>
*/
listPublishers(location: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachineImagesListPublishersResponse>;
/**
* @param location The name of a supported Azure region.
* @param callback The callback
*/
listPublishers(location: string, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
/**
* @param location The name of a supported Azure region.
* @param options The optional parameters
* @param callback The callback
*/
listPublishers(location: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
listPublishers(location: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineImageResource[]>, callback?: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): Promise<Models.VirtualMachineImagesListPublishersResponse> {
return this.client.sendOperationRequest(
{
location,
options
},
listPublishersOperationSpec,
callback) as Promise<Models.VirtualMachineImagesListPublishersResponse>;
}
/**
* Gets a list of virtual machine image SKUs for the specified location, publisher, and offer.
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param [options] The optional parameters
* @returns Promise<Models.VirtualMachineImagesListSkusResponse>
*/
listSkus(location: string, publisherName: string, offer: string, options?: msRest.RequestOptionsBase): Promise<Models.VirtualMachineImagesListSkusResponse>;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param callback The callback
*/
listSkus(location: string, publisherName: string, offer: string, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
/**
* @param location The name of a supported Azure region.
* @param publisherName A valid image publisher.
* @param offer A valid image publisher offer.
* @param options The optional parameters
* @param callback The callback
*/
listSkus(location: string, publisherName: string, offer: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): void;
listSkus(location: string, publisherName: string, offer: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.VirtualMachineImageResource[]>, callback?: msRest.ServiceCallback<Models.VirtualMachineImageResource[]>): Promise<Models.VirtualMachineImagesListSkusResponse> {
return this.client.sendOperationRequest(
{
location,
publisherName,
offer,
options
},
listSkusOperationSpec,
callback) as Promise<Models.VirtualMachineImagesListSkusResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions/{version}",
urlParameters: [
Parameters.location0,
Parameters.publisherName,
Parameters.offer,
Parameters.skus,
Parameters.version,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.VirtualMachineImage
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus/{skus}/versions",
urlParameters: [
Parameters.location0,
Parameters.publisherName,
Parameters.offer,
Parameters.skus,
Parameters.subscriptionId
],
queryParameters: [
Parameters.filter,
Parameters.top,
Parameters.orderby,
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VirtualMachineImageResource"
}
}
}
}
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOffersOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers",
urlParameters: [
Parameters.location0,
Parameters.publisherName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VirtualMachineImageResource"
}
}
}
}
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listPublishersOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers",
urlParameters: [
Parameters.location0,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VirtualMachineImageResource"
}
}
}
}
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listSkusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/publishers/{publisherName}/artifacttypes/vmimage/offers/{offer}/skus",
urlParameters: [
Parameters.location0,
Parameters.publisherName,
Parameters.offer,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: {
serializedName: "parsedResponse",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "VirtualMachineImageResource"
}
}
}
}
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import {assert} from '@esm-bundle/chai';
import {html, render} from 'lit';
import {PlaygroundIde} from '../playground-ide.js';
import '../playground-ide.js';
import {sendKeys, executeServerCommand} from '@web/test-runner-commands';
import type {ReactiveElement} from '@lit/reactive-element';
import type {PlaygroundCodeEditor} from '../playground-code-editor.js';
import type {PlaygroundProject} from '../playground-project.js';
suite('playground-ide', () => {
let container: HTMLDivElement;
let testRunning: boolean;
setup(() => {
container = document.createElement('div');
document.body.appendChild(container);
testRunning = true;
});
teardown(() => {
container.remove();
testRunning = false;
});
test('is registered', () => {
assert.instanceOf(document.createElement('playground-ide'), PlaygroundIde);
});
const raf = async () => new Promise((r) => requestAnimationFrame(r));
const pierce = async (...selectors: string[]) => {
let node = document.body;
for (const selector of selectors) {
const result = (node.shadowRoot ?? node).querySelector(selector);
assert.instanceOf(result, Element);
if ((result as ReactiveElement).updateComplete) {
await (result as ReactiveElement).updateComplete;
}
node = result as HTMLElement;
}
return node;
};
// TODO(aomarks) Use sendKeys instead
// https://modern-web.dev/docs/test-runner/commands/#send-keys
const updateCurrentFile = async (
editor: PlaygroundCodeEditor,
newValue: string
) => {
const codemirror = (
editor as unknown as {
_codemirror: PlaygroundCodeEditor['_codemirror'];
}
)._codemirror;
codemirror!.setValue(newValue);
};
const waitForIframeLoad = (iframe: HTMLElement) =>
new Promise<void>((resolve) => {
iframe.addEventListener('load', () => resolve(), {once: true});
});
const assertPreviewContains = async (text: string) => {
const iframe = (await pierce(
'playground-ide',
'playground-preview',
'iframe'
)) as HTMLIFrameElement;
await waitForIframeLoad(iframe);
// TODO(aomarks) Chromium and Webkit both fire iframe "load" after the
// contentDocument has actually loaded, but Firefox fires it before. Why is
// that? If not for that, we wouldn't need to poll here.
await new Promise<void>((resolve) => {
const check = () => {
if (iframe.contentDocument?.body?.textContent?.includes(text)) {
resolve();
} else if (testRunning) {
setTimeout(check, 10);
}
};
check();
});
};
test('renders HTML', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html">
<p>Hello HTML</p>
<script>console.log('hello');</script>
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello HTML');
});
test('renders JS', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html">
<body>
<script src="hello.js"></script>
</body>
</script>
<script type="sample/js" filename="hello.js">
document.body.textContent = 'Hello JS';
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello JS');
});
test('renders TS', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html">
<body>
<script src="hello.js"></script>
</body>
</script>
<script type="sample/ts" filename="hello.ts">
const hello: string = "Hello TS";
document.body.textContent = hello;
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello TS');
});
test('re-renders HTML', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html">
<body>
<p>Hello HTML 1</p>
</body>
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello HTML 1');
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
updateCurrentFile(editor, 'Hello HTML 2');
const project = (await pierce(
'playground-ide',
'playground-project'
)) as PlaygroundProject;
// Note we shouldn't await the save(), because assertPreviewContains waits
// for an iframe load event, and we can legitimately get an iframe load
// before the full compile is done since we serve each asset as soon as it
// is ready.
project.save();
await assertPreviewContains('Hello HTML 2');
});
test('hidden file is not displayed in tab bar', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html" hidden>
<body>
<script src="hello.js"></script>
</body>
</script>
<script type="sample/js" filename="hello.js">
document.body.textContent = 'Hello JS';
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello JS');
const tabBar = await pierce('playground-ide', 'playground-tab-bar');
const tabs = tabBar.shadowRoot?.querySelectorAll('playground-internal-tab');
assert.equal(tabs?.length, 1);
});
test('file label is displayed in tab bar', async () => {
render(
html`
<playground-ide sandbox-base-url="/">
<script type="sample/html" filename="index.html" label="HTML">
<body>
<script src="hello.js"></script>
</body>
</script>
<script type="sample/js" filename="hello.js" label="JS">
document.body.textContent = 'Hello JS';
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello JS');
const tabBar = await pierce('playground-ide', 'playground-tab-bar');
const tabs = tabBar.shadowRoot?.querySelectorAll('playground-internal-tab');
const texts = Array.from(tabs ?? []).map((tab) => tab.textContent?.trim());
assert.deepEqual(texts, ['HTML', 'JS']);
});
test('reads files from config property', async () => {
const ide = document.createElement('playground-ide')!;
ide.sandboxBaseUrl = '/';
container.appendChild(ide);
ide.config = {
files: {
'index.html': {
content: 'Hello HTML',
},
},
};
await assertPreviewContains('Hello HTML');
});
test('a11y: is contenteditable', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.html': {
content: 'Foo',
},
},
};
container.appendChild(ide);
await assertPreviewContains('Foo');
const cmCode = await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor',
'.CodeMirror-code'
);
assert.equal(cmCode.getAttribute('contenteditable'), 'true');
});
test('a11y: line numbers get aria-hidden attribute', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.lineNumbers = true;
ide.config = {
files: {
'index.html': {
content: 'Foo\nBar',
},
},
};
container.appendChild(ide);
await assertPreviewContains('Foo\nBar');
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
const queryHiddenLineNumbers = () =>
[
...editor.shadowRoot!.querySelectorAll('.CodeMirror-gutter-wrapper'),
].filter((gutter) => gutter.getAttribute('aria-hidden') === 'true');
// Initial render with line-numbers enabled.
assert.equal(queryHiddenLineNumbers().length, 2);
// Disable line numbers.
ide.lineNumbers = false;
await raf();
assert.equal(queryHiddenLineNumbers().length, 0);
// Re-enable line numbers.
ide.lineNumbers = true;
await raf();
assert.equal(queryHiddenLineNumbers().length, 2);
// Add a line.
const editorInternals = editor as unknown as {
_codemirror: PlaygroundCodeEditor['_codemirror'];
};
editorInternals._codemirror!.setValue(editor.value + '\nBaz');
await raf();
assert.equal(queryHiddenLineNumbers().length, 3);
});
test('a11y: focusing shows keyboard prompt', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.html': {
content: 'Foo',
},
},
};
container.appendChild(ide);
await assertPreviewContains('Foo');
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
const focusContainer = editor.shadowRoot!.querySelector(
'#focusContainer'
) as HTMLElement;
const editableRegion = editor.shadowRoot!.querySelector(
'.CodeMirror-code'
) as HTMLElement;
const keyboardHelp = 'Press Enter';
// Not focused initially
assert.notInclude(focusContainer.textContent, keyboardHelp);
// When the inner container is focused, show the keyboard prompt
focusContainer.focus();
await raf();
assert.isTrue(focusContainer.matches(':focus'));
assert.include(focusContainer.textContent, keyboardHelp);
// Press Enter to start editing
focusContainer.dispatchEvent(new KeyboardEvent('keydown', {key: 'Enter'}));
await raf();
assert.isTrue(editableRegion.matches(':focus'));
assert.notInclude(focusContainer.textContent, keyboardHelp);
// Press Escape to stop editing
editableRegion.dispatchEvent(
new KeyboardEvent('keydown', {key: 'Escape', bubbles: true})
);
await raf();
assert.isTrue(focusContainer.matches(':focus'));
assert.include(focusContainer.textContent, keyboardHelp);
// Focus something else entirely
focusContainer.blur();
await raf();
assert.isFalse(focusContainer.matches(':focus'));
assert.isFalse(editableRegion.matches(':focus'));
assert.notInclude(focusContainer.textContent, keyboardHelp);
});
test('ignores query params when serving files', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.html': {
content: '<script>location.assign("./foo.html?xyz");</script>',
},
'foo.html': {
content: 'foo.html loaded',
},
},
};
container.appendChild(ide);
await assertPreviewContains('foo.html loaded');
});
test('create new files', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.html': {
content: 'Hello',
},
'package.json': {
content: '{"dependencies":{}}',
hidden: true,
},
},
};
container.appendChild(ide);
const project = (await pierce(
'playground-ide',
'playground-project'
)) as PlaygroundProject;
// Need to defer another microtask for the config to initialize.
await new Promise((resolve) => requestAnimationFrame(resolve));
// Already exists.
assert.isFalse(project.isValidNewFilename('index.html'));
// Does not exist.
assert.isTrue(project.isValidNewFilename('newfile.ts'));
project.addFile('newfile.ts');
assert.isFalse(project.isValidNewFilename('newfile.ts'));
// Exists but is hidden. Creating it unhides it and reveals the existing
// content.
assert.isTrue(project.isValidNewFilename('package.json'));
project.addFile('package.json');
assert.isFalse(project.isValidNewFilename('package.json'));
const packageJson = project.files?.find(
(file) => file.name === 'package.json'
);
assert.isFalse(packageJson?.hidden);
assert.equal(packageJson?.content, '{"dependencies":{}}');
});
test('modified property', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.html': {
content: 'Old content',
},
},
};
container.appendChild(ide);
const project = (await pierce(
'playground-ide',
'playground-project'
)) as PlaygroundProject;
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
const editorInternals = editor as unknown as {
_codemirror: PlaygroundCodeEditor['_codemirror'];
};
// Need to defer another microtask for the config to initialize.
await new Promise((resolve) => requestAnimationFrame(resolve));
// Note the double checks are here to add coverage for cached states.
assert.isFalse(ide.modified);
assert.isFalse(ide.modified);
project.addFile('potato.html');
assert.isTrue(ide.modified);
assert.isTrue(ide.modified);
project.deleteFile('potato.html');
assert.isFalse(ide.modified);
assert.isFalse(ide.modified);
project.renameFile('index.html', 'potato.html');
assert.isTrue(ide.modified);
assert.isTrue(ide.modified);
project.renameFile('potato.html', 'index.html');
assert.isFalse(ide.modified);
assert.isFalse(ide.modified);
editorInternals._codemirror!.setValue('New content');
assert.isTrue(ide.modified);
assert.isTrue(ide.modified);
editorInternals._codemirror!.setValue('Old content');
assert.isFalse(ide.modified);
assert.isFalse(ide.modified);
project.addFile('potato.html');
assert.isTrue(ide.modified);
assert.isTrue(ide.modified);
ide.config = {
files: {
'index.html': {
content: 'Different content',
},
},
};
await new Promise((resolve) => requestAnimationFrame(resolve));
assert.isFalse(ide.modified);
assert.isFalse(ide.modified);
});
test('returns the correct cursor position and index', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.js': {
content: '',
},
},
};
container.appendChild(ide);
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
const codeToAdd = `console.log("Foo");
console.log("bar");`;
await new Promise((resolve) => window.requestAnimationFrame(resolve));
editor.focus();
await sendKeys({
type: codeToAdd,
});
assert.equal(editor.value, codeToAdd);
assert.equal(editor.cursorIndex, codeToAdd.length);
const cursorPosition = editor.cursorPosition;
assert.equal(cursorPosition.line, 1);
assert.equal(cursorPosition.ch, 23);
});
test('returns the token under cursor', async () => {
const ide = document.createElement('playground-ide');
ide.sandboxBaseUrl = '/';
ide.config = {
files: {
'index.js': {
content: 'console.log("Foo")',
},
},
};
container.appendChild(ide);
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
await new Promise((resolve) => window.requestAnimationFrame(resolve));
editor.focus();
await sendKeys({
press: 'ArrowRight',
});
const tokenUnderCursor = editor.tokenUnderCursor;
assert.equal(tokenUnderCursor.start, 0);
assert.equal(tokenUnderCursor.end, 7);
assert.equal(tokenUnderCursor.string, 'console');
});
test('reloading preview does not modify history', async () => {
const historyLengthBefore = window.history.length;
// NOTE: For some reason, the parent window's history only seems to be
// affected when the iframe origin is different.
const separateOrigin = (await executeServerCommand(
'separate-origin'
)) as string;
render(
html`
<playground-ide sandbox-base-url="${separateOrigin}">
<script type="sample/html" filename="index.html">
<body>
<p>Hello HTML 1</p>
</body>
</script>
</playground-ide>
`,
container
);
const iframe = (await pierce(
'playground-ide',
'playground-preview',
'iframe'
)) as HTMLIFrameElement;
await waitForIframeLoad(iframe);
const editor = (await pierce(
'playground-ide',
'playground-file-editor',
'playground-code-editor'
)) as PlaygroundCodeEditor;
updateCurrentFile(editor, 'Hello HTML 2');
const project = (await pierce(
'playground-ide',
'playground-project'
)) as PlaygroundProject;
project.save();
await waitForIframeLoad(iframe);
const historyLengthAfter = window.history.length;
assert.equal(historyLengthAfter, historyLengthBefore);
});
test('delete file using menu', async () => {
render(
html`
<playground-ide sandbox-base-url="/" editable-file-system>
<script type="sample/html" filename="index.html">
<body>
<p>Hello HTML</p>
</body>
</script>
</playground-ide>
`,
container
);
await assertPreviewContains('Hello HTML');
const project = (await pierce(
'playground-ide',
'playground-project'
)) as PlaygroundProject;
assert.lengthOf(project.files ?? [], 1);
// Between MWC v0.25.1 and v0.25.2, when clicking on an <mwc-icon-button>,
// the target changed from the <mwc-icon-button> to its internal <svg>.
const menuButtonSvg = await pierce(
'playground-ide',
'playground-tab-bar',
'.menu-button > svg'
);
menuButtonSvg.dispatchEvent(new Event('click', {bubbles: true}));
const deleteButton = await pierce(
'playground-ide',
'playground-tab-bar',
'playground-file-system-controls',
'#deleteButton'
);
deleteButton.click();
assert.lengthOf(project.files ?? [], 0);
});
}); | the_stack |
import * as React from 'react'
import { Translated, translateWithTracker } from '../../lib/ReactMeteorData/react-meteor-data'
import { PeripheralDevice, PeripheralDevices } from '../../../lib/collections/PeripheralDevices'
import * as reacti18next from 'react-i18next'
import * as i18next from 'i18next'
import { PeripheralDeviceAPI } from '../../../lib/api/peripheralDevice'
import Moment from 'react-moment'
import { getCurrentTime, getHash, unprotectString } from '../../../lib/lib'
import { Link } from 'react-router-dom'
import Tooltip from 'rc-tooltip'
import { faTrash, faEye } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import * as _ from 'underscore'
import { doModalDialog } from '../../lib/ModalDialog'
import { MeteorReactComponent } from '../../lib/MeteorReactComponent'
import { callPeripheralDeviceFunction, PeripheralDevicesAPI } from '../../lib/clientAPI'
import { NotificationCenter, NoticeLevel, Notification } from '../../lib/notifications/notifications'
import { getAllowConfigure, getAllowDeveloper, getAllowStudio, getHelpMode } from '../../lib/localStorage'
import { PubSub } from '../../../lib/api/pubsub'
import ClassNames from 'classnames'
import { TSR } from '@sofie-automation/blueprints-integration'
import { CoreSystem, ICoreSystem } from '../../../lib/collections/CoreSystem'
import { StatusResponse } from '../../../lib/api/systemStatus'
import { doUserAction, UserAction } from '../../lib/userAction'
import { MeteorCall } from '../../../lib/api/methods'
import { RESTART_SALT } from '../../../lib/api/userActions'
import { CASPARCG_RESTART_TIME } from '../../../lib/constants'
interface IDeviceItemProps {
// key: string,
device: PeripheralDevice
showRemoveButtons?: boolean
toplevel?: boolean
hasChildren?: boolean
}
interface IDeviceItemState {}
export function statusCodeToString(t: i18next.TFunction, statusCode: PeripheralDeviceAPI.StatusCode) {
return statusCode === PeripheralDeviceAPI.StatusCode.UNKNOWN
? t('Unknown')
: statusCode === PeripheralDeviceAPI.StatusCode.GOOD
? t('Good')
: statusCode === PeripheralDeviceAPI.StatusCode.WARNING_MINOR
? t('Minor Warning')
: statusCode === PeripheralDeviceAPI.StatusCode.WARNING_MAJOR
? t('Warning')
: statusCode === PeripheralDeviceAPI.StatusCode.BAD
? t('Bad')
: statusCode === PeripheralDeviceAPI.StatusCode.FATAL
? t('Fatal')
: t('Unknown')
}
export const DeviceItem = reacti18next.withTranslation()(
class DeviceItem extends React.Component<Translated<IDeviceItemProps>, IDeviceItemState> {
constructor(props: Translated<IDeviceItemProps>) {
super(props)
this.state = {
showDeleteDeviceConfirm: null,
showKillDeviceConfirm: null,
}
}
deviceTypeString() {
let t = this.props.t
switch (this.props.device.type) {
case PeripheralDeviceAPI.DeviceType.MOS:
return t('MOS Gateway')
case PeripheralDeviceAPI.DeviceType.PLAYOUT:
return t('Play-out Gateway')
case PeripheralDeviceAPI.DeviceType.MEDIA_MANAGER:
return t('Media Manager')
default:
return t('Unknown Device')
}
}
deviceVersions() {
let versions = this.props.device.versions
if (versions) {
return _.map(versions, (version, packageName) => {
return packageName + ': ' + version
}).join('\n')
}
}
onToggleIgnore(device: PeripheralDevice) {
PeripheralDevices.update(device._id, {
$set: {
ignore: !device.ignore,
},
})
}
onRestartCasparCG(device: PeripheralDevice) {
const { t } = this.props
doModalDialog({
title: t('Restart CasparCG Server'),
message: t('Do you want to restart CasparCG Server?'),
onAccept: (event: any) => {
callPeripheralDeviceFunction(event, device._id, CASPARCG_RESTART_TIME, 'restartCasparCG')
.then(() => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.NOTIFICATION,
t('CasparCG on device "{{deviceName}}" restarting...', { deviceName: device.name }),
'SystemStatus'
)
)
})
.catch((err) => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.WARNING,
t('Failed to restart CasparCG on device: "{{deviceName}}": {{errorMessage}}', {
deviceName: device.name,
errorMessage: err + '',
}),
'SystemStatus'
)
)
})
},
})
}
onRestartQuantel(device: PeripheralDevice) {
const { t } = this.props
doModalDialog({
title: t('Restart Quantel Gateway'),
message: t('Do you want to restart Quantel Gateway?'),
onAccept: (event: any) => {
callPeripheralDeviceFunction(event, device._id, undefined, 'restartQuantel')
.then(() => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.NOTIFICATION,
t('Quantel Gateway restarting...'),
'SystemStatus'
)
)
})
.catch((err) => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.WARNING,
t('Failed to restart Quantel Gateway: {{errorMessage}}', { errorMessage: err + '' }),
'SystemStatus'
)
)
})
},
})
}
onFormatHyperdeck(device: PeripheralDevice) {
const { t } = this.props
doModalDialog({
title: t('Format HyperDeck disks'),
message: t('Do you want to format the HyperDeck disks? This is a destructive action and cannot be undone.'),
onAccept: (event: any) => {
callPeripheralDeviceFunction(event, device._id, undefined, 'formatHyperdeck')
.then(() => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.NOTIFICATION,
t('Formatting HyperDeck disks on device "{{deviceName}}"...', { deviceName: device.name }),
'SystemStatus'
)
)
})
.catch((err) => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.WARNING,
t('Failed to format HyperDecks on device: "{{deviceName}}": {{errorMessage}}', {
deviceName: device.name,
errorMessage: err + '',
}),
'SystemStatus'
)
)
})
},
})
}
render() {
const { t } = this.props
return (
<div key={unprotectString(this.props.device._id)} className="device-item">
<div className="status-container">
<PeripheralDeviceStatus device={this.props.device} />
<div className="device-item__last-seen">
<label>{t('Last seen')}: </label>
<div className="value">
<Moment from={getCurrentTime()} date={this.props.device.lastSeen} />
</div>
</div>
</div>
<div className="device-item__id">
<Tooltip
overlay={t('Connect some devices to the playout gateway')}
visible={
getHelpMode() &&
this.props.device.type === PeripheralDeviceAPI.DeviceType.PLAYOUT &&
this.props.toplevel === true &&
!this.props.hasChildren &&
this.props.hasChildren !== undefined
}
placement="right"
>
{getAllowConfigure() ? (
<div className="value">
<Link to={'/settings/peripheralDevice/' + this.props.device._id}>{this.props.device.name}</Link>
</div>
) : (
<div className="value">{this.props.device.name}</div>
)}
</Tooltip>
</div>
{this.props.device.versions ? (
<div className="device-item__version">
<label>{t('Version')}: </label>
<div className="value">
<a title={this.deviceVersions()} href="#">
{this.props.device.versions._process || 'N/A'}
</a>
</div>
</div>
) : null}
<div className="actions-container">
<div className="device-item__actions">
{getAllowStudio() &&
this.props.device.type === PeripheralDeviceAPI.DeviceType.PLAYOUT &&
this.props.device.subType === TSR.DeviceType.CASPARCG ? (
<React.Fragment>
<button
className="btn btn-secondary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
this.onRestartCasparCG(this.props.device)
}}
>
{t('Restart')}
{/** IDK what this does, but it doesn't seem to make a lot of sense: JSON.stringify(this.props.device.settings) */}
</button>
</React.Fragment>
) : null}
{getAllowStudio() &&
this.props.device.type === PeripheralDeviceAPI.DeviceType.PLAYOUT &&
this.props.device.subType === TSR.DeviceType.HYPERDECK ? (
<React.Fragment>
<button
className="btn btn-secondary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
this.onFormatHyperdeck(this.props.device)
}}
>
{t('Format disks')}
</button>
</React.Fragment>
) : null}
{getAllowStudio() &&
this.props.device.type === PeripheralDeviceAPI.DeviceType.PLAYOUT &&
this.props.device.subType === TSR.DeviceType.QUANTEL ? (
<React.Fragment>
<button
className="btn btn-secondary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
this.onRestartQuantel(this.props.device)
}}
>
{t('Restart Quantel Gateway')}
</button>
</React.Fragment>
) : null}
{getAllowDeveloper() ? (
<button
key="button-ignore"
className={ClassNames('btn btn-secondary', {
warn: this.props.device.ignore,
})}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
this.onToggleIgnore(this.props.device)
}}
>
<FontAwesomeIcon icon={faEye} />
</button>
) : null}
{this.props.showRemoveButtons ? (
<button
key="button-device"
className="btn btn-primary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
doModalDialog({
title: t('Delete'),
message: (
<p>
{t('Are you sure you want to delete this device: "{{deviceId}}"?', {
deviceId: this.props.device.name || this.props.device._id,
})}
</p>
),
onAccept: () => {
MeteorCall.peripheralDevice.removePeripheralDevice(this.props.device._id).catch(console.error)
},
})
}}
>
<FontAwesomeIcon icon={faTrash} />
</button>
) : null}
{getAllowStudio() && this.props.device.subType === PeripheralDeviceAPI.SUBTYPE_PROCESS ? (
<React.Fragment>
<button
className="btn btn-secondary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
doModalDialog({
title: t('Delete'),
message: <p>{t('Are you sure you want to restart this device?')}</p>,
onAccept: () => {
const { t } = this.props
PeripheralDevicesAPI.restartDevice(this.props.device, e)
.then(() => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.NOTIFICATION,
t('Device "{{deviceName}}" restarting...', {
deviceName: this.props.device.name,
}),
'SystemStatus'
)
)
})
.catch((err) => {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.WARNING,
t('Failed to restart device: "{{deviceName}}": {{errorMessage}}', {
deviceName: this.props.device.name,
errorMessage: err + '',
}),
'SystemStatus'
)
)
})
},
})
}}
>
{t('Restart')}
</button>
</React.Fragment>
) : null}
</div>
</div>
<div className="clear"></div>
</div>
)
}
}
)
interface ICoreItemProps {
systemStatus: StatusResponse | undefined
coreSystem: ICoreSystem
}
interface ICoreItemState {}
const PackageInfo = require('../../../package.json')
export const CoreItem = reacti18next.withTranslation()(
class CoreItem extends React.Component<Translated<ICoreItemProps>, ICoreItemState> {
constructor(props: Translated<ICoreItemProps>) {
super(props)
this.state = {}
}
render() {
const { t } = this.props
return (
<div key={unprotectString(this.props.coreSystem._id)} className="device-item">
<div className="status-container">
<div
className={ClassNames(
'device-status',
this.props.systemStatus &&
this.props.systemStatus.status && {
'device-status--unknown': this.props.systemStatus.status === 'UNDEFINED',
'device-status--good': this.props.systemStatus.status === 'OK',
'device-status--warning': this.props.systemStatus.status === 'WARNING',
'device-status--fatal': this.props.systemStatus.status === 'FAIL',
}
)}
>
<div className="value">
<span className="pill device-status__label">
<a
href="#"
title={
this.props.systemStatus && this.props.systemStatus._internal.messages
? this.props.systemStatus._internal.messages.join('\n')
: undefined
}
>
{this.props.systemStatus && this.props.systemStatus.status}
</a>
</span>
</div>
</div>
</div>
<div className="device-item__id">
<div className="value">
{t('Sofie Automation Server Core: {{name}}', { name: this.props.coreSystem.name || 'unnamed' })}
</div>
</div>
<div className="device-item__version">
<label>{t('Version')}: </label>
<div className="value">{PackageInfo.version || 'UNSTABLE'}</div>
</div>
{(getAllowConfigure() || getAllowDeveloper()) && (
<div className="actions-container">
<div className="device-item__actions">
<button
className="btn btn-secondary"
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
doModalDialog({
title: t('Restart this system?'),
yes: t('Restart'),
no: t('Cancel'),
message: (
<p>
{t('Are you sure you want to restart this Sofie Automation Server Core: {{name}}?', {
name: this.props.coreSystem.name || 'unnamed',
})}
</p>
),
onAccept: (e) => {
doUserAction(
t,
e,
UserAction.GENERATE_RESTART_TOKEN,
(e) => MeteorCall.userAction.generateRestartToken(e),
(err, token) => {
if (err || !token) {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.CRITICAL,
t('Could not generate restart token!'),
'SystemStatus'
)
)
return
}
const restartToken = getHash(RESTART_SALT + token)
doUserAction(
t,
{},
UserAction.RESTART_CORE,
(e) => MeteorCall.userAction.restartCore(e, restartToken),
(err, token) => {
if (err || !token) {
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.CRITICAL,
t('Could not generate restart core: {{err}}', { err }),
'SystemStatus'
)
)
return
}
let time = 'unknown'
const match = token.match(/([\d\.]+)s/)
if (match) {
time = match[1]
}
NotificationCenter.push(
new Notification(
undefined,
NoticeLevel.WARNING,
t('Sofie Automation Server Core will restart in {{time}}s...', { time }),
'SystemStatus'
)
)
}
)
}
)
},
})
}}
>
{t('Restart')}
</button>
</div>
</div>
)}
<div className="clear"></div>
</div>
)
}
}
)
interface ISystemStatusProps {}
interface ISystemStatusState {
systemStatus: StatusResponse | undefined
}
interface ISystemStatusTrackedProps {
coreSystem: ICoreSystem | undefined
devices: Array<PeripheralDevice>
}
interface DeviceInHierarchy {
device: PeripheralDevice
children: Array<DeviceInHierarchy>
}
export default translateWithTracker<ISystemStatusProps, ISystemStatusState, ISystemStatusTrackedProps>(() => {
return {
coreSystem: CoreSystem.findOne(),
devices: PeripheralDevices.find({}, { sort: { lastConnected: -1 } }).fetch(),
}
})(
class SystemStatus extends MeteorReactComponent<
Translated<ISystemStatusProps & ISystemStatusTrackedProps>,
ISystemStatusState
> {
private refreshInterval: NodeJS.Timer | undefined = undefined
private destroyed: boolean = false
constructor(props) {
super(props)
this.state = {
systemStatus: undefined,
}
}
componentDidMount() {
this.refreshSystemStatus()
this.refreshInterval = setInterval(this.refreshSystemStatus, 5000)
// Subscribe to data:
this.subscribe(PubSub.peripheralDevices, {})
}
componentWillUnmount() {
if (this.refreshInterval) clearInterval(this.refreshInterval)
this.destroyed = true
}
refreshSystemStatus = () => {
const { t } = this.props
MeteorCall.systemStatus
.getSystemStatus()
.then((systemStatus: StatusResponse) => {
if (this.destroyed) return
this.setState({
systemStatus: systemStatus,
})
})
.catch(() => {
if (this.destroyed) return
// console.error(err)
NotificationCenter.push(
new Notification(
'systemStatus_failed',
NoticeLevel.CRITICAL,
t('Could not get system status. Please consult system administrator.'),
'RundownList'
)
)
return
})
}
renderPeripheralDevices() {
let devices: Array<DeviceInHierarchy> = []
let refs = {}
let devicesToAdd = {}
// First, add all as references:
_.each(this.props.devices, (device) => {
let d: DeviceInHierarchy = {
device: device,
children: [],
}
refs[unprotectString(device._id)] = d
devicesToAdd[unprotectString(device._id)] = d
})
// Then, map and add devices:
_.each(devicesToAdd, (d: DeviceInHierarchy) => {
if (d.device.parentDeviceId) {
let parent: DeviceInHierarchy = refs[unprotectString(d.device.parentDeviceId)]
if (parent) {
parent.children.push(d)
} else {
// not found, add on top level then:
devices.push(d)
}
} else {
devices.push(d)
}
})
const getDeviceContent = (d: DeviceInHierarchy, toplevel: boolean): JSX.Element => {
let content: JSX.Element[] = [
<DeviceItem
key={'device' + d.device._id}
device={d.device}
toplevel={toplevel}
hasChildren={d.children.length !== 0}
/>,
]
if (d.children.length) {
let children: JSX.Element[] = []
_.each(d.children, (child: DeviceInHierarchy) =>
children.push(
<li key={'childdevice' + child.device._id} className="child-device-li">
{getDeviceContent(child, false)}
</li>
)
)
content.push(
<div key={d.device._id + '_children'} className="children">
<ul className="childlist">{children}</ul>
</div>
)
}
return (
<div key={d.device._id + '_parent'} className="device-item-container">
{content}
</div>
)
}
return (
<React.Fragment>
{this.props.coreSystem && (
<CoreItem coreSystem={this.props.coreSystem} systemStatus={this.state.systemStatus} />
)}
{_.map(devices, (d) => getDeviceContent(d, true))}
</React.Fragment>
)
}
render() {
const { t } = this.props
return (
<div className="mhl gutter system-status">
<header className="mbs">
<h1>{t('System Status')}</h1>
</header>
<div className="mod mvl">{this.renderPeripheralDevices()}</div>
</div>
)
}
}
)
interface PeripheralDeviceStatusProps {
device: PeripheralDevice
}
interface PeripheralDeviceStatusState {}
export const PeripheralDeviceStatus = reacti18next.withTranslation()(
class PeripheralDeviceStatus extends React.Component<
PeripheralDeviceStatusProps & reacti18next.WithTranslation,
PeripheralDeviceStatusState
> {
constructor(props: PeripheralDeviceStatusProps & reacti18next.WithTranslation) {
super(props)
}
statusCodeString() {
const { t } = this.props
return this.props.device.connected
? statusCodeToString(t, this.props.device.status.statusCode)
: t('Not Connected')
}
statusMessages() {
let messages = ((this.props.device || {}).status || {}).messages || []
return messages.length ? '"' + messages.join(', ') + '"' : ''
}
render() {
const statusClassNames = [
'device-status',
this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.UNKNOWN || !this.props.device.connected
? 'device-status--unknown'
: this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.GOOD
? 'device-status--good'
: this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.WARNING_MINOR
? 'device-status--minor-warning'
: this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.WARNING_MAJOR
? 'device-status--warning'
: this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.BAD
? 'device-status--bad'
: this.props.device.status.statusCode === PeripheralDeviceAPI.StatusCode.FATAL
? 'device-status--fatal'
: '',
].join(' ')
return (
<div className={statusClassNames}>
<div className="value">
<span className="pill device-status__label">{this.statusCodeString()}</span>
</div>
<div className="device-item__device-status-message">
<span className="text-s dimmed">{this.statusMessages()}</span>
</div>
</div>
)
}
}
) | the_stack |
import "./../style/gantt.less";
import * as d3 from "d3";
import * as _ from "lodash";
import powerbi from "powerbi-visuals-api";
// d3
type Selection<T1, T2 = T1> = d3.Selection<any, T1, any, T2>;
import timeScale = d3.ScaleTime;
// powerbi
import DataView = powerbi.DataView;
import IViewport = powerbi.IViewport;
import SortDirection = powerbi.SortDirection;
import DataViewValueColumn = powerbi.DataViewValueColumn;
import DataViewValueColumns = powerbi.DataViewValueColumns;
import DataViewMetadataColumn = powerbi.DataViewMetadataColumn;
import DataViewValueColumnGroup = powerbi.DataViewValueColumnGroup;
import PrimitiveValue = powerbi.PrimitiveValue;
import VisualObjectInstance = powerbi.VisualObjectInstance;
import DataViewCategoryColumn = powerbi.DataViewCategoryColumn;
import VisualObjectInstanceEnumeration = powerbi.VisualObjectInstanceEnumeration;
import DataViewObjectPropertyIdentifier = powerbi.DataViewObjectPropertyIdentifier;
import EnumerateVisualObjectInstancesOptions = powerbi.EnumerateVisualObjectInstancesOptions;
import VisualObjectInstanceEnumerationObject = powerbi.VisualObjectInstanceEnumerationObject;
import VisualObjectInstancesToPersist = powerbi.VisualObjectInstancesToPersist;
import IColorPalette = powerbi.extensibility.IColorPalette;
import ILocalizationManager = powerbi.extensibility.ILocalizationManager;
import IVisualEventService = powerbi.extensibility.IVisualEventService;
import VisualTooltipDataItem = powerbi.extensibility.VisualTooltipDataItem;
// powerbi.visuals
import ISelectionId = powerbi.visuals.ISelectionId;
import ISelectionIdBuilder = powerbi.visuals.ISelectionIdBuilder;
// powerbi.extensibility.visual
import IVisualHost = powerbi.extensibility.visual.IVisualHost;
import IVisual = powerbi.extensibility.visual.IVisual;
import VisualUpdateOptions = powerbi.extensibility.visual.VisualUpdateOptions;
import VisualConstructorOptions = powerbi.extensibility.visual.VisualConstructorOptions;
// powerbi.extensibility.utils.svg
import * as SVGUtil from "powerbi-visuals-utils-svgutils";
import SVGManipulations = SVGUtil.manipulation;
import ClassAndSelector = SVGUtil.CssConstants.ClassAndSelector;
import createClassAndSelector = SVGUtil.CssConstants.createClassAndSelector;
import IMargin = SVGUtil.IMargin;
// powerbi.extensibility.utils.type
import { pixelConverter as PixelConverter, valueType } from "powerbi-visuals-utils-typeutils";
import PrimitiveType = valueType.PrimitiveType;
import ValueType = valueType.ValueType;
// powerbi.extensibility.utils.formatting
import { textMeasurementService as tms, valueFormatter as ValueFormatter } from "powerbi-visuals-utils-formattingutils";
import TextProperties = tms.TextProperties;
import IValueFormatter = ValueFormatter.IValueFormatter;
import textMeasurementService = tms.textMeasurementService;
// powerbi.extensibility.utils.interactivity
import { interactivityBaseService as interactivityService, interactivitySelectionService } from "powerbi-visuals-utils-interactivityutils";
import appendClearCatcher = interactivityService.appendClearCatcher;
import IInteractiveBehavior = interactivityService.IInteractiveBehavior;
import IInteractivityService = interactivityService.IInteractivityService;
import createInteractivityService = interactivitySelectionService.createInteractivitySelectionService;
// powerbi.extensibility.utils.tooltip
import { createTooltipServiceWrapper, TooltipEventArgs, ITooltipServiceWrapper, TooltipEnabledDataPoint } from "powerbi-visuals-utils-tooltiputils";
// powerbi.extensibility.utils.color
import { ColorHelper } from "powerbi-visuals-utils-colorutils";
// powerbi.extensibility.utils.chart.legend
import { legend as LegendModule, legendInterfaces, OpacityLegendBehavior, axisInterfaces, axisScale, axis as AxisHelper } from "powerbi-visuals-utils-chartutils";
import ILegend = legendInterfaces.ILegend;
import LegendPosition = legendInterfaces.LegendPosition;
import LegendData = legendInterfaces.LegendData;
import createLegend = LegendModule.createLegend;
import LegendDataPoint = legendInterfaces.LegendDataPoint;
// powerbi.extensibility.utils.chart
import IAxisProperties = axisInterfaces.IAxisProperties;
// behavior
import { Behavior, BehaviorOptions } from "./behavior";
import {
Task,
Line,
LinearStop,
MilestonePath,
ExtraInformation,
GanttViewModel,
DaysOffDataForAddition,
DayOffData,
TaskTypeMetadata,
TaskDaysOff,
TaskTypes,
GroupedTask,
GanttCalculateScaleAndDomainOptions,
GanttChartFormatters,
MilestoneData,
MilestoneDataPoint,
Milestone
} from "./interfaces";
import { DurationHelper } from "./durationHelper";
import { GanttColumns } from "./columns";
import { GanttSettings, DateTypeSettings } from "./settings";
import {
drawNotRoundedRectByPath,
drawRoundedRectByPath,
drawCircle,
drawDiamond,
drawRectangle,
isValidDate,
isStringNotNullEmptyOrUndefined,
hashCode
} from "./utils";
import { drawExpandButton, drawCollapseButton, drawMinusButton, drawPlusButton } from "./drawButtons";
const PercentFormat: string = "0.00 %;-0.00 %;0.00 %";
const ScrollMargin: number = 100;
const MillisecondsInASecond: number = 1000;
const MillisecondsInAMinute: number = 60 * MillisecondsInASecond;
const MillisecondsInAHour: number = 60 * MillisecondsInAMinute;
const MillisecondsInADay: number = 24 * MillisecondsInAHour;
const MillisecondsInWeek: number = 4 * MillisecondsInADay;
const MillisecondsInAMonth: number = 30 * MillisecondsInADay;
const MillisecondsInAYear: number = 365 * MillisecondsInADay;
const MillisecondsInAQuarter: number = MillisecondsInAYear / 4;
const PaddingTasks: number = 5;
const DaysInAWeekend: number = 2;
const DaysInAWeek: number = 5;
const DefaultChartLineHeight = 40;
const TaskColumnName: string = "Task";
const ParentColumnName: string = "Parent";
const GanttDurationUnitType = [
"second",
"minute",
"hour",
"day",
];
export enum ResourceLabelPositions {
Top = <any>"Top",
Right = <any>"Right",
Inside = <any>"Inside"
}
export enum DurationUnits {
Second = <any>"second",
Minute = <any>"minute",
Hour = <any>"hour",
Day = <any>"day",
}
export enum DateTypes {
Second = <any>"Second",
Minute = <any>"Minute",
Hour = <any>"Hour",
Day = <any>"Day",
Week = <any>"Week",
Month = <any>"Month",
Quarter = <any>"Quarter",
Year = <any>"Year"
}
export enum LabelsForDateTypes {
Now = <any>"Now",
Today = <any>"Today"
}
export enum MilestoneShapeTypes {
Rhombus = "Rhombus",
Circle = "Circle",
Square = "Square"
}
export class SortingOptions {
isCustomSortingNeeded: boolean;
sortingDirection: SortDirection;
}
module Selectors {
export const ClassName: ClassAndSelector = createClassAndSelector("gantt");
export const Chart: ClassAndSelector = createClassAndSelector("chart");
export const ChartLine: ClassAndSelector = createClassAndSelector("chart-line");
export const Body: ClassAndSelector = createClassAndSelector("gantt-body");
export const AxisGroup: ClassAndSelector = createClassAndSelector("axis");
export const Domain: ClassAndSelector = createClassAndSelector("domain");
export const AxisTick: ClassAndSelector = createClassAndSelector("tick");
export const Tasks: ClassAndSelector = createClassAndSelector("tasks");
export const TaskGroup: ClassAndSelector = createClassAndSelector("task-group");
export const SingleTask: ClassAndSelector = createClassAndSelector("task");
export const TaskRect: ClassAndSelector = createClassAndSelector("task-rect");
export const TaskMilestone: ClassAndSelector = createClassAndSelector("task-milestone");
export const TaskProgress: ClassAndSelector = createClassAndSelector("task-progress");
export const TaskDaysOff: ClassAndSelector = createClassAndSelector("task-days-off");
export const TaskResource: ClassAndSelector = createClassAndSelector("task-resource");
export const TaskLabels: ClassAndSelector = createClassAndSelector("task-labels");
export const TaskLines: ClassAndSelector = createClassAndSelector("task-lines");
export const LabelLines: ClassAndSelector = createClassAndSelector("label-lines");
export const TaskLinesRect: ClassAndSelector = createClassAndSelector("task-lines-rect");
export const TaskTopLine: ClassAndSelector = createClassAndSelector("task-top-line");
export const CollapseAll: ClassAndSelector = createClassAndSelector("collapse-all");
export const CollapseAllArrow: ClassAndSelector = createClassAndSelector("collapse-all-arrow");
export const Label: ClassAndSelector = createClassAndSelector("label");
export const LegendItems: ClassAndSelector = createClassAndSelector("legendItem");
export const LegendTitle: ClassAndSelector = createClassAndSelector("legendTitle");
export const ClickableArea: ClassAndSelector = createClassAndSelector("clickableArea");
}
module GanttRoles {
export const Legend: string = "Legend";
export const Task: string = "Task";
export const StartDate: string = "StartDate";
export const EndDate: string = "EndDate";
export const Duration: string = "Duration";
export const Completion: string = "Completion";
export const Resource: string = "Resource";
export const Tooltips: string = "Tooltips";
export const Parent: string = "Parent";
export const Milestones: string = "Milestones";
}
export class Gantt implements IVisual {
private viewport: IViewport;
private colors: IColorPalette;
private colorHelper: ColorHelper;
private legend: ILegend;
private textProperties: TextProperties = {
fontFamily: "wf_segoe-ui_normal",
fontSize: PixelConverter.toString(9),
};
private static LegendPropertyIdentifier: DataViewObjectPropertyIdentifier = {
objectName: "legend",
propertyName: "fill"
};
private static MilestonesPropertyIdentifier: DataViewObjectPropertyIdentifier = {
objectName: "milestones",
propertyName: "fill"
};
private static TaskResourcePropertyIdentifier: DataViewObjectPropertyIdentifier = {
objectName: "taskResource",
propertyName: "show"
};
private static CollapsedTasksPropertyIdentifier: DataViewObjectPropertyIdentifier = {
objectName: "collapsedTasks",
propertyName: "list"
};
public static DefaultValues = {
AxisTickSize: 6,
BarMargin: 2,
ResourceWidth: 100,
TaskColor: "#00B099",
TaskLineColor: "#ccc",
CollapseAllColor: "#000",
PlusMinusColor: "#5F6B6D",
CollapseAllTextColor: "#aaa",
MilestoneLineColor: "#ccc",
TaskCategoryLabelsRectColor: "#fafafa",
TaskLineWidth: 15,
IconMargin: 12,
IconHeight: 16,
IconWidth: 15,
ChildTaskLeftMargin: 25,
ParentTaskLeftMargin: 0,
DefaultDateType: "Week",
DateFormatStrings: {
Second: "HH:mm:ss",
Minute: "HH:mm",
Hour: "HH:mm (dd)",
Day: "MMM dd",
Week: "MMM dd",
Month: "MMM yyyy",
Quarter: "MMM yyyy",
Year: "yyyy"
}
};
private static DefaultGraphicWidthPercentage: number = 0.78;
private static ResourceLabelDefaultDivisionCoefficient: number = 1.5;
private static DefaultTicksLength: number = 50;
private static DefaultDuration: number = 250;
private static TaskLineCoordinateX: number = 15;
private static AxisLabelClip: number = 40;
private static AxisLabelStrokeWidth: number = 1;
private static BarHeightMargin: number = 5;
private static ChartLineHeightDivider: number = 4;
private static ResourceWidthPadding: number = 10;
private static TaskLabelsMarginTop: number = 15;
private static ComplectionDefault: number = null;
private static ComplectionMax: number = 1;
private static ComplectionMin: number = 0;
private static ComplectionMaxInPercent: number = 100;
private static MinTasks: number = 1;
private static ChartLineProportion: number = 1.5;
private static MilestoneTop: number = 0;
private static DeviderForCalculatingPadding: number = 4;
private static LabelTopOffsetForPadding: number = 0.5;
private static DeviderForCalculatingCenter: number = 2;
private static SubtasksLeftMargin: number = 10;
private static NotCompletedTaskOpacity: number = .5;
private static TaskOpacity: number = 1;
private static RectRound: number = 7;
private static get DefaultMargin(): IMargin {
return {
top: 50,
right: 40,
bottom: 40,
left: 10
};
}
private margin: IMargin = Gantt.DefaultMargin;
private body: Selection<any>;
private ganttSvg: Selection<any>;
private viewModel: GanttViewModel;
private timeScale: timeScale<any, any>;
private collapseAllGroup: Selection<any>;
private axisGroup: Selection<any>;
private chartGroup: Selection<any>;
private taskGroup: Selection<any>;
private lineGroup: Selection<any>;
private lineGroupWrapper: Selection<any>;
private clearCatcher: Selection<any>;
private ganttDiv: Selection<any>;
private behavior: Behavior;
private interactivityService: IInteractivityService<Task | LegendDataPoint>;
private eventService: IVisualEventService;
private tooltipServiceWrapper: ITooltipServiceWrapper;
private host: IVisualHost;
private localizationManager: ILocalizationManager;
private isInteractiveChart: boolean = false;
private groupTasksPrevValue: boolean = false;
private collapsedTasks: string[] = [];
private collapseAllFlag: "data-is-collapsed";
private parentLabelOffset: number = 5;
private groupLabelSize: number = 25;
private secondExpandAllIconOffset: number = 7;
private hasNotNullableDates: boolean = false;
constructor(options: VisualConstructorOptions) {
if (window.location !== window.parent.location) {
require("core-js/stable");
}
this.init(options);
}
private init(options: VisualConstructorOptions): void {
this.host = options.host;
this.localizationManager = this.host.createLocalizationManager();
this.colors = options.host.colorPalette;
this.colorHelper = new ColorHelper(this.colors);
this.body = d3.select(options.element);
this.tooltipServiceWrapper = createTooltipServiceWrapper(this.host.tooltipService, options.element);
this.behavior = new Behavior();
this.interactivityService = createInteractivityService(this.host);
this.eventService = options.host.eventService;
this.createViewport(options.element);
}
/**
* Create the viewport area of the gantt chart
*/
private createViewport(element: HTMLElement): void {
let self = this;
const isHighContrast: boolean = this.colorHelper.isHighContrast;
const axisBackgroundColor: string = this.colorHelper.getThemeColor();
// create div container to the whole viewport area
this.ganttDiv = this.body.append("div")
.classed(Selectors.Body.className, true);
// create container to the svg area
this.ganttSvg = this.ganttDiv
.append("svg")
.classed(Selectors.ClassName.className, true);
// create clear catcher
this.clearCatcher = appendClearCatcher(this.ganttSvg);
// create chart container
this.chartGroup = this.ganttSvg
.append("g")
.classed(Selectors.Chart.className, true);
// create tasks container
this.taskGroup = this.chartGroup
.append("g")
.classed(Selectors.Tasks.className, true);
// create tasks container
this.taskGroup = this.chartGroup
.append("g")
.classed(Selectors.Tasks.className, true);
// create axis container
this.axisGroup = this.ganttSvg
.append("g")
.classed(Selectors.AxisGroup.className, true);
this.axisGroup
.append("rect")
.attr("width", "100%")
.attr("y", "-20")
.attr("height", "40px")
.attr("fill", axisBackgroundColor);
// create task lines container
this.lineGroup = this.ganttSvg
.append("g")
.classed(Selectors.TaskLines.className, true);
this.lineGroupWrapper = this.lineGroup
.append("rect")
.classed(Selectors.TaskLinesRect.className, true)
.attr("height", "100%")
.attr("width", "0")
.attr("fill", axisBackgroundColor)
.attr("y", this.margin.top);
this.lineGroup
.append("rect")
.classed(Selectors.TaskTopLine.className, true)
.attr("width", "100%")
.attr("height", 1)
.attr("y", this.margin.top)
.attr("fill", this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.TaskLineColor));
this.collapseAllGroup = this.lineGroup
.append("g")
.classed(Selectors.CollapseAll.className, true);
// create legend container
const interactiveBehavior: IInteractiveBehavior = this.colorHelper.isHighContrast ? new OpacityLegendBehavior() : null;
this.legend = createLegend(
element,
this.isInteractiveChart,
this.interactivityService,
true,
LegendPosition.Top,
interactiveBehavior);
this.ganttDiv.on("scroll", function (evt) {
if (self.viewModel) {
const taskLabelsWidth: number = self.viewModel.settings.taskLabels.show
? self.viewModel.settings.taskLabels.width
: 0;
self.axisGroup
.attr("transform", SVGManipulations.translate(taskLabelsWidth + self.margin.left + Gantt.SubtasksLeftMargin, Gantt.TaskLabelsMarginTop + this.scrollTop));
self.lineGroup
.attr("transform", SVGManipulations.translate(this.scrollLeft, 0))
.attr("height", 20);
}
}, false);
}
/**
* Clear the viewport area
*/
private clearViewport(): void {
this.ganttDiv
.style("height", 0)
.style("width", 0);
this.body
.selectAll(Selectors.LegendItems.selectorName)
.remove();
this.body
.selectAll(Selectors.LegendTitle.selectorName)
.remove();
this.axisGroup
.selectAll(Selectors.AxisTick.selectorName)
.remove();
this.axisGroup
.selectAll(Selectors.Domain.selectorName)
.remove();
this.collapseAllGroup
.selectAll(Selectors.CollapseAll.selectorName)
.remove();
this.lineGroup
.selectAll(Selectors.TaskLabels.selectorName)
.remove();
this.lineGroup
.selectAll(Selectors.Label.selectorName)
.remove();
this.chartGroup
.selectAll(Selectors.ChartLine.selectorName)
.remove();
this.chartGroup
.selectAll(Selectors.TaskGroup.selectorName)
.remove();
this.chartGroup
.selectAll(Selectors.SingleTask.selectorName)
.remove();
}
/**
* Update div container size to the whole viewport area
*/
private updateChartSize(): void {
this.ganttDiv
.style("height", PixelConverter.toString(this.viewport.height))
.style("width", PixelConverter.toString(this.viewport.width));
}
/**
* Check if dataView has a given role
* @param column The dataView headers
* @param name The role to find
*/
private static hasRole(column: DataViewMetadataColumn, name: string) {
return column.roles && column.roles[name];
}
/**
* Get the tooltip info (data display names & formated values)
* @param task All task attributes.
* @param formatters Formatting options for gantt attributes.
* @param durationUnit Duration unit option
*/
public static getTooltipInfo(
task: Task,
formatters: GanttChartFormatters,
durationUnit: string,
localizationManager: ILocalizationManager,
isEndDateFillled: boolean): VisualTooltipDataItem[] {
let tooltipDataArray: VisualTooltipDataItem[] = [];
if (task.taskType) {
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_Legend"),
value: task.taskType
});
}
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_Task"),
value: task.name
});
if (task.start && !isNaN(task.start.getDate())) {
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_StartDate"),
value: formatters.startDateFormatter.format(task.start)
});
}
if (_.isEmpty(task.Milestones) && task.end && !isNaN(task.end.getDate())) {
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_EndDate"),
value: formatters.startDateFormatter.format(task.end)
});
}
if (_.isEmpty(task.Milestones) && task.duration && !isEndDateFillled) {
const durationLabel: string = DurationHelper.generateLabelForDuration(task.duration, durationUnit, localizationManager);
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_Duration"),
value: durationLabel
});
}
if (task.completion) {
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_Completion"),
value: formatters.completionFormatter.format(task.completion)
});
}
if (task.resource) {
tooltipDataArray.push({
displayName: localizationManager.getDisplayName("Role_Resource"),
value: task.resource
});
}
if (task.tooltipInfo && task.tooltipInfo.length) {
tooltipDataArray.push(...task.tooltipInfo);
}
task.extraInformation
.map(tooltip => {
if (typeof tooltip.value === "string") {
return tooltip;
}
const value: any = tooltip.value;
if (isNaN(Date.parse(value)) || typeof value === "number") {
tooltip.value = value.toString();
} else {
tooltip.value = formatters.startDateFormatter.format(value);
}
return tooltip;
})
.forEach(tooltip => tooltipDataArray.push(tooltip));
tooltipDataArray
.filter(x => x.value && typeof x.value !== "string")
.forEach(tooltip => tooltip.value = tooltip.value.toString());
return tooltipDataArray;
}
/**
* Check if task has data for task
* @param dataView
*/
private static isChartHasTask(dataView: DataView): boolean {
if (dataView.metadata &&
dataView.metadata.columns) {
for (let column of dataView.metadata.columns) {
if (Gantt.hasRole(column, GanttRoles.Task)) {
return true;
}
}
}
return false;
}
/**
* Returns the chart formatters
* @param dataView The data Model
* @param cultureSelector The current user culture
*/
private static getFormatters(
dataView: DataView,
settings: GanttSettings,
cultureSelector: string): GanttChartFormatters {
if (!dataView ||
!dataView.metadata ||
!dataView.metadata.columns) {
return null;
}
let dateFormat: string = "d";
for (let dvColumn of dataView.metadata.columns) {
if (Gantt.hasRole(dvColumn, GanttRoles.StartDate)) {
dateFormat = dvColumn.format;
}
}
// Priority of using date format: Format from dvColumn -> Format by culture selector -> Custom Format
if (cultureSelector) {
dateFormat = null;
}
if (!settings.tooltipConfig.dateFormat) {
settings.tooltipConfig.dateFormat = dateFormat;
}
if (settings.tooltipConfig.dateFormat &&
settings.tooltipConfig.dateFormat !== dateFormat) {
dateFormat = settings.tooltipConfig.dateFormat;
}
return <GanttChartFormatters>{
startDateFormatter: ValueFormatter.create({ format: dateFormat, cultureSelector }),
completionFormatter: ValueFormatter.create({ format: PercentFormat, value: 1, allowFormatBeautification: true })
};
}
private static createLegend(
host: IVisualHost,
colorPalette: IColorPalette,
settings: GanttSettings,
taskTypes: TaskTypes,
useDefaultColor: boolean): LegendData {
const colorHelper = new ColorHelper(colorPalette, Gantt.LegendPropertyIdentifier);
const legendData: LegendData = {
fontSize: settings.legend.fontSize,
dataPoints: [],
title: settings.legend.showTitle ? (settings.legend.titleText || taskTypes.typeName) : null,
labelColor: settings.legend.labelColor
};
legendData.dataPoints = taskTypes.types.map(
(typeMeta: TaskTypeMetadata): LegendDataPoint => {
let color: string = settings.taskConfig.fill;
if (!useDefaultColor && !colorHelper.isHighContrast) {
color = colorHelper.getColorForMeasure(typeMeta.columnGroup.objects, typeMeta.name);
}
return {
label: typeMeta.name,
color: color,
selected: false,
identity: host.createSelectionIdBuilder()
.withCategory(typeMeta.selectionColumn, 0)
.createSelectionId()
};
});
return legendData;
}
private static getSortingOptions(dataView: DataView): SortingOptions {
let sortingOption: SortingOptions = new SortingOptions();
dataView.metadata.columns.forEach(column => {
if (column.roles && column.sort && (column.roles[ParentColumnName] || column.roles[TaskColumnName])) {
sortingOption.isCustomSortingNeeded = true;
sortingOption.sortingDirection = column.sort;
return sortingOption;
}
});
return sortingOption;
}
private static getMinDurationUnitInMilliseconds(durationUnit: string): number {
switch (durationUnit) {
case "hour":
return MillisecondsInAHour;
case "minute":
return MillisecondsInAMinute;
case "second":
return MillisecondsInASecond;
default:
return MillisecondsInADay;
}
}
private static getUniqueMilestones(milestonesDataPoints: MilestoneDataPoint[]) {
const milestonesWithoutDublicates = {};
milestonesDataPoints.forEach((milestone: MilestoneDataPoint) => {
if (milestone.name) {
milestonesWithoutDublicates[milestone.name] = milestone;
}
});
return milestonesWithoutDublicates;
}
private static createMilestones(
dataView: DataView,
host: IVisualHost): MilestoneData {
let milestonesIndex = -1;
for (const index in dataView.categorical.categories) {
const category = dataView.categorical.categories[index];
if (category.source.roles.Milestones) {
milestonesIndex = +index;
}
}
let milestoneData: MilestoneData = {
dataPoints: []
};
const milestonesCategory = dataView.categorical.categories[milestonesIndex];
let milestones: { value: PrimitiveValue, index: number }[] = [];
if (milestonesCategory && milestonesCategory.values) {
milestonesCategory.values.forEach((value: PrimitiveValue, index: number) => milestones.push({ value, index }));
milestones.forEach((milestone) => {
const milestoneObjects = milestonesCategory.objects && milestonesCategory.objects[milestone.index];
const selectionBuilder: ISelectionIdBuilder = host
.createSelectionIdBuilder()
.withCategory(milestonesCategory, milestone.index);
const milestoneDataPoint: MilestoneDataPoint = {
name: milestone.value as string,
identity: selectionBuilder.createSelectionId(),
shapeType: milestoneObjects && milestoneObjects.milestones && milestoneObjects.milestones.shapeType ?
milestoneObjects.milestones.shapeType as string : MilestoneShapeTypes.Rhombus,
color: milestoneObjects && milestoneObjects.milestones && milestoneObjects.milestones.fill ?
(milestoneObjects.milestones as any).fill.solid.color : Gantt.DefaultValues.TaskColor
};
milestoneData.dataPoints.push(milestoneDataPoint);
});
}
return milestoneData;
}
/**
* Create task objects dataView
* @param dataView The data Model.
* @param formatters task attributes represented format.
* @param taskColor Color of task
* @param settings settings of visual
* @param colors colors of groped tasks
* @param host Host object
* @param taskTypes
*/
private static createTasks(
dataView: DataView,
taskTypes: TaskTypes,
host: IVisualHost,
formatters: GanttChartFormatters,
colors: IColorPalette,
settings: GanttSettings,
taskColor: string,
localizationManager: ILocalizationManager,
isEndDateFillled: boolean): Task[] {
let tasks: Task[] = [],
addedParents: string[] = [];
const values: GanttColumns<any> = GanttColumns.getCategoricalValues(dataView);
if (!values.Task) {
return tasks;
}
const colorHelper: ColorHelper = new ColorHelper(colors, Gantt.LegendPropertyIdentifier);
const groupValues: GanttColumns<DataViewValueColumn>[] = GanttColumns.getGroupedValueColumns(dataView);
const sortingOptions: SortingOptions = Gantt.getSortingOptions(dataView);
let collapsedTasks: string[] = JSON.parse(settings.collapsedTasks.list);
let durationUnit: string = settings.general.durationUnit;
let duration: number = settings.general.durationMin;
let taskProgressShow: boolean = settings.taskCompletion.show;
let endDate: Date = null;
values.Task.forEach((categoryValue: PrimitiveValue, index: number) => {
let color: string = taskColor || Gantt.DefaultValues.TaskColor;
let completion: number = 0;
let taskType: TaskTypeMetadata = null;
let wasDowngradeDurationUnit: boolean = false;
let tooltips: VisualTooltipDataItem[] = [];
let stepDurationTransformation: number = 0;
const selectionBuilder: ISelectionIdBuilder = host
.createSelectionIdBuilder()
.withCategory(dataView.categorical.categories[0], index);
if (groupValues) {
groupValues.forEach((group: GanttColumns<DataViewValueColumn>) => {
let maxCompletionFromTasks: number = _.max(values.Completion);
maxCompletionFromTasks = maxCompletionFromTasks > Gantt.ComplectionMax ? Gantt.ComplectionMaxInPercent : Gantt.ComplectionMax;
if (group.Duration && group.Duration.values[index] !== null) {
taskType = _.find(taskTypes.types,
(typeMeta: TaskTypeMetadata) => typeMeta.name === group.Duration.source.groupName);
if (taskType) {
selectionBuilder.withCategory(taskType.selectionColumn, 0);
color = colorHelper.getColorForMeasure(taskType.columnGroup.objects, taskType.name);
}
duration = group.Duration.values[index] > settings.general.durationMin ? group.Duration.values[index] as number : settings.general.durationMin;
if (duration && duration % 1 !== 0) {
durationUnit = DurationHelper.downgradeDurationUnit(durationUnit, duration);
stepDurationTransformation =
GanttDurationUnitType.indexOf(settings.general.durationUnit) - GanttDurationUnitType.indexOf(durationUnit);
duration = DurationHelper.transformDuration(duration, durationUnit, stepDurationTransformation);
wasDowngradeDurationUnit = true;
}
completion = ((group.Completion && group.Completion.values[index])
&& taskProgressShow
&& Gantt.convertToDecimal(group.Completion.values[index] as number, settings.taskCompletion.maxCompletion, maxCompletionFromTasks)) || null;
if (completion !== null) {
if (completion < Gantt.ComplectionMin) {
completion = Gantt.ComplectionMin;
}
if (completion > Gantt.ComplectionMax) {
completion = Gantt.ComplectionMax;
}
}
} else if (group.EndDate && group.EndDate.values[index] !== null) {
taskType = _.find(taskTypes.types,
(typeMeta: TaskTypeMetadata) => typeMeta.name === group.EndDate.source.groupName);
if (taskType) {
selectionBuilder.withCategory(taskType.selectionColumn, 0);
color = colorHelper.getColorForMeasure(taskType.columnGroup.objects, taskType.name);
}
endDate = group.EndDate.values[index] ? group.EndDate.values[index] as Date : null;
if (typeof (endDate) === "string" || typeof (endDate) === "number") {
endDate = new Date(endDate);
}
completion = ((group.Completion && group.Completion.values[index])
&& taskProgressShow
&& Gantt.convertToDecimal(group.Completion.values[index] as number, settings.taskCompletion.maxCompletion, maxCompletionFromTasks)) || null;
if (completion !== null) {
if (completion < Gantt.ComplectionMin) {
completion = Gantt.ComplectionMin;
}
if (completion > Gantt.ComplectionMax) {
completion = Gantt.ComplectionMax;
}
}
}
});
}
const selectionId: powerbi.extensibility.ISelectionId = selectionBuilder.createSelectionId();
const extraInformation: ExtraInformation[] = [];
const resource: string = (values.Resource && values.Resource[index] as string) || "";
const parent: string = (values.Parent && values.Parent[index] as string) || null;
const Milestone: string = (values.Milestones && !_.isEmpty(values.Milestones[index]) && values.Milestones[index]) || null;
const startDate: Date = (values.StartDate && values.StartDate[index]
&& isValidDate(new Date(values.StartDate[index])) && new Date(values.StartDate[index]))
|| new Date(Date.now());
if (values.ExtraInformation) {
const extraInformationKeys: any[] = Object.keys(values.ExtraInformation);
for (const key of extraInformationKeys) {
const value: string = values.ExtraInformation[key][index];
if (value) {
extraInformation.push({
displayName: key,
value: value
});
}
}
}
const task: Task = {
color,
completion,
resource,
index: null,
name: categoryValue as string,
start: startDate,
end: endDate,
parent,
children: null,
visibility: true,
duration,
taskType: taskType && taskType.name,
description: categoryValue as string,
tooltipInfo: tooltips,
selected: false,
identity: selectionId,
extraInformation,
daysOffList: [],
wasDowngradeDurationUnit,
stepDurationTransformation,
Milestones: Milestone && startDate ? [{ type: Milestone, start: startDate, tooltipInfo: null, category: categoryValue as string }] : []
};
if (parent) {
let parentTask: Task = null;
if (addedParents.indexOf(parent) === -1) {
addedParents.push(parent);
parentTask = {
index: 0,
name: parent,
start: null,
duration: null,
completion: null,
resource: null,
end: null,
parent: null,
children: [task],
visibility: true,
taskType: null,
description: null,
color: null,
tooltipInfo: null,
extraInformation: _.includes(collapsedTasks, parent) ? extraInformation : null,
daysOffList: null,
wasDowngradeDurationUnit: null,
selected: null,
identity: selectionBuilder.createSelectionId(),
Milestones: Milestone && startDate ? [{ type: Milestone, start: startDate, tooltipInfo: null, category: categoryValue as string }] : []
};
tasks.push(parentTask);
} else {
parentTask = tasks.filter(x => x.index === 0 && x.name === parent)[0];
parentTask.children.push(task);
}
}
tasks.push(task);
});
Gantt.downgradeDurationUnitIfNeeded(tasks, durationUnit);
if (values.Parent) {
tasks = Gantt.sortTasksWithParents(tasks, sortingOptions);
}
tasks.forEach(task => {
if (task.children && task.children.length) {
return;
}
if (task.end && task.start && isValidDate(task.end)) {
const durationInMilliseconds: number = task.end.getTime() - task.start.getTime(),
minDurationUnitInMilliseconds: number = Gantt.getMinDurationUnitInMilliseconds(durationUnit);
task.end = durationInMilliseconds < minDurationUnitInMilliseconds ? Gantt.getEndDate(durationUnit, task.start, task.duration) : task.end;
} else {
task.end = isValidDate(task.end) ? task.end : Gantt.getEndDate(durationUnit, task.start, task.duration);
}
if (settings.daysOff.show && duration) {
let datesDiff: number = 0;
do {
task.daysOffList = Gantt.calculateDaysOff(
+settings.daysOff.firstDayOfWeek,
new Date(task.start.getTime()),
new Date(task.end.getTime())
);
if (task.daysOffList.length) {
const isDurationFilled: boolean = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.Duration)) !== -1;
if (isDurationFilled) {
let extraDuration = Gantt.calculateExtraDurationDaysOff(task.daysOffList, task.start, task.end, +settings.daysOff.firstDayOfWeek, durationUnit);
task.end = Gantt.getEndDate(durationUnit, task.start, task.duration + extraDuration);
}
const lastDayOffListItem = task.daysOffList[task.daysOffList.length - 1];
const lastDayOff: Date = lastDayOffListItem[1] === 1 ? lastDayOffListItem[0]
: new Date(lastDayOffListItem[0].getFullYear(), lastDayOffListItem[0].getMonth(), lastDayOffListItem[0].getDate() + 1);
datesDiff = Math.ceil((task.end.getTime() - lastDayOff.getTime()) / MillisecondsInADay);
}
} while (task.daysOffList.length && datesDiff - DaysInAWeekend > DaysInAWeek);
}
if (task.parent) {
task.visibility = collapsedTasks.indexOf(task.parent) === -1;
}
});
tasks.forEach((task: Task) => {
if (!task.children || _.includes(collapsedTasks, task.name)) {
task.tooltipInfo = Gantt.getTooltipInfo(task, formatters, durationUnit, localizationManager, isEndDateFillled);
if (task.Milestones) {
task.Milestones.forEach((milestone) => {
const dateFormatted = formatters.startDateFormatter.format(task.start);
const dateTypesSettings = settings.dateType;
milestone.tooltipInfo = Gantt.getTooltipForMilestoneLine(dateFormatted, localizationManager, dateTypesSettings, [milestone.type], [milestone.category]);
});
}
}
});
return tasks;
}
public static sortTasksWithParents(tasks: Task[], sortingOptions: SortingOptions): Task[] {
const sortingFunction = ((a: Task, b: Task) => {
if (a.name < b.name) {
return sortingOptions.sortingDirection === SortDirection.Ascending ? -1 : 1;
}
if (a.name > b.name) {
return sortingOptions.sortingDirection === SortDirection.Ascending ? 1 : -1;
}
return 0;
});
if (sortingOptions.isCustomSortingNeeded) {
tasks.sort(sortingFunction);
}
let index: number = 0;
tasks.forEach(task => {
if (!task.index && !task.parent) {
task.index = index++;
if (task.children) {
if (sortingOptions.isCustomSortingNeeded) {
task.children.sort(sortingFunction);
}
task.children.forEach(subtask => {
subtask.index = subtask.index === null ? index++ : subtask.index;
});
}
}
});
let resultTasks: Task[] = [];
tasks.forEach((task) => {
resultTasks[task.index] = task;
});
return resultTasks;
}
/**
* Calculate days off
* @param daysOffDataForAddition Temporary days off data for addition new one
* @param firstDayOfWeek First day of working week. From settings
* @param date Date for verifying
* @param extraCondition Extra condition for handle special case for last date
*/
private static addNextDaysOff(
daysOffDataForAddition: DaysOffDataForAddition,
firstDayOfWeek: number,
date: Date,
extraCondition: boolean = false): DaysOffDataForAddition {
daysOffDataForAddition.amountOfLastDaysOff = 1;
for (let i = DaysInAWeekend; i > 0; i--) {
let dateForCheck: Date = new Date(date.getTime() + (i * MillisecondsInADay));
let alreadyInDaysOffList = false;
daysOffDataForAddition.list.forEach((item) => {
const itemDate = item[0];
if (itemDate.getFullYear() === date.getFullYear() && itemDate.getMonth() === date.getMonth() && itemDate.getDate() === date.getDate()) {
alreadyInDaysOffList = true;
}
});
const isFirstDaysOfWeek = dateForCheck.getDay() === +firstDayOfWeek;
const isFirstDayOff = dateForCheck.getDay() === (+firstDayOfWeek + 5) % 7;
const isSecondDayOff = dateForCheck.getDay() === (+firstDayOfWeek + 6) % 7;
const isPartlyUsed = !/00\:00\:00/g.test(dateForCheck.toTimeString());
if (!alreadyInDaysOffList && isFirstDaysOfWeek && (!extraCondition || (extraCondition && isPartlyUsed))) {
daysOffDataForAddition.amountOfLastDaysOff = i;
daysOffDataForAddition.list.push([
new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0), i
]);
}
// Example: some task starts on Saturday 8:30 and ends on Thursday 8:30,
// so it has extra duration and now will end on next Saturday 8:30
// --- we need to add days off -- it ends on Monday 8.30
if (!alreadyInDaysOffList && (isFirstDayOff || isSecondDayOff) && isPartlyUsed) {
const amount = isFirstDayOff ? 2 : 1;
daysOffDataForAddition.amountOfLastDaysOff = amount;
daysOffDataForAddition.list.push([
new Date(dateForCheck.getFullYear(), dateForCheck.getMonth(), dateForCheck.getDate(), 0, 0, 0), amount
]);
}
}
return daysOffDataForAddition;
}
/**
* Calculates end date from start date and offset for different durationUnits
* @param durationUnit
* @param start Start date
* @param step An offset
*/
public static getEndDate(durationUnit: string, start: Date, step: number): Date {
switch (durationUnit) {
case DurationUnits.Second.toString():
return d3.timeSecond.offset(start, step);
case DurationUnits.Minute.toString():
return d3.timeMinute.offset(start, step);
case DurationUnits.Hour.toString():
return d3.timeHour.offset(start, step);
default:
return d3.timeDay.offset(start, step);
}
}
private static isDayOff(date: Date, firstDayOfWeek: number): boolean {
const isFirstDayOff = date.getDay() === (+firstDayOfWeek + 5) % 7;
const isSecondDayOff = date.getDay() === (+firstDayOfWeek + 6) % 7;
return isFirstDayOff || isSecondDayOff;
}
private static isOneDay(firstDate: Date, secondDate: Date): boolean {
return firstDate.getMonth() === secondDate.getMonth() && firstDate.getFullYear() === secondDate.getFullYear()
&& firstDate.getDay() === secondDate.getDay();
}
/**
* Calculate days off
* @param firstDayOfWeek First day of working week. From settings
* @param fromDate Start of task
* @param toDate End of task
*/
private static calculateDaysOff(
firstDayOfWeek: number,
fromDate: Date,
toDate: Date): DayOffData[] {
let tempDaysOffData: DaysOffDataForAddition = {
list: [],
amountOfLastDaysOff: 0
};
if (Gantt.isOneDay(fromDate, toDate)) {
if (!Gantt.isDayOff(fromDate, +firstDayOfWeek)) {
return tempDaysOffData.list;
}
}
while (fromDate < toDate) {
Gantt.addNextDaysOff(tempDaysOffData, firstDayOfWeek, fromDate);
fromDate.setDate(fromDate.getDate() + tempDaysOffData.amountOfLastDaysOff);
}
Gantt.addNextDaysOff(tempDaysOffData, firstDayOfWeek, toDate, true);
return tempDaysOffData.list;
}
private static convertMillisecondsToDuration(milliseconds: number, durationUnit: string): number {
switch (durationUnit) {
case DurationUnits.Hour.toString():
return milliseconds /= MillisecondsInAHour;
case DurationUnits.Minute.toString():
return milliseconds /= MillisecondsInAMinute;
case DurationUnits.Second.toString():
return milliseconds /= MillisecondsInASecond;
default:
return milliseconds /= MillisecondsInADay;
}
}
private static calculateExtraDurationDaysOff(daysOffList: DayOffData[], startDate: Date, endDate: Date, firstDayOfWeek: number, durationUnit: string): number {
let extraDuration = 0;
for (let i = 0; i < daysOffList.length; i++) {
const itemAmount = daysOffList[i][1];
extraDuration += itemAmount;
// not to count for neighbour dates
if (itemAmount === 2 && (i + 1) < daysOffList.length) {
const itemDate = daysOffList[i][0].getDate();
const nextDate = daysOffList[i + 1][0].getDate();
if (itemDate + 1 === nextDate) {
i += 2;
}
}
}
// not to add duration twice
if (this.isDayOff(startDate, firstDayOfWeek)) {
let prevDayTimestamp = startDate.getTime();
let prevDate = new Date(prevDayTimestamp);
prevDate.setHours(0, 0, 0);
// in milliseconds
let alreadyAccountedDuration = startDate.getTime() - prevDate.getTime();
alreadyAccountedDuration = Gantt.convertMillisecondsToDuration(alreadyAccountedDuration, durationUnit);
extraDuration = DurationHelper.transformExtraDuration(durationUnit, extraDuration);
extraDuration -= alreadyAccountedDuration;
}
return extraDuration;
}
/**
* Convert the dataView to view model
* @param dataView The data Model
* @param host Host object
* @param colors Color pallete
*/
public static converter(
dataView: DataView,
host: IVisualHost,
colors: IColorPalette,
colorHelper: ColorHelper,
localizationManager: ILocalizationManager): GanttViewModel {
if (!dataView
|| !dataView.categorical
|| !Gantt.isChartHasTask(dataView)
|| dataView.categorical.categories.length === 0) {
return null;
}
const settings: GanttSettings = this.parseSettings(dataView, colorHelper);
const taskTypes: TaskTypes = Gantt.getAllTasksTypes(dataView);
const formatters: GanttChartFormatters = this.getFormatters(dataView, settings, host.locale || null);
const isDurationFilled: boolean = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.Duration)) !== -1,
isEndDateFillled: boolean = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.EndDate)) !== -1,
isParentFilled: boolean = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.Parent)) !== -1,
isResourcesFilled: boolean = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.Resource)) !== -1;
const legendData: LegendData = Gantt.createLegend(host, colors, settings, taskTypes, !isDurationFilled && !isEndDateFillled);
const milestonesData: MilestoneData = Gantt.createMilestones(dataView, host);
let taskColor: string = (legendData.dataPoints.length <= 1) || !isDurationFilled
? settings.taskConfig.fill
: null;
const tasks: Task[] = Gantt.createTasks(dataView, taskTypes, host, formatters, colors, settings, taskColor, localizationManager, isEndDateFillled);
// Remove empty legend if tasks isn't exist
const types = _.groupBy(tasks, x => x.taskType);
legendData.dataPoints = legendData.dataPoints.filter(x => types[x.label]);
return {
dataView,
settings,
taskTypes,
tasks,
legendData,
milestonesData,
isDurationFilled,
isEndDateFillled,
isParentFilled,
isResourcesFilled
};
}
public static parseSettings(dataView: DataView, colorHelper: ColorHelper): GanttSettings {
let settings: GanttSettings = GanttSettings.parse<GanttSettings>(dataView);
if (!colorHelper) {
return settings;
}
if (settings.taskCompletion.maxCompletion < Gantt.ComplectionMin || settings.taskCompletion.maxCompletion > Gantt.ComplectionMaxInPercent) {
settings.taskCompletion.maxCompletion = Gantt.ComplectionDefault;
}
if (colorHelper.isHighContrast) {
settings.dateType.axisColor = colorHelper.getHighContrastColor("foreground", settings.dateType.axisColor);
settings.dateType.axisTextColor = colorHelper.getHighContrastColor("foreground", settings.dateType.axisTextColor);
settings.dateType.todayColor = colorHelper.getHighContrastColor("foreground", settings.dateType.todayColor);
settings.daysOff.fill = colorHelper.getHighContrastColor("foreground", settings.daysOff.fill);
settings.taskConfig.fill = colorHelper.getHighContrastColor("foreground", settings.taskConfig.fill);
settings.taskLabels.fill = colorHelper.getHighContrastColor("foreground", settings.taskLabels.fill);
settings.taskResource.fill = colorHelper.getHighContrastColor("foreground", settings.taskResource.fill);
settings.legend.labelColor = colorHelper.getHighContrastColor("foreground", settings.legend.labelColor);
}
return settings;
}
private static convertToDecimal(value: number, maxCompletionFromSettings: number, maxCompletionFromTasks: number): number {
if (maxCompletionFromSettings) {
return value / maxCompletionFromSettings;
}
return value / maxCompletionFromTasks;
}
/**
* Gets all unique types from the tasks array
* @param dataView The data model.
*/
private static getAllTasksTypes(dataView: DataView): TaskTypes {
const taskTypes: TaskTypes = {
typeName: "",
types: []
};
let index: number = _.findIndex(dataView.metadata.columns, col => col.roles.hasOwnProperty(GanttRoles.Legend));
if (index !== -1) {
taskTypes.typeName = dataView.metadata.columns[index].displayName;
let legendMetaCategoryColumn: DataViewMetadataColumn = dataView.metadata.columns[index];
let values = dataView.categorical && dataView.categorical.values || <DataViewValueColumns>[];
let groupValues = values.grouped();
taskTypes.types = groupValues.map((group: DataViewValueColumnGroup): TaskTypeMetadata => {
let column: DataViewCategoryColumn = {
identity: [group.identity],
source: {
displayName: null,
queryName: legendMetaCategoryColumn.queryName
},
values: null
};
return {
name: group.name as string,
selectionColumn: column,
columnGroup: group
};
});
}
return taskTypes;
}
/**
* Get legend data, calculate position and draw it
*/
private renderLegend(): void {
if (!this.viewModel.legendData) {
return;
}
let position: LegendPosition = this.viewModel.settings.legend.show
? LegendPosition[this.viewModel.settings.legend.position]
: LegendPosition.None;
this.legend.changeOrientation(position);
this.legend.drawLegend(this.viewModel.legendData, _.clone(this.viewport));
LegendModule.positionChartArea(this.ganttDiv, this.legend);
switch (this.legend.getOrientation()) {
case LegendPosition.Left:
case LegendPosition.LeftCenter:
case LegendPosition.Right:
case LegendPosition.RightCenter:
this.viewport.width -= this.legend.getMargins().width;
break;
case LegendPosition.Top:
case LegendPosition.TopCenter:
case LegendPosition.Bottom:
case LegendPosition.BottomCenter:
this.viewport.height -= this.legend.getMargins().height;
break;
}
}
private scaleAxisLength(axisLength: number): number {
let fullScreenAxisLength: number = Gantt.DefaultGraphicWidthPercentage * this.viewport.width;
if (axisLength < fullScreenAxisLength) {
axisLength = fullScreenAxisLength;
}
return axisLength;
}
/**
* Called on data change or resizing
* @param options The visual option that contains the dataview and the viewport
*/
public update(options: VisualUpdateOptions): void {
if (!options || !options.dataViews || !options.dataViews[0]) {
this.clearViewport();
return;
}
this.viewModel = Gantt.converter(options.dataViews[0], this.host, this.colors, this.colorHelper, this.localizationManager);
// for dublicated milestone types
if (this.viewModel && this.viewModel.milestonesData) {
let newMilestoneData: MilestoneData = this.viewModel.milestonesData;
const milestonesWithoutDublicates = Gantt.getUniqueMilestones(newMilestoneData.dataPoints);
newMilestoneData.dataPoints.forEach((dataPoint: MilestoneDataPoint) => {
if (dataPoint.name) {
const theSameUniqDataPoint: MilestoneDataPoint = milestonesWithoutDublicates[dataPoint.name];
dataPoint.color = theSameUniqDataPoint.color;
dataPoint.shapeType = theSameUniqDataPoint.shapeType;
}
});
this.viewModel.milestonesData = newMilestoneData;
}
if (!this.viewModel || !this.viewModel.tasks || this.viewModel.tasks.length <= 0) {
this.clearViewport();
return;
}
this.viewport = _.clone(options.viewport);
this.margin = Gantt.DefaultMargin;
this.eventService.renderingStarted(options);
this.renderLegend();
this.updateChartSize();
const visibleTasks = this.viewModel.tasks
.filter((task: Task) => task.visibility);
const tasks: Task[] = visibleTasks
.map((task: Task, i: number) => {
task.index = i;
return task;
});
if (this.interactivityService) {
this.interactivityService.applySelectionStateToData(tasks);
}
if (tasks.length < Gantt.MinTasks) {
return;
}
let settings = this.viewModel.settings;
this.collapsedTasks = JSON.parse(settings.collapsedTasks.list);
let groupedTasks: GroupedTask[] = this.groupTasks(tasks);
// do smth with task ids
this.updateCommonTasks(groupedTasks);
this.updateCommonMilestones(groupedTasks);
let tasksAfterGrouping: Task[] = [];
groupedTasks.forEach((t: GroupedTask) => tasksAfterGrouping = tasksAfterGrouping.concat(t.tasks));
const minDateTask: Task = _.minBy(tasksAfterGrouping, (t) => t && t.start);
const maxDateTask: Task = _.maxBy(tasksAfterGrouping, (t) => t && t.end);
this.hasNotNullableDates = !!minDateTask && !!maxDateTask;
let axisLength: number = 0;
if (this.hasNotNullableDates) {
let startDate: Date = minDateTask.start;
let endDate: Date = maxDateTask.end;
if (startDate.toString() === endDate.toString()) {
endDate = new Date(endDate.valueOf() + (24 * 60 * 60 * 1000));
}
let dateTypeMilliseconds: number = Gantt.getDateType(settings.dateType.type);
let ticks: number = Math.ceil(Math.round(endDate.valueOf() - startDate.valueOf()) / dateTypeMilliseconds);
ticks = ticks < 2 ? 2 : ticks;
axisLength = ticks * Gantt.DefaultTicksLength;
axisLength = this.scaleAxisLength(axisLength);
let viewportIn: IViewport = {
height: this.viewport.height,
width: axisLength
};
let xAxisProperties: IAxisProperties = this.calculateAxes(viewportIn, this.textProperties, startDate, endDate, ticks, false);
this.timeScale = <timeScale<Date, Date>>xAxisProperties.scale;
this.renderAxis(xAxisProperties);
}
axisLength = this.scaleAxisLength(axisLength);
this.setDimension(groupedTasks, axisLength, settings);
this.renderTasks(groupedTasks);
this.updateTaskLabels(groupedTasks, settings.taskLabels.width);
this.updateElementsPositions(this.margin);
this.createMilestoneLine(groupedTasks);
if (settings.general.scrollToCurrentTime && this.hasNotNullableDates) {
this.scrollToMilestoneLine(axisLength);
}
if (this.interactivityService) {
const behaviorOptions: BehaviorOptions = {
clearCatcher: this.clearCatcher,
taskSelection: this.taskGroup.selectAll(Selectors.SingleTask.selectorName),
legendSelection: this.body.selectAll(Selectors.LegendItems.selectorName),
subTasksCollapse: {
selection: this.body.selectAll(Selectors.ClickableArea.selectorName),
callback: this.subTasksCollapseCb.bind(this)
},
allSubtasksCollapse: {
selection: this.body
.selectAll(Selectors.CollapseAllArrow.selectorName),
callback: this.subTasksCollapseAll.bind(this)
},
interactivityService: this.interactivityService,
behavior: this.behavior,
dataPoints: tasks
};
this.interactivityService.bind(behaviorOptions);
this.behavior.renderSelection(false);
}
this.eventService.renderingFinished(options);
}
private static getDateType(dateType: DateTypes): number {
switch (dateType) {
case DateTypes.Second:
return MillisecondsInASecond;
case DateTypes.Minute:
return MillisecondsInAMinute;
case DateTypes.Hour:
return MillisecondsInAHour;
case DateTypes.Day:
return MillisecondsInADay;
case DateTypes.Week:
return MillisecondsInWeek;
case DateTypes.Month:
return MillisecondsInAMonth;
case DateTypes.Quarter:
return MillisecondsInAQuarter;
case DateTypes.Year:
return MillisecondsInAYear;
default:
return MillisecondsInWeek;
}
}
private calculateAxes(
viewportIn: IViewport,
textProperties: TextProperties,
startDate: Date,
endDate: Date,
ticksCount: number,
scrollbarVisible: boolean): IAxisProperties {
let dataTypeDatetime: ValueType = ValueType.fromPrimitiveTypeAndCategory(PrimitiveType.Date);
let category: DataViewMetadataColumn = {
displayName: this.localizationManager.getDisplayName("Role_StartDate"),
queryName: GanttRoles.StartDate,
type: dataTypeDatetime,
index: 0
};
let visualOptions: GanttCalculateScaleAndDomainOptions = {
viewport: viewportIn,
margin: this.margin,
forcedXDomain: [startDate, endDate],
forceMerge: false,
showCategoryAxisLabel: false,
showValueAxisLabel: false,
categoryAxisScaleType: axisScale.linear,
valueAxisScaleType: null,
valueAxisDisplayUnits: 0,
categoryAxisDisplayUnits: 0,
trimOrdinalDataOnOverflow: false,
forcedTickCount: ticksCount
};
const width: number = viewportIn.width;
let axes: IAxisProperties = this.calculateAxesProperties(viewportIn, visualOptions, category);
axes.willLabelsFit = AxisHelper.LabelLayoutStrategy.willLabelsFit(
axes,
width,
textMeasurementService.measureSvgTextWidth,
textProperties);
// If labels do not fit and we are not scrolling, try word breaking
axes.willLabelsWordBreak = (!axes.willLabelsFit && !scrollbarVisible) && AxisHelper.LabelLayoutStrategy.willLabelsWordBreak(
axes, this.margin, width, textMeasurementService.measureSvgTextWidth,
textMeasurementService.estimateSvgTextHeight, textMeasurementService.getTailoredTextOrDefault,
textProperties);
return axes;
}
private calculateAxesProperties(
viewportIn: IViewport,
options: GanttCalculateScaleAndDomainOptions,
metaDataColumn: DataViewMetadataColumn): IAxisProperties {
const dateType: DateTypes = this.viewModel.settings.dateType.type;
const cultureSelector: string = this.host.locale;
let xAxisDateFormatter: IValueFormatter = ValueFormatter.create({
format: Gantt.DefaultValues.DateFormatStrings[dateType],
cultureSelector
});
let xAxisProperties: IAxisProperties = AxisHelper.createAxis({
pixelSpan: viewportIn.width,
dataDomain: options.forcedXDomain,
metaDataColumn: metaDataColumn,
formatString: Gantt.DefaultValues.DateFormatStrings[dateType],
outerPadding: 0,
isScalar: true,
isVertical: false,
forcedTickCount: options.forcedTickCount,
useTickIntervalForDisplayUnits: true,
isCategoryAxis: true,
getValueFn: (index) => {
return xAxisDateFormatter.format(new Date(index));
},
scaleType: options.categoryAxisScaleType,
axisDisplayUnits: options.categoryAxisDisplayUnits,
});
xAxisProperties.axisLabel = metaDataColumn.displayName;
return xAxisProperties;
}
private setDimension(
groupedTasks: GroupedTask[],
axisLength: number,
settings: GanttSettings): void {
const fullResourceLabelMargin = groupedTasks.length * this.getResourceLabelTopMargin();
let widthBeforeConvertion = this.margin.left + settings.taskLabels.width + axisLength;
if (settings.taskResource.show && settings.taskResource.position === ResourceLabelPositions.Right) {
widthBeforeConvertion += Gantt.DefaultValues.ResourceWidth;
} else {
widthBeforeConvertion += Gantt.DefaultValues.ResourceWidth / 2;
}
const height = PixelConverter.toString(groupedTasks.length * (settings.taskConfig.height || DefaultChartLineHeight) + this.margin.top + fullResourceLabelMargin);
const width = PixelConverter.toString(widthBeforeConvertion);
this.ganttSvg
.attr("height", height)
.attr("width", width);
}
private groupTasks(tasks: Task[]): GroupedTask[] {
if (this.viewModel.settings.general.groupTasks) {
let groupedTasks: _.Dictionary<Task[]> = _.groupBy(tasks,
x => (x.parent ? `${x.parent}.${x.name}` : x.name));
let result: GroupedTask[] = [];
const taskKeys: string[] = Object.keys(groupedTasks);
let alreadyReviewedKeys: string[] = [];
taskKeys.forEach((key: string) => {
const isKeyAlreadyReviewed = _.includes(alreadyReviewedKeys, key);
if (!isKeyAlreadyReviewed) {
let name: string = key;
if (groupedTasks[key] && groupedTasks[key].length && groupedTasks[key][0].parent && key.indexOf(groupedTasks[key][0].parent) !== -1) {
name = key.substr(groupedTasks[key][0].parent.length + 1, key.length);
}
// add current task
const taskRecord = <GroupedTask>{
name,
tasks: groupedTasks[key]
};
result.push(taskRecord);
alreadyReviewedKeys.push(key);
// see all the children and add them
groupedTasks[key].forEach((task: Task) => {
if (task.children && !_.includes(this.collapsedTasks, task.name)) {
task.children.forEach((childrenTask: Task) => {
const childrenFullName = `${name}.${childrenTask.name}`;
const isChildrenKeyAlreadyReviewed = _.includes(alreadyReviewedKeys, childrenFullName);
if (!isChildrenKeyAlreadyReviewed) {
const childrenRecord = <GroupedTask>{
name: childrenTask.name,
tasks: groupedTasks[childrenFullName]
};
result.push(childrenRecord);
alreadyReviewedKeys.push(childrenFullName);
}
});
}
});
}
});
result.forEach((x, i) => {
x.tasks.forEach(t => t.index = i);
x.index = i;
});
return result;
}
return tasks.map(x => <GroupedTask>{
name: x.name,
index: x.index,
tasks: [x]
});
}
private renderAxis(xAxisProperties: IAxisProperties, duration: number = Gantt.DefaultDuration): void {
const axisColor: string = this.viewModel.settings.dateType.axisColor;
const axisTextColor: string = this.viewModel.settings.dateType.axisTextColor;
let xAxis = xAxisProperties.axis;
this.axisGroup.call(xAxis.tickSizeOuter(xAxisProperties.outerPadding));
this.axisGroup
.transition()
.duration(duration)
.call(xAxis);
this.axisGroup
.selectAll("path")
.style("stroke", axisColor);
this.axisGroup
.selectAll(".tick line")
.style("stroke", (timestamp: number) => this.setTickColor(timestamp, axisColor));
this.axisGroup
.selectAll(".tick text")
.style("fill", (timestamp: number) => this.setTickColor(timestamp, axisTextColor));
}
private setTickColor(
timestamp: number,
defaultColor: string): string {
const tickTime = new Date(timestamp);
const firstDayOfWeek: string = this.viewModel.settings.daysOff.firstDayOfWeek;
const color: string = this.viewModel.settings.daysOff.fill;
if (this.viewModel.settings.daysOff.show) {
let dateForCheck: Date = new Date(tickTime.getTime());
for (let i = 0; i <= DaysInAWeekend; i++) {
if (dateForCheck.getDay() === +firstDayOfWeek) {
return !i
? defaultColor
: color;
}
dateForCheck.setDate(dateForCheck.getDate() + 1);
}
}
return defaultColor;
}
/**
* Update task labels and add its tooltips
* @param tasks All tasks array
* @param width The task label width
*/
private updateTaskLabels(
tasks: GroupedTask[],
width: number): void {
let axisLabel: Selection<any>;
let taskLabelsShow: boolean = this.viewModel.settings.taskLabels.show;
let displayGridLines: boolean = this.viewModel.settings.general.displayGridLines;
let taskLabelsColor: string = this.viewModel.settings.taskLabels.fill;
let taskLabelsFontSize: number = this.viewModel.settings.taskLabels.fontSize;
let taskLabelsWidth: number = this.viewModel.settings.taskLabels.width;
let taskConfigHeight: number = this.viewModel.settings.taskConfig.height || DefaultChartLineHeight;
const categoriesAreaBackgroundColor: string = this.colorHelper.getThemeColor();
const isHighContrast: boolean = this.colorHelper.isHighContrast;
if (taskLabelsShow) {
this.lineGroupWrapper
.attr("width", taskLabelsWidth)
.attr("fill", isHighContrast ? categoriesAreaBackgroundColor : Gantt.DefaultValues.TaskCategoryLabelsRectColor)
.attr("stroke", this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.TaskLineColor))
.attr("stroke-width", 1);
this.lineGroup
.selectAll(Selectors.Label.selectorName)
.remove();
axisLabel = this.lineGroup
.selectAll(Selectors.Label.selectorName)
.data(tasks);
let axisLabelGroup = axisLabel
.enter()
.append("g")
.merge(axisLabel);
axisLabelGroup.classed(Selectors.Label.className, true)
.attr("transform", (task: GroupedTask) => SVGManipulations.translate(0, this.margin.top + this.getTaskLabelCoordinateY(task.index)));
const clickableArea = axisLabelGroup
.append("g")
.classed(Selectors.ClickableArea.className, true)
.merge(axisLabelGroup);
clickableArea
.append("text")
.attr("x", (task: GroupedTask) => (Gantt.TaskLineCoordinateX +
(_.every(task.tasks, (task: Task) => !!task.parent)
? Gantt.SubtasksLeftMargin
: (task.tasks[0].children && !!task.tasks[0].children.length) ? this.parentLabelOffset : 0)))
.attr("class", (task: GroupedTask) => task.tasks[0].children ? "parent" : task.tasks[0].parent ? "child" : "normal-node")
.attr("y", (task: GroupedTask) => (task.index + 0.5) * this.getResourceLabelTopMargin())
.attr("fill", taskLabelsColor)
.attr("stroke-width", Gantt.AxisLabelStrokeWidth)
.style("font-size", PixelConverter.fromPoint(taskLabelsFontSize))
.text((task: GroupedTask) => task.name)
.call(AxisHelper.LabelLayoutStrategy.clip, width - Gantt.AxisLabelClip, textMeasurementService.svgEllipsis)
.append("title")
.text((task: GroupedTask) => task.name);
const buttonSelection = clickableArea
.filter((task: GroupedTask) => task.tasks[0].children && !!task.tasks[0].children.length)
.append("svg")
.attr("viewBox", "0 0 32 32")
.attr("width", Gantt.DefaultValues.IconWidth)
.attr("height", Gantt.DefaultValues.IconHeight)
.attr("y", (task: GroupedTask) => (task.index + 0.5) * this.getResourceLabelTopMargin() - Gantt.DefaultValues.IconMargin)
.attr("x", Gantt.DefaultValues.BarMargin);
clickableArea
.append("rect")
.attr("width", 2 * Gantt.DefaultValues.IconWidth)
.attr("height", 2 * Gantt.DefaultValues.IconWidth)
.attr("y", (task: GroupedTask) => (task.index + 0.5) * this.getResourceLabelTopMargin() - Gantt.DefaultValues.IconMargin)
.attr("x", Gantt.DefaultValues.BarMargin)
.attr("fill", "transparent");
const buttonPlusMinusColor = this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.PlusMinusColor);
buttonSelection
.each(function (task: GroupedTask) {
let element = d3.select(this);
if (!task.tasks[0].children[0].visibility) {
drawPlusButton(element, buttonPlusMinusColor);
} else {
drawMinusButton(element, buttonPlusMinusColor);
}
});
let parentTask: string = "";
let childrenCount = 0;
let currentChildrenIndex = 0;
axisLabelGroup
.append("rect")
.attr("x", (task: GroupedTask) => {
const isGrouped = this.viewModel.settings.general.groupTasks;
const drawStandartMargin: boolean = !task.tasks[0].parent || task.tasks[0].parent && task.tasks[0].parent !== parentTask;
parentTask = task.tasks[0].parent ? task.tasks[0].parent : task.tasks[0].name;
if (task.tasks[0].children) {
parentTask = task.tasks[0].name;
childrenCount = isGrouped ? _.uniqBy(task.tasks[0].children, "name").length : task.tasks[0].children.length;
currentChildrenIndex = 0;
}
if (task.tasks[0].parent === parentTask) {
currentChildrenIndex++;
}
const isLastChild = childrenCount && childrenCount === currentChildrenIndex;
return drawStandartMargin || isLastChild ? Gantt.DefaultValues.ParentTaskLeftMargin : Gantt.DefaultValues.ChildTaskLeftMargin;
})
.attr("y", (task: GroupedTask) => (task.index + 1) * this.getResourceLabelTopMargin() + (taskConfigHeight - this.viewModel.settings.taskLabels.fontSize) / 2)
.attr("width", () => displayGridLines ? this.viewport.width : 0)
.attr("height", 1)
.attr("fill", this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.TaskLineColor));
axisLabel
.exit()
.remove();
this.collapseAllGroup
.selectAll("svg")
.remove();
this.collapseAllGroup
.selectAll("rect")
.remove();
this.collapseAllGroup
.selectAll("text")
.remove();
if (this.viewModel.isParentFilled) {
let categoryLabelsWidth: number = this.viewModel.settings.taskLabels.width;
this.collapseAllGroup
.append("rect")
.attr("width", categoryLabelsWidth)
.attr("height", 2 * Gantt.TaskLabelsMarginTop)
.attr("fill", categoriesAreaBackgroundColor);
const expandCollapseButton = this.collapseAllGroup
.append("svg")
.classed(Selectors.CollapseAllArrow.className, true)
.attr("viewBox", "0 0 48 48")
.attr("width", this.groupLabelSize)
.attr("height", this.groupLabelSize)
.attr("x", 0)
.attr("y", this.secondExpandAllIconOffset)
.attr(this.collapseAllFlag, (this.collapsedTasks.length ? "1" : "0"));
expandCollapseButton
.append("rect")
.attr("width", this.groupLabelSize)
.attr("height", this.groupLabelSize)
.attr("x", 0)
.attr("y", this.secondExpandAllIconOffset)
.attr("fill", "transparent");
const buttonExpandCollapseColor = this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.CollapseAllColor);
if (this.collapsedTasks.length) {
drawExpandButton(expandCollapseButton, buttonExpandCollapseColor);
} else {
drawCollapseButton(expandCollapseButton, buttonExpandCollapseColor);
}
this.collapseAllGroup
.append("text")
.attr("x", this.secondExpandAllIconOffset + this.groupLabelSize)
.attr("y", this.groupLabelSize)
.attr("font-size", "12px")
.attr("fill", this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.CollapseAllTextColor))
.text(this.collapsedTasks.length ? "Expand All" : "Collapse All");
}
} else {
this.lineGroupWrapper
.attr("width", 0)
.attr("fill", "transparent");
this.collapseAllGroup
.selectAll("image")
.remove();
this.collapseAllGroup
.selectAll("rect")
.remove();
this.collapseAllGroup
.selectAll("text")
.remove();
this.lineGroup
.selectAll(Selectors.Label.selectorName)
.remove();
}
}
/**
* callback for subtasks click event
* @param taskClicked Grouped clicked task
*/
private subTasksCollapseCb(taskClicked: GroupedTask): void {
const taskIsChild: boolean = taskClicked.tasks[0].parent && !taskClicked.tasks[0].children;
const taskWithoutParentAndChildren: boolean = !taskClicked.tasks[0].parent && !taskClicked.tasks[0].children;
if (taskIsChild || taskWithoutParentAndChildren) {
return;
}
const taskClickedParent: string = taskClicked.tasks[0].parent || taskClicked.tasks[0].name;
this.viewModel.tasks.forEach((task: Task) => {
if (task.parent === taskClickedParent &&
task.parent.length >= taskClickedParent.length) {
const index: number = this.collapsedTasks.indexOf(task.parent);
if (task.visibility) {
this.collapsedTasks.push(task.parent);
} else {
if (taskClickedParent === task.parent) {
this.collapsedTasks.splice(index, 1);
}
}
}
});
this.setJsonFiltersValues(this.collapsedTasks);
}
/**
* callback for subtasks collapse all click event
*/
private subTasksCollapseAll(): void {
const collapsedAllSelector = this.collapseAllGroup.select(Selectors.CollapseAllArrow.selectorName);
const isCollapsed: string = collapsedAllSelector.attr(this.collapseAllFlag);
const buttonExpandCollapseColor = this.colorHelper.getHighContrastColor("foreground", Gantt.DefaultValues.CollapseAllColor);
collapsedAllSelector.selectAll("path").remove();
if (isCollapsed === "1") {
this.collapsedTasks = [];
collapsedAllSelector.attr(this.collapseAllFlag, "0");
drawCollapseButton(collapsedAllSelector, buttonExpandCollapseColor);
} else {
collapsedAllSelector.attr(this.collapseAllFlag, "1");
drawExpandButton(collapsedAllSelector, buttonExpandCollapseColor);
this.viewModel.tasks.forEach((task: Task) => {
if (task.parent) {
if (task.visibility) {
this.collapsedTasks.push(task.parent);
}
}
});
}
this.setJsonFiltersValues(this.collapsedTasks);
}
private setJsonFiltersValues(collapsedValues: string[]) {
this.host.persistProperties(<VisualObjectInstancesToPersist>{
merge: [{
objectName: "collapsedTasks",
selector: null,
properties: {
list: JSON.stringify(this.collapsedTasks)
}
}]
});
}
/**
* Render tasks
* @param groupedTasks Grouped tasks
*/
private renderTasks(groupedTasks: GroupedTask[]): void {
let taskConfigHeight: number = this.viewModel.settings.taskConfig.height || DefaultChartLineHeight;
let taskGroupSelection: Selection<any> = this.taskGroup
.selectAll(Selectors.TaskGroup.selectorName)
.data(groupedTasks);
taskGroupSelection
.exit()
.remove();
// render task group container
const taskGroupSelectionMerged = taskGroupSelection
.enter()
.append("g")
.merge(taskGroupSelection);
taskGroupSelectionMerged.classed(Selectors.TaskGroup.className, true);
let taskSelection: Selection<Task> = this.taskSelectionRectRender(taskGroupSelectionMerged);
this.taskMainRectRender(taskSelection, taskConfigHeight);
this.MilestonesRender(taskSelection, taskConfigHeight);
this.taskProgressRender(taskSelection);
this.taskDaysOffRender(taskSelection, taskConfigHeight);
this.taskResourceRender(taskSelection, taskConfigHeight);
this.renderTooltip(taskSelection);
}
/**
* Change task structure to be able for
* Rendering common tasks when all the children of current parent are collapsed
* used only the Grouping mode is OFF
* @param groupedTasks Grouped tasks
*/
private updateCommonTasks(groupedTasks: GroupedTask[]): void {
if (!this.viewModel.settings.general.groupTasks) {
groupedTasks.forEach((groupedTask: GroupedTask) => {
const currentTaskName: string = groupedTask.name;
if (_.includes(this.collapsedTasks, currentTaskName)) {
const firstTask: Task = groupedTask.tasks && groupedTask.tasks[0];
const tasks = groupedTask.tasks;
tasks.forEach((task: Task) => {
if (task.children) {
const childrenColors = task.children.map((child: Task) => child.color).filter((color) => color);
const minChildDateStart = _.min(task.children.map((child: Task) => child.start).filter((dateStart) => dateStart));
const maxChildDateEnd = _.max(task.children.map((child: Task) => child.end).filter((dateStart) => dateStart));
firstTask.color = !firstTask.color && task.children ? childrenColors[0] : firstTask.color;
firstTask.start = _.min([firstTask.start, minChildDateStart]);
firstTask.end = <any>_.max([firstTask.end, maxChildDateEnd]);
}
});
groupedTask.tasks = firstTask && [firstTask] || [];
}
});
}
}
/**
* Change task structure to be able for
* Rendering common milestone when all the children of current parent are collapsed
* used only the Grouping mode is OFF
* @param groupedTasks Grouped tasks
*/
private updateCommonMilestones(groupedTasks: GroupedTask[]): void {
groupedTasks.forEach((groupedTask: GroupedTask) => {
const currentTaskName: string = groupedTask.name;
if (_.includes(this.collapsedTasks, currentTaskName)) {
const lastTask: Task = groupedTask.tasks && groupedTask.tasks[groupedTask.tasks.length - 1];
const tasks = groupedTask.tasks;
tasks.forEach((task: Task) => {
if (task.children) {
task.children.map((child: Task) => {
if (!_.isEmpty(child.Milestones)) {
lastTask.Milestones = lastTask.Milestones.concat(child.Milestones);
}
});
}
});
}
});
}
/**
* Render task progress rect
* @param taskGroupSelection Task Group Selection
*/
private taskSelectionRectRender(taskGroupSelection: Selection<any>) {
let taskSelection: Selection<Task> = taskGroupSelection
.selectAll(Selectors.SingleTask.selectorName)
.data((d: GroupedTask) => d.tasks);
taskSelection
.exit()
.remove();
const taskSelectionMerged = taskSelection
.enter()
.append("g")
.merge(taskSelection);
taskSelectionMerged.classed(Selectors.SingleTask.className, true);
return taskSelectionMerged;
}
/**
* @param task
*/
private getTaskRectWidth(task: Task): number {
const taskIsCollapsed = _.includes(this.collapsedTasks, task.name);
return this.hasNotNullableDates && (taskIsCollapsed || _.isEmpty(task.Milestones)) ? this.taskDurationToWidth(task.start, task.end) : 0;
}
/**
*
* @param task
* @param taskConfigHeight
*/
private drawTaskRect(task: Task, taskConfigHeight: number): string {
const x = this.hasNotNullableDates ? this.timeScale(task.start) : 0,
y = Gantt.getBarYCoordinate(task.index, taskConfigHeight) + (task.index + 1) * this.getResourceLabelTopMargin(),
width = this.getTaskRectWidth(task),
height = Gantt.getBarHeight(taskConfigHeight),
radius = Gantt.RectRound;
if (width < 2 * radius) {
return drawNotRoundedRectByPath(x, y, width, height);
}
return drawRoundedRectByPath(x, y, width + Gantt.RectRound, height, radius);
}
/**
* Render task progress rect
* @param taskSelection Task Selection
* @param taskConfigHeight Task heights from settings
*/
private taskMainRectRender(
taskSelection: Selection<Task>,
taskConfigHeight: number): void {
const highContrastModeTaskRectStroke: number = 1;
let taskRect: Selection<Task> = taskSelection
.selectAll(Selectors.TaskRect.selectorName)
.data((d: Task) => [d]);
const taskRectMerged = taskRect
.enter()
.append("path")
.merge(taskRect);
taskRectMerged.classed(Selectors.TaskRect.className, true);
let index = 0, groupedTaskIndex = 0;
taskRectMerged
.attr("d", (task: Task) => this.drawTaskRect(task, taskConfigHeight))
.attr("width", (task: Task) => this.getTaskRectWidth(task))
.style("fill", (task: Task) => {
// logic used for grouped tasks, when there are several bars related to one category
if (index === task.index) {
groupedTaskIndex++;
} else {
groupedTaskIndex = 0;
index = task.index;
}
const url = `${task.index}-${groupedTaskIndex}-${isStringNotNullEmptyOrUndefined(task.taskType) ? task.taskType.toString() : "taskType"}`;
const encodedUrl = `task${hashCode(url)}`;
return `url(#${encodedUrl})`;
});
if (this.colorHelper.isHighContrast) {
taskRectMerged
.style("stroke", (task: Task) => this.colorHelper.getHighContrastColor("foreground", task.color))
.style("stroke-width", highContrastModeTaskRectStroke);
}
taskRect
.exit()
.remove();
}
/**
*
* @param milestoneType milestone type
*/
private getMilestoneColor(milestoneType: string): string {
const milestone: MilestoneDataPoint = this.viewModel.milestonesData.dataPoints.filter((dataPoint: MilestoneDataPoint) => dataPoint.name === milestoneType)[0];
return this.colorHelper.getHighContrastColor("foreground", milestone.color);
}
private getMilestonePath(milestoneType: string, taskConfigHeight: number): string {
let shape: string;
const convertedHeight: number = Gantt.getBarHeight(taskConfigHeight);
const milestone: MilestoneDataPoint = this.viewModel.milestonesData.dataPoints.filter((dataPoint: MilestoneDataPoint) => dataPoint.name === milestoneType)[0];
switch (milestone.shapeType) {
case MilestoneShapeTypes.Rhombus:
shape = drawDiamond(convertedHeight);
break;
case MilestoneShapeTypes.Square:
shape = drawRectangle(convertedHeight);
break;
case MilestoneShapeTypes.Circle:
shape = drawCircle(convertedHeight);
}
return shape;
}
/**
* Render milestones
* @param taskSelection Task Selection
* @param taskConfigHeight Task heights from settings
*/
private MilestonesRender(
taskSelection: Selection<Task>,
taskConfigHeight: number): void {
let taskMilestones: Selection<any> = taskSelection
.selectAll(Selectors.TaskMilestone.selectorName)
.data((d: Task) => {
const nestedByDate = d3.nest().key((d: Milestone) => d.start.toDateString()).entries(d.Milestones);
let updatedMilestones: MilestonePath[] = nestedByDate.map((nestedObj) => {
const oneDateMilestones = nestedObj.values;
// if there 2 or more milestones for concrete date => draw only one milestone for concrete date, but with tooltip for all of them
let currentMilestone = [...oneDateMilestones].pop();
const allTooltipInfo = oneDateMilestones.map((milestone: MilestonePath) => milestone.tooltipInfo);
currentMilestone.tooltipInfo = allTooltipInfo.reduce((a, b) => a.concat(b), []);
return {
type: currentMilestone.type,
start: currentMilestone.start,
taskID: d.index,
tooltipInfo: currentMilestone.tooltipInfo
};
});
return [{
key: d.index, values: <MilestonePath[]>updatedMilestones
}];
});
taskMilestones
.exit()
.remove();
const taskMilestonesAppend = taskMilestones
.enter()
.append("g");
const taskMilestonesMerged = taskMilestonesAppend
.merge(taskMilestones);
taskMilestonesMerged.classed(Selectors.TaskMilestone.className, true);
const transformForMilestone = (id: number, start: Date) => {
return SVGManipulations.translate(this.timeScale(start) - Gantt.getBarHeight(taskConfigHeight) / 4, Gantt.getBarYCoordinate(id, taskConfigHeight) + (id + 1) * this.getResourceLabelTopMargin());
};
let taskMilestonesSelection = taskMilestonesMerged.selectAll("path");
let taskMilestonesSelectionData = taskMilestonesSelection.data(milestonesData => <MilestonePath[]>milestonesData.values);
// add milestones: for collapsed task may be several milestones of its children, in usual case - just 1 milestone
let taskMilestonesSelectionAppend = taskMilestonesSelectionData.enter()
.append("path");
taskMilestonesSelectionData
.exit()
.remove();
let taskMilestonesSelectionMerged = taskMilestonesSelectionAppend
.merge(<any>taskMilestonesSelection);
if (this.hasNotNullableDates) {
taskMilestonesSelectionMerged
.attr("d", (data: MilestonePath) => this.getMilestonePath(data.type, taskConfigHeight))
.attr("transform", (data: MilestonePath) => transformForMilestone(data.taskID, data.start))
.attr("fill", (data: MilestonePath) => this.getMilestoneColor(data.type));
}
this.renderTooltip(taskMilestonesSelectionMerged);
}
/**
* Render days off rects
* @param taskSelection Task Selection
* @param taskConfigHeight Task heights from settings
*/
private taskDaysOffRender(
taskSelection: Selection<Task>,
taskConfigHeight: number): void {
const taskDaysOffColor: string = this.viewModel.settings.daysOff.fill;
const taskDaysOffShow: boolean = this.viewModel.settings.daysOff.show;
taskSelection
.selectAll(Selectors.TaskDaysOff.selectorName)
.remove();
if (taskDaysOffShow) {
let tasksDaysOff: Selection<TaskDaysOff, Task> = taskSelection
.selectAll(Selectors.TaskDaysOff.selectorName)
.data((d: Task) => {
let tasksDaysOff: TaskDaysOff[] = [];
if (!d.children && d.daysOffList) {
for (let i = 0; i < d.daysOffList.length; i++) {
let currentDaysOffItem = d.daysOffList[i];
let startOfLastDay = new Date(+d.end);
startOfLastDay.setHours(0, 0, 0);
if (currentDaysOffItem[0].getTime() < startOfLastDay.getTime()) {
tasksDaysOff.push({
id: d.index,
daysOff: d.daysOffList[i]
});
}
}
}
return tasksDaysOff;
});
const tasksDaysOffMerged = tasksDaysOff
.enter()
.append("path")
.merge(tasksDaysOff);
tasksDaysOffMerged.classed(Selectors.TaskDaysOff.className, true);
const getTaskRectDaysOffWidth = (task: TaskDaysOff) => {
let width = 0;
if (this.hasNotNullableDates) {
const startDate: Date = task.daysOff[0];
const startTime: number = startDate.getTime();
const endDate: Date = new Date(startTime + (task.daysOff[1] * MillisecondsInADay));
width = this.taskDurationToWidth(startDate, endDate);
}
return width;
};
const drawTaskRectDaysOff = (task: TaskDaysOff) => {
let x = this.hasNotNullableDates ? this.timeScale(task.daysOff[0]) : 0,
y = Gantt.getBarYCoordinate(task.id, taskConfigHeight) + (task.id + 1) * this.getResourceLabelTopMargin(),
height = Gantt.getBarHeight(taskConfigHeight),
radius = Gantt.RectRound,
width = getTaskRectDaysOffWidth(task);
if (width < radius) {
x = x - width / 2;
}
if (width < 2 * radius) {
return drawNotRoundedRectByPath(x, y, width, height);
}
return drawRoundedRectByPath(x, y, width, height, radius);
};
tasksDaysOffMerged
.attr("d", (task: TaskDaysOff) => drawTaskRectDaysOff(task))
.style("fill", taskDaysOffColor)
.attr("width", (task: TaskDaysOff) => getTaskRectDaysOffWidth(task));
tasksDaysOff
.exit()
.remove();
}
}
/**
* Render task progress rect
* @param taskSelection Task Selection
*/
private taskProgressRender(
taskSelection: Selection<Task>): void {
const taskProgressShow: boolean = this.viewModel.settings.taskCompletion.show;
let index = 0, groupedTaskIndex = 0;
let taskProgress: Selection<any> = taskSelection
.selectAll(Selectors.TaskProgress.selectorName)
.data((d: Task, i: number) => {
const taskProgressPercentage = this.getDaysOffTaskProgressPercent(d);
// logic used for grouped tasks, when there are several bars related to one category
if (index === d.index) {
groupedTaskIndex++;
} else {
groupedTaskIndex = 0;
index = d.index;
}
const url = `${d.index}-${groupedTaskIndex}-${isStringNotNullEmptyOrUndefined(d.taskType) ? d.taskType.toString() : "taskType"}`;
const encodedUrl = `task${hashCode(url)}`;
return [{
key: encodedUrl, values: <LinearStop[]>[
{ completion: 0, color: d.color },
{ completion: taskProgressPercentage, color: d.color },
{ completion: taskProgressPercentage, color: d.color },
{ completion: 1, color: d.color }
]
}];
});
const taskProgressMerged = taskProgress
.enter()
.append("linearGradient")
.merge(taskProgress);
taskProgressMerged.classed(Selectors.TaskProgress.className, true);
taskProgressMerged
.attr("id", (data) => data.key);
let stopsSelection = taskProgressMerged.selectAll("stop");
let stopsSelectionData = stopsSelection.data(gradient => <LinearStop[]>gradient.values);
// draw 4 stops: 1st and 2d stops are for completed rect part; 3d and 4th ones - for main rect
stopsSelectionData.enter()
.append("stop")
.merge(<any>stopsSelection)
.attr("offset", (data: LinearStop) => `${data.completion * 100}%`)
.attr("stop-color", (data: LinearStop) => this.colorHelper.getHighContrastColor("foreground", data.color))
.attr("stop-opacity", (data: LinearStop, index: number) => (index > 1) && taskProgressShow ? Gantt.NotCompletedTaskOpacity : Gantt.TaskOpacity);
taskProgress
.exit()
.remove();
}
/**
* Render task resource labels
* @param taskSelection Task Selection
* @param taskConfigHeight Task heights from settings
*/
private taskResourceRender(
taskSelection: Selection<Task>,
taskConfigHeight: number): void {
const groupTasks: boolean = this.viewModel.settings.general.groupTasks;
let newLabelPosition: ResourceLabelPositions | null = null;
if (groupTasks && !this.groupTasksPrevValue) {
newLabelPosition = ResourceLabelPositions.Inside;
}
if (!groupTasks && this.groupTasksPrevValue) {
newLabelPosition = ResourceLabelPositions.Right;
}
if (newLabelPosition) {
this.host.persistProperties(<VisualObjectInstancesToPersist>{
merge: [{
objectName: "taskResource",
selector: null,
properties: { position: newLabelPosition }
}]
});
this.viewModel.settings.taskResource.position = newLabelPosition;
newLabelPosition = null;
}
this.groupTasksPrevValue = groupTasks;
const isResourcesFilled: boolean = this.viewModel.isResourcesFilled;
const taskResourceShow: boolean = this.viewModel.settings.taskResource.show;
const taskResourceColor: string = this.viewModel.settings.taskResource.fill;
const taskResourceFontSize: number = this.viewModel.settings.taskResource.fontSize;
const taskResourcePosition: ResourceLabelPositions = this.viewModel.settings.taskResource.position;
const taskResourceFullText: boolean = this.viewModel.settings.taskResource.fullText;
const taskResourceWidthByTask: boolean = this.viewModel.settings.taskResource.widthByTask;
const isGroupedByTaskName: boolean = this.viewModel.settings.general.groupTasks;
if (isResourcesFilled && taskResourceShow) {
let taskResource: Selection<Task> = taskSelection
.selectAll(Selectors.TaskResource.selectorName)
.data((d: Task) => [d]);
const taskResourceMerged = taskResource
.enter()
.append("text")
.merge(taskResource);
taskResourceMerged.classed(Selectors.TaskResource.className, true);
taskResourceMerged
.attr("x", (task: Task) => this.getResourceLabelXCoordinate(task, taskConfigHeight, taskResourceFontSize, taskResourcePosition))
.attr("y", (task: Task) => Gantt.getBarYCoordinate(task.index, taskConfigHeight)
+ Gantt.getResourceLabelYOffset(taskConfigHeight, taskResourceFontSize, taskResourcePosition)
+ (task.index + 1) * this.getResourceLabelTopMargin())
.text((task: Task) => _.isEmpty(task.Milestones) && task.resource || "")
.style("fill", taskResourceColor)
.style("font-size", PixelConverter.fromPoint(taskResourceFontSize));
let self: Gantt = this;
let hasNotNullableDates: boolean = this.hasNotNullableDates;
const defaultWidth: number = Gantt.DefaultValues.ResourceWidth - Gantt.ResourceWidthPadding;
if (taskResourceWidthByTask) {
taskResourceMerged
.each(function (task: Task, outerIndex: number) {
const width: number = hasNotNullableDates ? self.taskDurationToWidth(task.start, task.end) : 0;
AxisHelper.LabelLayoutStrategy.clip(d3.select(this), width, textMeasurementService.svgEllipsis);
});
} else if (isGroupedByTaskName) {
taskResourceMerged
.each(function (task: Task, outerIndex: number) {
const sameRowNextTaskStart: Date = self.getSameRowNextTaskStartDate(task, outerIndex, taskResourceMerged);
if (sameRowNextTaskStart) {
let width: number = 0;
if (hasNotNullableDates) {
const startDate: Date = taskResourcePosition === ResourceLabelPositions.Top ? task.start : task.end;
width = self.taskDurationToWidth(startDate, sameRowNextTaskStart);
}
AxisHelper.LabelLayoutStrategy.clip(d3.select(this), width, textMeasurementService.svgEllipsis);
} else {
if (!taskResourceFullText) {
AxisHelper.LabelLayoutStrategy.clip(d3.select(this), defaultWidth, textMeasurementService.svgEllipsis);
}
}
});
} else if (!taskResourceFullText) {
taskResourceMerged
.each(function (task: Task, outerIndex: number) {
AxisHelper.LabelLayoutStrategy.clip(d3.select(this), defaultWidth, textMeasurementService.svgEllipsis);
});
}
taskResource
.exit()
.remove();
} else {
taskSelection
.selectAll(Selectors.TaskResource.selectorName)
.remove();
}
}
private getSameRowNextTaskStartDate(task: Task, index: number, selection: Selection<Task>) {
let sameRowNextTaskStart: Date;
selection
.each(function (x: Task, i: number) {
if (index !== i &&
x.index === task.index &&
x.start >= task.start &&
(!sameRowNextTaskStart || sameRowNextTaskStart < x.start)) {
sameRowNextTaskStart = x.start;
}
});
return sameRowNextTaskStart;
}
private static getResourceLabelYOffset(
taskConfigHeight: number,
taskResourceFontSize: number,
taskResourcePosition: ResourceLabelPositions): number {
const barHeight: number = Gantt.getBarHeight(taskConfigHeight);
switch (taskResourcePosition) {
case ResourceLabelPositions.Right:
return (barHeight / Gantt.DeviderForCalculatingCenter) + (taskResourceFontSize / Gantt.DeviderForCalculatingCenter);
case ResourceLabelPositions.Top:
return -(taskResourceFontSize / Gantt.DeviderForCalculatingPadding) + Gantt.LabelTopOffsetForPadding;
case ResourceLabelPositions.Inside:
return -(taskResourceFontSize / Gantt.DeviderForCalculatingPadding) + Gantt.LabelTopOffsetForPadding + barHeight / Gantt.ResourceLabelDefaultDivisionCoefficient;
}
}
private getResourceLabelXCoordinate(
task: Task,
taskConfigHeight: number,
taskResourceFontSize: number,
taskResourcePosition: ResourceLabelPositions): number {
if (!this.hasNotNullableDates) {
return 0;
}
const barHeight: number = Gantt.getBarHeight(taskConfigHeight);
switch (taskResourcePosition) {
case ResourceLabelPositions.Right:
return this.timeScale(task.end) + (taskResourceFontSize / 2) + Gantt.RectRound;
case ResourceLabelPositions.Top:
return this.timeScale(task.start) + Gantt.RectRound;
case ResourceLabelPositions.Inside:
return this.timeScale(task.start) + barHeight / (2 * Gantt.ResourceLabelDefaultDivisionCoefficient) + Gantt.RectRound;
}
}
/**
* Returns the matching Y coordinate for a given task index
* @param taskIndex Task Number
*/
private getTaskLabelCoordinateY(taskIndex: number): number {
const settings = this.viewModel.settings;
const fontSize: number = + settings.taskLabels.fontSize;
const taskConfigHeight = settings.taskConfig.height || DefaultChartLineHeight;
const taskYCoordinate = taskConfigHeight * taskIndex;
const barHeight = Gantt.getBarHeight(taskConfigHeight);
return taskYCoordinate + (barHeight + Gantt.BarHeightMargin - (taskConfigHeight - fontSize) / Gantt.ChartLineHeightDivider);
}
/**
* Get completion percent when days off feature is on
* @param task All task attributes
* @param durationUnit unit Duration unit
*/
private getDaysOffTaskProgressPercent(task: Task) {
if (this.viewModel.settings.daysOff.show) {
if (task.daysOffList && task.daysOffList.length && task.duration && task.completion) {
let durationUnit: string = this.viewModel.settings.general.durationUnit;
if (task.wasDowngradeDurationUnit) {
durationUnit = DurationHelper.downgradeDurationUnit(durationUnit, task.duration);
}
const startTime: number = task.start.getTime();
const progressLength: number = (task.end.getTime() - startTime) * task.completion;
const currentProgressTime: number = new Date(startTime + progressLength).getTime();
let daysOffFiltered: DayOffData[] = task.daysOffList
.filter((date) => startTime <= date[0].getTime() && date[0].getTime() <= currentProgressTime);
let extraDuration = Gantt.calculateExtraDurationDaysOff(daysOffFiltered, task.end, task.start, +this.viewModel.settings.daysOff.firstDayOfWeek, durationUnit);
const extraDurationPercentage = extraDuration / task.duration;
return task.completion + extraDurationPercentage;
}
}
return task.completion;
}
/**
* Get bar y coordinate
* @param lineNumber Line number that represents the task number
* @param lineHeight Height of task line
*/
private static getBarYCoordinate(
lineNumber: number,
lineHeight: number): number {
return (lineHeight * lineNumber) + PaddingTasks;
}
/**
* Get bar height
* @param lineHeight The height of line
*/
private static getBarHeight(lineHeight: number): number {
return lineHeight / Gantt.ChartLineProportion;
}
/**
* Get the margin that added to task rects and task category labels
*
* depends on resource label position and resource label font size
*/
private getResourceLabelTopMargin(): number {
const isResourcesFilled: boolean = this.viewModel.isResourcesFilled;
const taskResourceShow: boolean = this.viewModel.settings.taskResource.show;
const taskResourceFontSize: number = this.viewModel.settings.taskResource.fontSize;
const taskResourcePosition: ResourceLabelPositions = this.viewModel.settings.taskResource.position;
let margin: number = 0;
if (isResourcesFilled && taskResourceShow && taskResourcePosition === ResourceLabelPositions.Top) {
margin = Number(taskResourceFontSize) + Gantt.LabelTopOffsetForPadding;
}
return margin;
}
/**
* convert task duration to width in the time scale
* @param start The start of task to convert
* @param end The end of task to convert
*/
private taskDurationToWidth(
start: Date,
end: Date): number {
return this.timeScale(end) - this.timeScale(start);
}
private static getTooltipForMilestoneLine(
formattedDate: string,
localizationManager: ILocalizationManager,
dateTypeSettings: DateTypeSettings,
milestoneTitle: string[] | LabelsForDateTypes[], milestoneCategoryName?: string[]): VisualTooltipDataItem[] {
let result: VisualTooltipDataItem[] = [];
for (let i = 0; i < milestoneTitle.length; i++) {
if (!milestoneTitle[i]) {
switch (dateTypeSettings.type) {
case DateTypes.Second:
case DateTypes.Minute:
case DateTypes.Hour:
milestoneTitle[i] = localizationManager.getDisplayName("Visual_Label_Now");
break;
default:
milestoneTitle[i] = localizationManager.getDisplayName("Visual_Label_Today");
}
}
if (milestoneCategoryName) {
result.push({
displayName: localizationManager.getDisplayName("Visual_Milestone_Name"),
value: milestoneCategoryName[i]
});
}
result.push({
displayName: <string>milestoneTitle[i],
value: formattedDate
});
}
return result;
}
/**
* Create vertical dotted line that represent milestone in the time axis (by default it shows not time)
* @param tasks All tasks array
* @param milestoneTitle
* @param timestamp the milestone to be shown in the time axis (default Date.now())
*/
private createMilestoneLine(
tasks: GroupedTask[],
timestamp: number = Date.now(),
milestoneTitle?: string): void {
if (!this.hasNotNullableDates) {
return;
}
let todayColor: string = this.viewModel.settings.dateType.todayColor;
// TODO: add not today milestones color
let milestoneDates = [new Date(timestamp)];
tasks.forEach((task: GroupedTask) => {
const subtasks: Task[] = task.tasks;
subtasks.forEach((task: Task) => {
if (!_.isEmpty(task.Milestones)) {
task.Milestones.forEach((milestone) => {
if (!_.includes(milestoneDates, milestone.start)) {
milestoneDates.push(milestone.start);
}
});
}
});
});
let line: Line[] = [];
const dateTypeSettings: DateTypeSettings = this.viewModel.settings.dateType;
milestoneDates.forEach((date: Date) => {
const title = date === this.timeScale(timestamp) ? milestoneTitle : "Milestone";
const lineOptions = {
x1: this.timeScale(date),
y1: Gantt.MilestoneTop,
x2: this.timeScale(date),
y2: this.getMilestoneLineLength(tasks.length),
tooltipInfo: Gantt.getTooltipForMilestoneLine(date.toLocaleDateString(), this.localizationManager, dateTypeSettings, [title])
};
line.push(lineOptions);
});
let chartLineSelection: Selection<Line> = this.chartGroup
.selectAll(Selectors.ChartLine.selectorName)
.data(line);
const chartLineSelectionMerged = chartLineSelection
.enter()
.append("line")
.merge(chartLineSelection);
chartLineSelectionMerged.classed(Selectors.ChartLine.className, true);
chartLineSelectionMerged
.attr("x1", (line: Line) => line.x1)
.attr("y1", (line: Line) => line.y1)
.attr("x2", (line: Line) => line.x2)
.attr("y2", (line: Line) => line.y2)
.style("stroke", (line: Line) => {
let color = line.x1 === this.timeScale(timestamp) ? todayColor : Gantt.DefaultValues.MilestoneLineColor;
return this.colorHelper.getHighContrastColor("foreground", color);
});
this.renderTooltip(chartLineSelectionMerged);
chartLineSelection
.exit()
.remove();
}
private scrollToMilestoneLine(axisLength: number,
timestamp: number = Date.now()): void {
let scrollValue = this.timeScale(new Date(timestamp));
scrollValue -= scrollValue > ScrollMargin
? ScrollMargin
: 0;
if (axisLength > scrollValue) {
(this.body.node() as SVGSVGElement)
.querySelector(Selectors.Body.selectorName).scrollLeft = scrollValue;
}
}
private renderTooltip(selection: Selection<Line | Task | MilestonePath>): void {
this.tooltipServiceWrapper.addTooltip(
selection,
(tooltipEvent: TooltipEventArgs<TooltipEnabledDataPoint>) => {
return tooltipEvent.data.tooltipInfo;
});
}
private updateElementsPositions(margin: IMargin): void {
let settings = this.viewModel.settings;
const taskLabelsWidth: number = settings.taskLabels.show
? settings.taskLabels.width
: 0;
let translateXValue = taskLabelsWidth + margin.left + Gantt.SubtasksLeftMargin;
this.chartGroup
.attr("transform", SVGManipulations.translate(translateXValue, margin.top));
let translateYValue = Gantt.TaskLabelsMarginTop + (this.ganttDiv.node() as SVGSVGElement).scrollTop;
this.axisGroup
.attr("transform", SVGManipulations.translate(translateXValue, translateYValue));
translateXValue = (this.ganttDiv.node() as SVGSVGElement).scrollLeft;
this.lineGroup
.attr("transform", SVGManipulations.translate(translateXValue, 0));
this.collapseAllGroup
.attr("transform", SVGManipulations.translate(0, margin.top / 4));
}
private getMilestoneLineLength(numOfTasks: number): number {
return numOfTasks * ((this.viewModel.settings.taskConfig.height || DefaultChartLineHeight) + (1 + numOfTasks) * this.getResourceLabelTopMargin() / 2);
}
public static downgradeDurationUnitIfNeeded(tasks: Task[], durationUnit: string) {
const downgradedDurationUnitTasks = tasks.filter(t => t.wasDowngradeDurationUnit);
if (downgradedDurationUnitTasks.length) {
let maxStepDurationTransformation: number = 0;
downgradedDurationUnitTasks.forEach(x => maxStepDurationTransformation = x.stepDurationTransformation > maxStepDurationTransformation ? x.stepDurationTransformation : maxStepDurationTransformation);
tasks.filter(x => x.stepDurationTransformation !== maxStepDurationTransformation).forEach(task => {
task.duration = DurationHelper.transformDuration(task.duration, durationUnit, maxStepDurationTransformation);
task.stepDurationTransformation = maxStepDurationTransformation;
task.wasDowngradeDurationUnit = true;
});
}
}
public enumerateObjectInstances(options: EnumerateVisualObjectInstancesOptions): VisualObjectInstanceEnumeration {
const settings: GanttSettings = this.viewModel && this.viewModel.settings
|| GanttSettings.getDefault() as GanttSettings;
const instanceEnumeration: VisualObjectInstanceEnumeration =
GanttSettings.enumerateObjectInstances(settings, options);
if (options.objectName === Gantt.MilestonesPropertyIdentifier.objectName) {
this.enumerateMilestones(instanceEnumeration);
}
if (options.objectName === Gantt.LegendPropertyIdentifier.objectName) {
this.enumerateLegend(instanceEnumeration);
}
if (options.objectName === Gantt.CollapsedTasksPropertyIdentifier.objectName) {
return;
}
if (!this.viewModel.isResourcesFilled && options.objectName === Gantt.TaskResourcePropertyIdentifier.objectName) {
return;
}
return (instanceEnumeration as VisualObjectInstanceEnumerationObject).instances || [];
}
private enumerateMilestones(instanceEnumeration: VisualObjectInstanceEnumeration): VisualObjectInstance[] {
if (this.viewModel && !this.viewModel.isDurationFilled && !this.viewModel.isEndDateFillled) {
return;
}
const dataPoints: MilestoneDataPoint[] = this.viewModel && this.viewModel.milestonesData.dataPoints;
if (!dataPoints || !dataPoints.length) {
return;
}
const milestonesWithoutDublicates = Gantt.getUniqueMilestones(dataPoints);
for (let uniqMilestones in milestonesWithoutDublicates) {
const milestone = milestonesWithoutDublicates[uniqMilestones];
this.addAnInstanceToEnumeration(instanceEnumeration, {
displayName: `${milestone.name} color`,
objectName: Gantt.MilestonesPropertyIdentifier.objectName,
selector: ColorHelper.normalizeSelector((milestone.identity as ISelectionId).getSelector(), false),
properties: {
fill: { solid: { color: milestone.color } }
}
});
this.addAnInstanceToEnumeration(instanceEnumeration, {
displayName: `${milestone.name} shape`,
objectName: Gantt.MilestonesPropertyIdentifier.objectName,
selector: ColorHelper.normalizeSelector((milestone.identity as ISelectionId).getSelector(), false),
properties: { shapeType: milestone.shapeType }
});
}
}
private enumerateLegend(instanceEnumeration: VisualObjectInstanceEnumeration): VisualObjectInstance[] {
if (this.viewModel && !this.viewModel.isDurationFilled && !this.viewModel.isEndDateFillled) {
return;
}
const dataPoints: LegendDataPoint[] = this.viewModel && this.viewModel.legendData.dataPoints;
if (!dataPoints || !dataPoints.length) {
return;
}
dataPoints.forEach((dataPoint: LegendDataPoint) => {
this.addAnInstanceToEnumeration(instanceEnumeration, {
displayName: dataPoint.label,
objectName: Gantt.LegendPropertyIdentifier.objectName,
selector: ColorHelper.normalizeSelector((dataPoint.identity as ISelectionId).getSelector(), false),
properties: {
fill: { solid: { color: dataPoint.color } }
}
});
});
}
private addAnInstanceToEnumeration(
instanceEnumeration: VisualObjectInstanceEnumeration,
instance: VisualObjectInstance): void {
if ((instanceEnumeration as VisualObjectInstanceEnumerationObject).instances) {
(instanceEnumeration as VisualObjectInstanceEnumerationObject)
.instances
.push(instance);
} else {
(instanceEnumeration as VisualObjectInstance[]).push(instance);
}
}
} | the_stack |
import * as React from "react";
import { getViewer, getFusionRoot } from "../api/runtime";
import { tr as xlate, tr } from "../api/i18n";
import { RuntimeMap } from "../api/contracts/runtime-map";
import {
GenericEvent,
IMapView,
IConfigurationReducerState,
IExternalBaseLayer,
IMapViewer,
Size
} from "../api/common";
import { MapCapturerContext, IMapCapturerContextCallback } from "./map-capturer-context";
import { Slider, Button, Intent, Callout, HTMLSelect } from '@blueprintjs/core';
import { useActiveMapName, useActiveMapView, useActiveMapExternalBaseLayers, useViewerLocale, useAvailableMaps, usePrevious } from './hooks';
import { setViewRotation, setViewRotationEnabled } from '../actions/map';
import { debug } from '../utils/logger';
import { useActiveMapState } from './hooks-mapguide';
import { useReduxDispatch } from "../components/map-providers/context";
function getMargin() {
/*
var widget = getParent().Fusion.getWidgetsByType("QuickPlot")[0];
var margin;
if(!!widget.margin){
margin = widget.margin;
}else{
//the default margin
margin = {top: 25.4, buttom: 12.7, left: 12.7, right: 12.7};
}
return margin;
*/
return { top: 25.4, buttom: 12.7, left: 12.7, right: 12.7 };
}
function getPrintSize(viewer: IMapViewer, showAdvanced: boolean, paperSize: string, orientation: "P" | "L"): Size {
const value = paperSize.split(",");
let size: Size;
if (orientation === "P") {
size = { w: parseFloat(value[0]), h: parseFloat(value[1]) };
} else {
size = { w: parseFloat(value[1]), h: parseFloat(value[0]) };
}
if (!showAdvanced) {
// Calculate the paper size to make sure it has a same ratio with the viweport
const paperRatio = size.w / size.h;
var viewSize = viewer.getSize();
let vs: Size | undefined;
if (orientation === "P") {
vs = {
w: viewSize[1],
h: viewSize[0]
};
} else {
vs = {
w: viewSize[0],
h: viewSize[1]
};
}
if (vs) {
const viewRatio = vs.w / vs.h;
if (paperRatio > viewRatio) {
size.w = size.h * viewRatio;
} else {
size.h = size.w / viewRatio;
}
}
}
const margins = getMargin();
size.h = size.h - margins.top - margins.buttom;
size.w = size.w - margins.left - margins.right;
return size;
}
const _mapCapturers: MapCapturerContext[] = [];
function getActiveCapturer(viewer: IMapViewer, mapNames: string[], activeMapName: string): MapCapturerContext | undefined {
let activeCapturer: MapCapturerContext | undefined;
if (_mapCapturers.length == 0) {
if (mapNames.length) {
for (const mapName of mapNames) {
const context = new MapCapturerContext(viewer, mapName);
_mapCapturers.push(context);
if (activeMapName == mapName) {
activeCapturer = context;
}
}
}
} else {
activeCapturer = _mapCapturers.filter(m => m.getMapName() === activeMapName)[0];
}
return activeCapturer;
}
function toggleMapCapturerLayer(locale: string,
mapNames: string[] | undefined,
activeMapName: string,
showAdvanced: boolean,
paperSize: string,
orientation: "P" | "L",
scale: string,
rotation: number,
updateBoxCoords: (box: string, normalizedBox: string) => void,
setViewRotationEnabled: (flag: boolean) => void,
setViewRotation: (rot: number) => void) {
const bVisible: boolean = showAdvanced;
const viewer = getViewer();
if (viewer && mapNames) {
const activeCapturer = getActiveCapturer(viewer, mapNames, activeMapName);
if (activeCapturer) {
if (bVisible) {
const ppSize = getPrintSize(viewer, showAdvanced, paperSize, orientation);
const cb: IMapCapturerContextCallback = {
updateBoxCoords
}
activeCapturer.activate(cb, ppSize, parseFloat(scale), rotation);
//For simplicity, reset rotation to 0 and prevent the ability to rotate while the map capture box
//is active
setViewRotationEnabled(false);
setViewRotation(0);
viewer.toastPrimary("info-sign", tr("QUICKPLOT_BOX_INFO", locale));
} else {
activeCapturer.deactivate();
setViewRotationEnabled(true);
}
}
}
}
export interface IQuickPlotContainerOwnProps {
}
export interface IQuickPlotContainerConnectedState {
config: IConfigurationReducerState;
map: RuntimeMap;
view: IMapView;
externalBaseLayers: IExternalBaseLayer[];
mapNames: string[];
}
export interface IQuickPlotContainerDispatch {
setViewRotation: (rotation: number) => void;
setViewRotationEnabled: (enabled: boolean) => void;
}
export interface IQuickPlotContainerState {
title: string;
subTitle: string;
showLegend: boolean;
showNorthBar: boolean;
showCoordinates: boolean;
showScaleBar: boolean;
showDisclaimer: boolean;
showAdvanced: boolean;
orientation: "P" | "L";
paperSize: string;
scale: string;
dpi: string;
rotation: number;
box: string;
normalizedBox: string;
}
export const QuickPlotContainer = () => {
const [title, setTitle] = React.useState(""); ``
const [subTitle, setSubTitle] = React.useState("");
const [showLegend, setShowLegend] = React.useState(false);
const [showNorthBar, setShowNorthBar] = React.useState(false);
const [showCoordinates, setShowCoordinates] = React.useState(false);
const [showScaleBar, setShowScaleBar] = React.useState(false);
const [showDisclaimer, setShowDisclaimer] = React.useState(false);
const [showAdvanced, setShowAdvanced] = React.useState(false);
const [orientation, setOrientation] = React.useState<"L" | "P">("P");
const [paperSize, setPaperSize] = React.useState("210.0,297.0,A4");
const [scale, setScale] = React.useState("5000");
const [dpi, setDpi] = React.useState("96");
const [rotation, setRotation] = React.useState(0);
const [box, setBox] = React.useState("");
const [normalizedBox, setNormalizedBox] = React.useState("");
const locale = useViewerLocale();
const activeMapName = useActiveMapName();
const mapNames = useAvailableMaps()?.map(m => m.value);
const map = useActiveMapState();
const view = useActiveMapView();
const externalBaseLayers = useActiveMapExternalBaseLayers(false);
const dispatch = useReduxDispatch();
const setViewRotationAction = (rotation: number) => dispatch(setViewRotation(rotation));
const setViewRotationEnabledAction = (enabled: boolean) => dispatch(setViewRotationEnabled(enabled));
const onTitleChanged = (e: GenericEvent) => {
setTitle(e.target.value);
};
const onSubTitleChanged = (e: GenericEvent) => {
setSubTitle(e.target.value);
};
const onShowLegendChanged = () => {
setShowLegend(!showLegend);
};
const onShowNorthArrowChanged = () => {
setShowNorthBar(!showNorthBar);
};
const onShowCoordinatesChanged = () => {
setShowCoordinates(!showCoordinates);
};
const onShowScaleBarChanged = () => {
setShowScaleBar(!showScaleBar);
};
const onShowDisclaimerChanged = () => {
setShowDisclaimer(!showDisclaimer);
};
const onDpiChanged = (e: GenericEvent) => {
setDpi(e.target.value);
};
const onAdvancedOptionsChanged = () => {
setShowAdvanced(!showAdvanced);
};
const onScaleChanged = (e: GenericEvent) => {
setScale(e.target.value);
};
const onPaperSizeChanged = (e: GenericEvent) => {
setPaperSize(e.target.value);
};
const onOrientationChanged = (e: GenericEvent) => {
setOrientation(e.target.value);
};
const onRotationChanged = (value: number) => {
setRotation(value);
};
const onGeneratePlot = () => { };
const updateBoxCoords = (box: string, normalizedBox: string): void => {
setBox(box);
setNormalizedBox(normalizedBox);
};
//Side-effect that emulates the old componentWillUnmount lifecyle method to tear down
//the active map capturer
React.useEffect(() => {
return () => {
//Tear down all active capture box layers
const viewer = getViewer();
if (viewer && mapNames) {
for (const activeMapName of mapNames) {
const activeCapturer = getActiveCapturer(viewer, mapNames, activeMapName);
if (activeCapturer) {
debug(`De-activating map capturer for: ${activeMapName}`);
activeCapturer.deactivate();
}
}
}
};
}, []);
//Although the dep array arg of React.useEffect() has effectively rendered the need to
//track previous values obsolete, we still need to track the previous advanced flag to
//verify that the flag is amongst the actual values in the dep array that has changed
const prevShowAdvanced = usePrevious(showAdvanced);
//Side-effect that toggles/updates associated map capturers
React.useEffect(() => {
if (activeMapName && mapNames) {
if (showAdvanced != prevShowAdvanced) {
toggleMapCapturerLayer(locale,
mapNames,
activeMapName,
showAdvanced,
paperSize,
orientation,
scale,
rotation,
updateBoxCoords,
setViewRotationEnabledAction,
setViewRotationAction);
}
if (showAdvanced) {
const v = getViewer();
if (v) {
const capturer = getActiveCapturer(v, mapNames, activeMapName);
if (capturer) {
const ppSize = getPrintSize(v, showAdvanced, paperSize, orientation);
debug(`Updating map capturer for: ${activeMapName}`);
capturer.updateBox(ppSize, parseFloat(scale), rotation);
}
}
}
}
}, [mapNames, activeMapName, showAdvanced, scale, paperSize, orientation, rotation, locale]);
const viewer = getViewer();
if (!viewer || !map || !view) {
return <noscript />;
}
let hasExternalBaseLayers = false;
if (externalBaseLayers) {
hasExternalBaseLayers = externalBaseLayers.length > 0;
}
let normBox = normalizedBox;
let theBox = box;
if (!showAdvanced) {
const extent = viewer.getCurrentExtent();
theBox = `${extent[0]}, ${extent[1]}, ${extent[2]}, ${extent[1]}, ${extent[2]}, ${extent[3]}, ${extent[0]}, ${extent[3]}, ${extent[0]}, ${extent[1]}`;
normBox = theBox;
}
let ppSize: string;
let prSize: string;
const tokens = paperSize.split(",");
if (orientation === "L") {
prSize = `${tokens[1]},${tokens[0]}`;
ppSize = `${prSize},${tokens[2]}`;
} else { // P
prSize = `${tokens[0]},${tokens[1]}`;
ppSize = `${prSize},${tokens[2]}`;
}
const url = `${getFusionRoot()}/widgets/QuickPlot/PlotAsPDF.php`
return <div className="component-quick-plot">
<form id="Form1" name="Form1" target="_blank" method="post" action={url}>
<input type="hidden" id="printId" name="printId" value={`${Math.random() * 1000}`} />
<div className="Title FixWidth">{xlate("QUICKPLOT_HEADER", locale)}</div>
<label className="bp3-label">
{xlate("QUICKPLOT_TITLE", locale)}
<input type="text" className="bp3-input bp3-fill" dir="auto" name="{field:title}" id="title" maxLength={100} value={title} onChange={onTitleChanged} />
</label>
<label className="bp3-label">
{xlate("QUICKPLOT_SUBTITLE", locale)}
<input type="text" className="bp3-input bp3-fill" dir="auto" name="{field:sub_title}" id="subtitle" maxLength={100} value={subTitle} onChange={onSubTitleChanged} />
</label>
<label className="bp3-label">
{xlate("QUICKPLOT_PAPER_SIZE", locale)}
<div className="bp3-select bp3-fill">
{/*
The pre-defined paper size list. The value for each "option" item is in this format: [width,height]. The unit is in millimeter.
We can change the html code to add more paper size or remove some ones.
*/}
<HTMLSelect className="FixWidth" id="paperSizeSelect" name="paperSizeSelect" value={paperSize} onChange={onPaperSizeChanged}>
<option value="210.0,297.0,A4">A4 (210x297 mm; 8.27x11.69 In) </option>
<option value="297.0,420.0,A3">A3 (297x420 mm; 11.69x16.54 In) </option>
<option value="148.0,210.0,A5">A5 (148x210 mm; 5.83x8.27 in) </option>
<option value="216.0,279.0,Letter">Letter (216x279 mm; 8.50x11.00 In) </option>
<option value="216.0,356.0,Legal">Legal (216x356 mm; 8.50x14.00 In) </option>
</HTMLSelect>
</div>
</label>
<label className="bp3-label">
{xlate("QUICKPLOT_ORIENTATION", locale)}
{/*
The pre-defined paper orientations
*/}
<div className="bp3-select bp3-fill">
<HTMLSelect className="FixWidth" id="orientation" name="orientation" value={orientation} onChange={onOrientationChanged}>
<option value="P">{xlate("QUICKPLOT_ORIENTATION_P", locale)}</option>
<option value="L">{xlate("QUICKPLOT_ORIENTATION_L", locale)}</option>
</HTMLSelect>
</div>
</label>
<input type="hidden" id="paperSize" name="paperSize" value={ppSize} />
<input type="hidden" id="printSize" name="printSize" value={prSize} />
<fieldset>
<legend>{xlate("QUICKPLOT_SHOWELEMENTS", locale)}</legend>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="ShowLegendCheckBox" name="ShowLegend" checked={showLegend} onChange={onShowLegendChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_SHOWLEGEND", locale)}
</label>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="ShowNorthArrowCheckBox" name="ShowNorthArrow" checked={showNorthBar} onChange={onShowNorthArrowChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_SHOWNORTHARROW", locale)}
</label>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="ShowCoordinatesCheckBox" name="ShowCoordinates" checked={showCoordinates} onChange={onShowCoordinatesChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_SHOWCOORDINTES", locale)}
</label>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="ShowScaleBarCheckBox" name="ShowScaleBar" checked={showScaleBar} onChange={onShowScaleBarChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_SHOWSCALEBAR", locale)}
</label>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="ShowDisclaimerCheckBox" name="ShowDisclaimer" checked={showDisclaimer} onChange={onShowDisclaimerChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_SHOWDISCLAIMER", locale)}
</label>
</fieldset>
<div className="HPlaceholder5px"></div>
<div>
<label className="bp3-control bp3-checkbox">
<input type="checkbox" id="AdvancedOptionsCheckBox" onChange={onAdvancedOptionsChanged} />
<span className="bp3-control-indicator" />
{xlate("QUICKPLOT_ADVANCED_OPTIONS", locale)}
</label>
</div>
{(() => {
if (showAdvanced) {
return <div>
<label className="bp3-label">
{xlate("QUICKPLOT_SCALING", locale)}
{/*
The pre-defined scales. The value for each "option" item is the scale denominator.
We can change the html code to extend the pre-defined scales
*/}
<div className="bp3-select bp3-fill">
<HTMLSelect className="FixWidth" id="scaleDenominator" name="scaleDenominator" value={scale} onChange={onScaleChanged}>
<option value="500">1: 500</option>
<option value="1000">1: 1000</option>
<option value="2500">1: 2500</option>
<option value="5000">1: 5000</option>
</HTMLSelect>
</div>
</label>
<label className="bp3-label">
{xlate("QUICKPLOT_DPI", locale)}
{/*
The pre-defined print DPI.
We can change the html code to extend the pre-defined values
*/}
<div className="bp3-select bp3-fill">
<HTMLSelect className="FixWidth" id="dpi" name="dpi" value={dpi} onChange={onDpiChanged}>
<option value="96">96</option>
<option value="150">150</option>
<option value="300">300</option>
<option value="600">600</option>
</HTMLSelect>
</div>
</label>
<label className="bp3-label noselect">
{xlate("QUICKPLOT_BOX_ROTATION", locale)}
<div style={{ paddingLeft: 16, paddingRight: 16 }}>
<Slider min={0} max={360} labelStepSize={90} stepSize={1} value={rotation} onChange={onRotationChanged} />
</div>
</label>
</div>;
} else {
return <div>
<input type="hidden" id="scaleDenominator" name="scaleDenominator" value={`${view.scale}`} />
<input type="hidden" id="dpi" name="dpi" value={dpi} />
</div>;
}
})()}
<div className="HPlaceholder5px"></div>
{(() => {
if (hasExternalBaseLayers) {
return <Callout intent={Intent.PRIMARY} icon="info-sign">
{xlate("QUICKPLOT_COMMERCIAL_LAYER_WARNING", locale)}
</Callout>;
}
})()}
<div className="ButtonContainer FixWidth">
<Button type="submit" intent={Intent.PRIMARY} icon="print" onClick={onGeneratePlot}>{xlate("QUICKPLOT_GENERATE", locale)}</Button>
</div>
<input type="hidden" id="margin" name="margin" />
<input type="hidden" id="normalizedBox" name="normalizedBox" value={normBox} />
<input type="hidden" id="rotation" name="rotation" value={-(rotation || 0)} />
<input type="hidden" id="sessionId" name="sessionId" value={map.SessionId} />
<input type="hidden" id="mapName" name="mapName" value={map.Name} />
<input type="hidden" id="box" name="box" value={theBox} />
<input type="hidden" id="legalNotice" name="legalNotice" />
</form>
</div>;
} | the_stack |
import {
DocumentReference,
DocumentSnapshot,
QueryDocumentSnapshot,
QuerySnapshot,
Timestamp,
Transaction,
} from "@google-cloud/firestore";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import config from "./config";
import { Constants } from "./constants";
import * as logs from "./logs";
import {
DocumentPaths,
filterObjectFields,
isDeletionEventType,
isValidDocumentId,
isValidDocumentName,
objectNameToFirestorePaths,
pathHash,
shouldMirrorObject,
mirrorDocumentPathToTombstonePath,
} from "./util";
// Firestore Document Data for a Document that represents a GCS Object.
interface ItemDocument {
lastEvent: Timestamp;
// The Object's Metadata, some fields are converted to Timestamp or number types.
gcsMetadata: any;
}
// Firestore Document Data for a Document that represents a GCS Object Prefix which may have further Items or
// Prefixes nested underneath in subcollections.
interface PrefixDocument {
lastEvent: Timestamp;
// This is used to figure out whether this Prefix needs to be checked for deletion when it's reference is deleted.
// Stored as a MD5 Hash of the Child reference path to obscure names in the path to this Document.
childRef: string;
}
// Firestore Document Data for the Document created when an Object gets deleted, this is stored in a separate
// subcollection and is used to store the latest Timestamp to compare against skip function execution in the case of
// out-of-order function execution.
interface Tombstone {
lastEvent: Timestamp;
}
// Any Firestore Document created by this extension.
type MirrorDocument = ItemDocument | PrefixDocument | Tombstone;
/**
* Get the metadata for an object, returning undefined if the object does not exist.
* This is a wrapper around `getMetadata` that returns undefined if the error is a 404.
*
* @param objectName Path to the GCS object (without the bucket) to get metadata for.
*/
async function getCurrentMetadata(
objectName: string
): Promise<ItemDocument | undefined> {
try {
const [gcsMetadata, _] = await admin
.storage()
.bucket(config.bucket!)
.file(objectName)
.getMetadata();
return firestoreDocumentData(
gcsMetadata as functions.storage.ObjectMetadata,
"google.storage.object.finalize"
) as ItemDocument;
} catch (e) {
if (e.code === 404) {
return undefined;
} else {
logs.error(e, `getting metadata for ${objectName}`);
throw e;
}
}
}
/**
* Mirror the gcs state of the given object to Firestore.
* This works by reading from GCS and Firestore and simulating an event.
* @param objectName The name of the object (without the bucket).
*/
export async function mirrorObjectPath(objectName: string): Promise<void> {
/**
* Step 1: Skip this if the path isn't valid.
* Step 2: Read the Firestore doc.
* Step 3: Read the GCS Metadata (note this needs to be done after the Firestore read to handle delete timestamps correctly).
* If they don't match, call onObjectChange.
* - If the GCS metadata doesn't exist, simulate a deletion event using the metadata from the Firestore document.
*
* Note that this function is meant to handle dropped events, not necessarily arbirary modifications.
* It is also not going to be able to called on a prefix path.
*/
if (!shouldMirrorObject(objectName)) {
return logs.skippedObject(objectName);
}
const paths = objectNameToFirestorePaths(objectName);
// Check if the generated Item Document is valid.
if (!isValidDocumentName(paths.itemPath)) {
return logs.invalidObjectName(objectName);
}
// Check if every generated Firestore Document will have a valid id.
if (!objectName.split("/").every(isValidDocumentId)) {
return logs.invalidObjectName(objectName);
}
const existingSnapshot = (await admin
.firestore()
.doc(paths.itemPath)
.get()) as DocumentSnapshot<MirrorDocument>;
const currentData = await getCurrentMetadata(objectName);
if (currentData) {
await updateFirestore(paths, currentData!, false);
} else if (existingSnapshot.exists) {
var lastEvent = new Timestamp(0, 0);
if (existingSnapshot.data()!.hasOwnProperty(Constants.lastEventField)) {
lastEvent = <Timestamp>existingSnapshot.data()![Constants.lastEventField];
}
await updateFirestore(paths, { lastEvent }, true);
} else {
logs.skippedMissingPath(objectName);
}
}
/**
* Handler for GCS Object Change events. Will validate the generated Documents before updating Firestore accordingly.
* @param object The GCS Object Metadata object.
* @param eventType The GCS Event type.
*/
export async function onObjectChange(
object: functions.storage.ObjectMetadata,
eventType: string
): Promise<void> {
const isDeletion = isDeletionEventType(eventType);
const objectName = object.name!;
if (!shouldMirrorObject(objectName)) {
return logs.skippedObject(objectName);
}
const paths = objectNameToFirestorePaths(objectName);
// Check if the generated Item Document is valid.
if (!isValidDocumentName(paths.itemPath)) {
return logs.invalidObjectName(objectName);
}
// Check if every generated Firestore Document will have a valid id.
if (!objectName.split("/").every(isValidDocumentId)) {
return logs.invalidObjectName(objectName);
}
if (isDeletion) {
// When an object is overwritten, it will fire a deletion/archive event for the original, followed by a finalize
// event for the new one. We try to avoid updating firestore for the first event, so that firestore doesn't
// temporarily show that the document doesn't exist.
const [objectExists] = await admin
.storage()
.bucket(object.bucket)
.file(objectName)
.exists();
if (objectExists) {
return logs.skippedOverwrite(objectName, eventType);
}
}
const data = firestoreDocumentData(object, eventType);
await updateFirestore(paths, data, isDeletion);
}
/**
* Update the Item Document in Firestore with the provided data and perform
* maintenance (creation/deletion) on it's Prefix Documents if necessary.
* @param paths The Item Document path and Prefix Document paths (sorted from root to the parent of the Item Document).
* @param data The data to write to the Item Document (and Prefix Documents if it is a Tombstone).
*/
async function updateFirestore(
paths: DocumentPaths,
data: MirrorDocument,
isDeletion: boolean
) {
const prefixRefs = paths.prefixPaths.map((prefixPath) =>
admin.firestore().doc(prefixPath)
);
const itemRef = admin.firestore().doc(paths.itemPath);
const references = [...prefixRefs, itemRef];
const timestamp = data[Constants.lastEventField];
let attemptNumber = 0;
return admin
.firestore()
.runTransaction(
async (t: Transaction): Promise<void> => {
attemptNumber += 1;
logs.startingTransaction(itemRef.path, attemptNumber);
// Can only write Documents after all reads have been done in the Transaction.
const docsToWrite: {
ref: DocumentReference;
data: MirrorDocument;
}[] = [];
const docsToDelete: {
ref: DocumentReference;
}[] = [];
const transactionReads: string[] = [];
// Read the Item Document and it's Tombstone under the Transaction.
const itemTombstoneRef = admin
.firestore()
.doc(mirrorDocumentPathToTombstonePath(itemRef.path));
const [itemSnapshot, itemTombstoneSnapshot] = (await Promise.all([
t.get(itemRef),
t.get(itemTombstoneRef),
])) as [DocumentSnapshot<MirrorDocument>, DocumentSnapshot<Tombstone>];
transactionReads.push(
itemSnapshot.ref.path,
itemTombstoneSnapshot.ref.path
);
if (
isStaleEvent(itemSnapshot, data, isDeletion) ||
isStaleEvent(itemTombstoneSnapshot, data, isDeletion)
) {
// Skip if the event is older than what is in Firestore.
return;
}
if (!isDeletion) {
// Write the Item Document for create/update events
docsToWrite.push({ ref: itemRef, data: data as ItemDocument });
if (itemTombstoneSnapshot.exists) {
docsToDelete.push({ ref: itemTombstoneSnapshot.ref });
}
} else {
// Tombstone the Item Document for delete/archive events
docsToWrite.push({
ref: itemTombstoneSnapshot.ref,
data: data as Tombstone,
});
if (itemSnapshot.exists) {
docsToDelete.push({ ref: itemRef });
}
}
// Move up the Prefixes from deepest to shallowest until the root.
// Read each Document and queue up the Documents that we need to modify.
for (let i = references.length - 2; i >= 0; i--) {
const prefixRef = references[i];
const prefixTombstoneRef = admin
.firestore()
.doc(mirrorDocumentPathToTombstonePath(prefixRef.path));
// Read the Prefix Document and it's Tombstone under the Transaction.
const [prefixSnapshot, prefixTombstoneSnapshot] = (await Promise.all([
t.get(prefixRef),
t.get(prefixTombstoneRef),
])) as [
DocumentSnapshot<MirrorDocument>,
DocumentSnapshot<Tombstone>
];
transactionReads.push(
prefixSnapshot.ref.path,
prefixTombstoneSnapshot.ref.path
);
const child = references[i + 1];
// Prefix Maintenance, create any Prefix Documents that need to exist, delete
// any that no longer have a child underneath it.
// A reference to an "existing" (non-Tombstone) child is kept on each Prefix
// Document, this is used to skip a Firestore query to determine whether the
// Prefix Document should be pruned when one of it's children is deleted or archived.
if (!isDeletion) {
// Prefix Maintenance for create/update events.
if (prefixTombstoneSnapshot.exists) {
docsToDelete.push({ ref: prefixTombstoneSnapshot.ref });
}
if (prefixSnapshot.exists) {
// Because we create Prefix Documents from the deepest path to shallowest, once we find a Document
// that has already been created we are guaranteed all remaining Prefix Documents also exist.
break;
}
docsToWrite.push({
ref: prefixRef,
data: {
[Constants.childRefField]: pathHash(child.path),
[Constants.lastEventField]: timestamp,
} as PrefixDocument,
});
} else {
// Prefix Maintenance for delete/archive events.
// The Prefix Document has been Tombstoned or never existed in the first place.
if (!prefixSnapshot.exists) break;
// Treat the Prefix Document as one requiring deletion if it is not what we're expecting/invalid.
else if (!isValidPrefixDocument(prefixSnapshot)) {
logs.invalidPrefixDocument(prefixSnapshot.id);
}
// If it already is a Tombstone we can stop.
else if (prefixTombstoneSnapshot.exists) break;
// This Document doesn't point to a child being deleted, can stop checking parents.
else if (
(<PrefixDocument>prefixSnapshot.data())[
Constants.childRefField
] !== pathHash(child.path)
) {
break;
}
// Reference points to Document being deleted, check if the Prefix Document should
// still exist. If it should still exist, update it's child reference.
const items = prefixRef.collection(config.itemsSubcollectionName);
const prefixes = prefixRef.collection(
config.prefixesSubcollectionName
);
const subcollections = [prefixes, items];
const childDocs: QueryDocumentSnapshot<MirrorDocument>[] = [];
// Try to find "existing" (non-Tombstone) child Documents to replace the child reference.
// A Prefix Document is preferred for the new child reference because they are less likely to be deleted.
for (let i = 0; i < subcollections.length; i++) {
const subcollection = subcollections[i];
const query = (await subcollection
.limit(Constants.queryLimit - childDocs.length)
.get()) as QuerySnapshot<MirrorDocument>;
// New child reference cannot be the old one because its being deleted.
const results = query.docs.filter(
(doc) => doc.ref.path !== child.path
);
childDocs.push(...results);
}
if (childDocs.length === 0) {
// No existing child Documents found. Add a tombstone and continue up.
// Re-using the same Tombstone object that is used to replace Item Documents.
docsToWrite.push({
ref: prefixTombstoneSnapshot.ref,
data: data as Tombstone,
});
if (prefixSnapshot.exists) {
docsToDelete.push({ ref: prefixSnapshot.ref });
}
continue;
}
let newChildPath: string | null = null;
// Find a child reference that hasn't been deleted since we ran the query and read under the transaction.
// Gets are transactional whereas the Query performed earlier was not, prevents concurrent transactions
// from deleting the document we've chosen as our new child reference before this transaction is done.
for (let i = 0; i < childDocs.length; i++) {
const newChild = childDocs[i];
const childSnapshot = (await t.get(
admin.firestore().doc(newChild.ref.path)
)) as DocumentSnapshot<MirrorDocument>;
transactionReads.push(childSnapshot.ref.path);
if (childSnapshot.exists) {
newChildPath = childSnapshot.ref.path;
break;
}
}
if (newChildPath === null) {
throw "All Query results have since been Tombstoned. Retrying transaction...";
} else {
// Update reference to the new child prefix/object under it.
docsToWrite.push({
ref: prefixRef,
data: {
[Constants.childRefField]: pathHash(newChildPath),
[Constants.lastEventField]: timestamp,
} as PrefixDocument,
});
break;
}
}
}
logs.transactionReads(transactionReads);
// Finished transaction reads. Attempt to write to each queued up document.
logs.transactionWriteAttempt(
docsToWrite.length,
docsToWrite.map((d) => d.ref.path)
);
docsToWrite.forEach((doc) => {
t.set(doc.ref, doc.data);
});
logs.transactionDeleteAttempt(
docsToDelete.length,
docsToDelete.map((d) => d.ref.path)
);
docsToDelete.forEach((doc) => {
t.delete(doc.ref);
});
},
{
maxAttempts: Constants.transactionAttempts,
}
)
.catch((reason: any) => {
logs.transactionFailure(itemRef.path, reason);
throw reason;
});
}
/**
* Returns whether an GCS event is stale based on what is currently in Firestore.
* @param existingSnapshot Current Firestore snapshot.
* @param eventData Data to write for the GCS event.
*/
export function isStaleEvent(
existingSnapshot: DocumentSnapshot,
eventData: MirrorDocument,
isDeletion: boolean
) {
// Timestamp on the incoming Firestore document.
const newDocumentTime = eventData[Constants.lastEventField];
if (existingSnapshot.exists) {
// Treat the Document as non-existent if it doesn't have a last-event field.
if (!existingSnapshot.data()!.hasOwnProperty(Constants.lastEventField)) {
logs.missingLastEventField(existingSnapshot.id);
return false;
}
const firestoreTime = <Timestamp>(
existingSnapshot.data()![Constants.lastEventField]
);
if (firestoreTime.valueOf() > newDocumentTime.valueOf()) {
logs.abortingStaleEvent(
existingSnapshot.ref.path,
newDocumentTime,
firestoreTime
);
// This event is older than what is in Firestore.
return true;
} else if (firestoreTime.isEqual(newDocumentTime) && !isDeletion) {
logs.staleTieBreak(
existingSnapshot.ref.path,
newDocumentTime,
firestoreTime
);
// Break ties in favor of deletion event taking precedence.
return true;
}
logs.eventNotStale(
existingSnapshot.ref.path,
newDocumentTime,
firestoreTime
);
return false;
}
logs.docDoesNotExist(existingSnapshot.ref.path);
return false;
}
/**
* Construct the Firestore Document fields for the Prefixes Documents & Item Document.
* @param metadata GCS metadata for the relevant object.
* @param eventType The event type.
*/
function firestoreDocumentData(
metadata: functions.storage.ObjectMetadata,
eventType: string
): MirrorDocument {
const timestamp = Timestamp.fromDate(new Date(metadata.updated));
if (isDeletionEventType(eventType)) {
// Instead of deleting Documents when the corresponding Object is deleted, replace it
// with a "Tombstone" to deal with out-of-order function execution.
return {
[Constants.lastEventField]: timestamp,
} as Tombstone;
}
const documentData: ItemDocument = {
[Constants.lastEventField]: timestamp,
[Constants.gcsMetadataField]: {},
};
const fields = filterObjectFields(metadata, config.metadataFieldFilter);
fields.forEach(({ key, value }) => {
let fieldValue: any;
if (key === Constants.objectCustomMetadataField) {
// Set custom metadata fields
fieldValue = {} as { [x: string]: any };
filterObjectFields(value, config.customMetadataFieldFilter).forEach(
({ key, value }) => {
fieldValue[key] = value;
}
);
} else if (Constants.numberFields.includes(key)) {
fieldValue = parseInt(value);
} else if (Constants.dateFields.includes(key)) {
fieldValue = new Date(value);
} else {
fieldValue = value;
}
documentData[Constants.gcsMetadataField][key] = fieldValue;
});
return documentData;
}
/**
* Returns whether a Prefix Document in Firestore has all the valid extension fields.
* @param snapshot The Firestore snapshot.
*/
function isValidPrefixDocument(
snapshot: DocumentSnapshot<MirrorDocument>
): snapshot is DocumentSnapshot<PrefixDocument> {
const fields = [Constants.lastEventField, Constants.childRefField];
for (let i = 0; i < fields.length; i++) {
const field = fields[i];
if (!snapshot.data()!.hasOwnProperty(field)) return false;
}
return true;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.